Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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+):
Expand Down
1 change: 0 additions & 1 deletion examples/postgres-restic.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ test:
WHERE nspname NOT LIKE 'pg_%'
AND nspname <> 'information_schema'
expect:
type: integer
greater_than: 0

isolation:
Expand Down
4 changes: 2 additions & 2 deletions examples/real-world/immich-real-test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 9 additions & 3 deletions internal/contract/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
24 changes: 20 additions & 4 deletions internal/contract/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
54 changes: 54 additions & 0 deletions internal/contract/validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 = &lt
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")
}
}
57 changes: 55 additions & 2 deletions internal/engines/postgres/checks.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,17 +59,33 @@ 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"
result.Err = fmt.Errorf("check has no expectation")
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 {
Expand Down Expand Up @@ -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.
//
Expand Down
84 changes: 84 additions & 0 deletions internal/engines/postgres/checks_extra_test.go
Original file line number Diff line number Diff line change
@@ -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" }
17 changes: 10 additions & 7 deletions internal/report/report.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions internal/report/template.html
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ <h2>Checks</h2>
<th>Status</th>
<th>Expected</th>
<th>Actual</th>
<th>Duration</th>
<th>Notes</th>
</tr>
</thead>
Expand All @@ -175,6 +176,7 @@ <h2>Checks</h2>
<td class="status {{statusClass .Status}}">{{.Status}}</td>
<td>{{or .Expected "-"}}</td>
<td>{{or .Actual "-"}}</td>
<td>{{formatDuration .DurationMS}}</td>
<td>{{if .Error}}<span class="error">{{.Error}}</span>{{end}}</td>
</tr>
{{end}}
Expand Down
Loading
Loading