diff --git a/README.md b/README.md index 7b47d8e..31873c3 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,42 @@ Not supported in v0.1.0: Borg, PBS, Duplicati / MySQL, MariaDB, SQLite / Kuberne Anything not in the supported list is deliberately deferred to ROADMAP.md and will not enter v0.1.0. +## SQL checks in the contract + +Each check runs a read-only query against the restored sandbox +database and compares the result to an expectation. Exactly one +expectation field per check: + +| Field | Meaning | +|----------------|------------------------------------------------------| +| `value` | actual must equal the expected value (string compare) | +| `greater_than` | actual integer must be strictly greater | +| `less_than` | actual integer must be strictly less | +| `min_length` | returned text must be at least N characters long | + +Optional `on_fail: warn` downgrades a failing check to a WARNING +instead of a hard FAIL — useful for advisory sanity bounds (e.g. +an approximate row count) that should not block an otherwise +successful recovery verification. + +```yaml +checks: + - name: asset_row_count + type: sql + query: "SELECT count(*) FROM asset" + expect: { greater_than: 100000 } + + - name: orphaned_files_bound + type: sql + query: "SELECT count(*) FROM file WHERE asset_id IS NULL" + expect: { less_than: 10 } + on_fail: warn +``` + +The drill-wide `limits.timeout` bounds the whole restore + +validation sequence; every stage and every SQL check records its +duration in the JSON and HTML reports. + ## Quick start Install directly (requires Go 1.22+): diff --git a/examples/postgres-restic.yaml b/examples/postgres-restic.yaml index 6edcafb..9f68ea9 100644 --- a/examples/postgres-restic.yaml +++ b/examples/postgres-restic.yaml @@ -44,7 +44,6 @@ test: WHERE nspname NOT LIKE 'pg_%' AND nspname <> 'information_schema' expect: - type: integer greater_than: 0 isolation: diff --git a/examples/real-world/immich-real-test.yaml b/examples/real-world/immich-real-test.yaml index b16184a..4669de0 100644 --- a/examples/real-world/immich-real-test.yaml +++ b/examples/real-world/immich-real-test.yaml @@ -36,11 +36,11 @@ test: SELECT count(*) FROM pg_namespace WHERE nspname NOT LIKE 'pg_%' AND nspname <> 'information_schema' - expect: { type: integer, greater_than: 0 } + expect: { greater_than: 0 } - name: asset_row_count type: sql query: "SELECT count(*) FROM asset" - expect: { type: integer, greater_than: 100000 } + expect: { greater_than: 100000 } isolation: network: internal diff --git a/internal/contract/types.go b/internal/contract/types.go index 06be205..ae4ce59 100644 --- a/internal/contract/types.go +++ b/internal/contract/types.go @@ -48,13 +48,19 @@ type Check struct { Type string `yaml:"type"` Query string `yaml:"query"` Expect CheckExpect `yaml:"expect"` + // OnFail controls what happens when this check fails: "fail" + // (default) marks the drill FAIL, "warn" downgrades it to a + // WARNING only. Useful for advisory checks like row-count + // sanity bounds that should not block a recovery verification. + OnFail string `yaml:"on_fail,omitempty"` } // CheckExpect describes the expected outcome of a check. type CheckExpect struct { - Value any `yaml:"value,omitempty"` - Type string `yaml:"type,omitempty"` - GreaterThan *int `yaml:"greater_than,omitempty"` + Value any `yaml:"value,omitempty"` + GreaterThan *int `yaml:"greater_than,omitempty"` + LessThan *int `yaml:"less_than,omitempty"` + MinLength *int `yaml:"min_length,omitempty"` } // Isolation describes network and sandbox isolation requirements. diff --git a/internal/contract/validator.go b/internal/contract/validator.go index 663783d..df09b83 100644 --- a/internal/contract/validator.go +++ b/internal/contract/validator.go @@ -125,11 +125,27 @@ func validateCheck(c Check) error { if strings.TrimSpace(c.Query) == "" { return errors.New("check query is required") } - if c.Expect.Value == nil && c.Expect.GreaterThan == nil { - return errors.New("check expect must define either value or greater_than") + expectFields := 0 + for _, set := range []bool{ + c.Expect.Value != nil, + c.Expect.GreaterThan != nil, + c.Expect.LessThan != nil, + c.Expect.MinLength != nil, + } { + if set { + expectFields++ + } + } + if expectFields == 0 { + return errors.New("check expect must define at least one of: value, greater_than, less_than, min_length") + } + if expectFields > 1 { + return errors.New("check expect fields are mutually exclusive (define only one)") } - if c.Expect.Value != nil && c.Expect.GreaterThan != nil { - return errors.New("check expect cannot define both value and greater_than") + switch c.OnFail { + case "", "fail", "warn": + default: + return fmt.Errorf("check on_fail must be \"fail\" or \"warn\", got %q", c.OnFail) } return nil } diff --git a/internal/contract/validator_test.go b/internal/contract/validator_test.go index 3a6b29c..3c90bf0 100644 --- a/internal/contract/validator_test.go +++ b/internal/contract/validator_test.go @@ -149,3 +149,57 @@ func TestValidate_CleanupAlwaysFalse(t *testing.T) { t.Fatal("expected error for cleanup.always=false") } } + +func TestValidate_CheckWithLessThan(t *testing.T) { + c := validContract() + c.Test.Checks[0].Expect.Value = nil + lt := 100 + c.Test.Checks[0].Expect.LessThan = < + if err := c.Validate(); err != nil { + t.Fatalf("unexpected error: %v", err) + } +} + +func TestValidate_CheckWithMinLength(t *testing.T) { + c := validContract() + c.Test.Checks[0].Expect.Value = nil + ml := 10 + c.Test.Checks[0].Expect.MinLength = &ml + if err := c.Validate(); err != nil { + t.Fatalf("unexpected error: %v", err) + } +} + +func TestValidate_CheckNoExpectation(t *testing.T) { + c := validContract() + c.Test.Checks[0].Expect = CheckExpect{} + if err := c.Validate(); err == nil { + t.Fatal("expected error for check with no expectation") + } +} + +func TestValidate_CheckThreeExpects(t *testing.T) { + c := validContract() + n := 5 + c.Test.Checks[0].Expect.GreaterThan = &n + c.Test.Checks[0].Expect.LessThan = &n + if err := c.Validate(); err == nil { + t.Fatal("expected error for check with multiple expectations") + } +} + +func TestValidate_CheckOnFailWarn(t *testing.T) { + c := validContract() + c.Test.Checks[0].OnFail = "warn" + if err := c.Validate(); err != nil { + t.Fatalf("unexpected error: %v", err) + } +} + +func TestValidate_CheckOnFailInvalid(t *testing.T) { + c := validContract() + c.Test.Checks[0].OnFail = "ignore" + if err := c.Validate(); err == nil { + t.Fatal("expected error for invalid on_fail value") + } +} diff --git a/internal/engines/postgres/checks.go b/internal/engines/postgres/checks.go index 4ac7162..efffa95 100644 --- a/internal/engines/postgres/checks.go +++ b/internal/engines/postgres/checks.go @@ -59,10 +59,16 @@ func runCheck(ctx context.Context, cli *client.Client, c *sandbox.Container, chk result.Actual = actual if chk.Expect.Value != nil { - return evaluateValue(result, chk.Expect.Value, actual), nil + return applyOnFail(evaluateValue(result, chk.Expect.Value, actual), chk), nil } if chk.Expect.GreaterThan != nil { - return evaluateGreaterThan(result, *chk.Expect.GreaterThan, actual), nil + return applyOnFail(evaluateGreaterThan(result, *chk.Expect.GreaterThan, actual), chk), nil + } + if chk.Expect.LessThan != nil { + return applyOnFail(evaluateLessThan(result, *chk.Expect.LessThan, actual), chk), nil + } + if chk.Expect.MinLength != nil { + return applyOnFail(evaluateMinLength(result, *chk.Expect.MinLength, actual), chk), nil } result.Status = "FAIL" @@ -70,6 +76,16 @@ func runCheck(ctx context.Context, cli *client.Client, c *sandbox.Container, chk return result, nil } +// applyOnFail downgrades a FAIL to WARNING when the contract marks +// the check as advisory (on_fail: warn). The error message is kept +// so the report still shows exactly what mismatched. +func applyOnFail(r engines.CheckResult, chk contract.Check) engines.CheckResult { + if r.Status == "FAIL" && chk.OnFail == "warn" { + r.Status = "WARNING" + } + return r +} + // evaluateValue compares the actual result as a string against the // expected value. func evaluateValue(result engines.CheckResult, expected any, actual string) engines.CheckResult { @@ -102,6 +118,43 @@ func evaluateGreaterThan(result engines.CheckResult, threshold int, actual strin return result } +// evaluateLessThan parses actual as an integer and compares. +func evaluateLessThan(result engines.CheckResult, threshold int, actual string) engines.CheckResult { + result.Expected = fmt.Sprintf("< %d", threshold) + n, err := strconv.Atoi(actual) + if err != nil { + result.Status = "FAIL" + result.Err = fmt.Errorf("expected integer result, got %q", actual) + return result + } + if n < threshold { + result.Status = "PASS" + } else { + result.Status = "FAIL" + result.Err = fmt.Errorf("expected value < %d, got %d", threshold, n) + } + return result +} + +// evaluateMinLength checks that the returned text is at least the +// given number of characters long. Useful for verifying a column +// actually contains non-trivial data (e.g. a JSON payload). +func evaluateMinLength(result engines.CheckResult, minLen int, actual string) engines.CheckResult { + result.Expected = fmt.Sprintf("len >= %d", minLen) + if minLen < 0 { + result.Status = "FAIL" + result.Err = fmt.Errorf("min_length must not be negative, got %d", minLen) + return result + } + if len(actual) >= minLen { + result.Status = "PASS" + } else { + result.Status = "FAIL" + result.Err = fmt.Errorf("expected length >= %d, got %d", minLen, len(actual)) + } + return result +} + // buildPSQLArgs returns the argument vector for psql. // Extracted for unit testing. // diff --git a/internal/engines/postgres/checks_extra_test.go b/internal/engines/postgres/checks_extra_test.go new file mode 100644 index 0000000..d4d655a --- /dev/null +++ b/internal/engines/postgres/checks_extra_test.go @@ -0,0 +1,84 @@ +package postgres + +import ( + "strings" + "testing" + + "github.com/techdev-lab/restorelab/internal/contract" + "github.com/techdev-lab/restorelab/internal/engines" +) + +func TestEvaluateLessThan(t *testing.T) { + cases := []struct { + name string + thr int + actual string + want string + wantErr bool + }{ + {"below", 10, "3", "PASS", false}, + {"equal is fail", 10, "10", "FAIL", true}, + {"above", 10, "11", "FAIL", true}, + {"non-integer", 10, "abc", "FAIL", true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + r := evaluateLessThan(engines.CheckResult{}, tc.thr, tc.actual) + if r.Status != tc.want { + t.Errorf("status = %s, want %s", r.Status, tc.want) + } + if (r.Err != nil) != tc.wantErr { + t.Errorf("err = %v, wantErr = %v", r.Err, tc.wantErr) + } + if !strings.HasPrefix(r.Expected, "< ") { + t.Errorf("expected label %q, want prefix \"< \"", r.Expected) + } + }) + } +} + +func TestEvaluateMinLength(t *testing.T) { + cases := []struct { + name string + minLen int + actual string + want string + }{ + {"long enough", 5, "hello world", "PASS"}, + {"exact", 5, "hello", "PASS"}, + {"too short", 5, "hey", "FAIL"}, + {"zero min always passes", 0, "", "PASS"}, + {"negative min fails", -1, "anything", "FAIL"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + r := evaluateMinLength(engines.CheckResult{}, tc.minLen, tc.actual) + if r.Status != tc.want { + t.Errorf("status = %s, want %s", r.Status, tc.want) + } + }) + } +} + +func TestApplyOnFail(t *testing.T) { + failed := engines.CheckResult{Status: "FAIL", Err: errDummy{}} + + if got := applyOnFail(failed, contract.Check{OnFail: "warn"}); got.Status != "WARNING" { + t.Errorf("on_fail=warn: status = %s, want WARNING", got.Status) + } + if got := applyOnFail(failed, contract.Check{OnFail: "fail"}); got.Status != "FAIL" { + t.Errorf("on_fail=fail: status = %s, want FAIL", got.Status) + } + if got := applyOnFail(failed, contract.Check{}); got.Status != "FAIL" { + t.Errorf("on_fail unset: status = %s, want FAIL", got.Status) + } + + passed := engines.CheckResult{Status: "PASS"} + if got := applyOnFail(passed, contract.Check{OnFail: "warn"}); got.Status != "PASS" { + t.Errorf("passing check must stay PASS, got %s", got.Status) + } +} + +type errDummy struct{} + +func (errDummy) Error() string { return "dummy" } diff --git a/internal/report/report.go b/internal/report/report.go index 1b561fa..b4c22dd 100644 --- a/internal/report/report.go +++ b/internal/report/report.go @@ -11,8 +11,10 @@ import ( "time" ) -// CurrentVersion is the report schema version. -const CurrentVersion = "1.0" +// CurrentVersion is the report schema version. 1.1 adds +// duration_ms to check results; all pre-existing fields are +// unchanged, so older consumers can still parse new reports. +const CurrentVersion = "1.1" // Status is the categorical outcome of a stage or check. type Status string @@ -36,11 +38,12 @@ type Stage struct { // Check is one SQL validation result. type Check struct { - Name string `json:"name"` - Status Status `json:"status"` - Expected string `json:"expected,omitempty"` - Actual string `json:"actual,omitempty"` - Error string `json:"error,omitempty"` + Name string `json:"name"` + Status Status `json:"status"` + Expected string `json:"expected,omitempty"` + Actual string `json:"actual,omitempty"` + Error string `json:"error,omitempty"` + DurationMS int64 `json:"duration_ms"` } // Report is the complete outcome of a single recovery drill. diff --git a/internal/report/template.html b/internal/report/template.html index cd87224..e8cfc80 100644 --- a/internal/report/template.html +++ b/internal/report/template.html @@ -165,6 +165,7 @@