ops: the box drill never counts unknown freshness as current
Spec 2026-12-03 sqlite-integrity-1 §5.2-5.3 (S2b). freshnessOK covered two things: a copy level with its source, and a copy behind a source written within staleGrace. It is now freshnessCurrent, and only a copy level with or ahead of a rollback-journal source earns it: - behind, source written within 15 minutes: unknown, "behind a write made in the last 15 minutes" (was ok); - level or ahead, source in WAL mode (header bytes 18 and 19 both 2): unknown, "WAL mode, where the change counter does not track writes" (was ok); - behind and quiet: STALE, missing source and unreadable headers: unchanged. RestoreVerify says on each line that the copy restored clean and what its freshness is, and its summary counts current and could-not-judge apart. Exit status is unchanged: non-zero only on a failed restore or STALE. The hibernate drill already maps unknown to FreshnessUnknown; new subtests pin that for both new unknowns, and its no-DBPath guard now returns unknown rather than current. Placeholder wording from spec §7, for copy review.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+276
−31
internal/ops/freshness.go+47 −12internal/ops/freshness_test.go+166 −0internal/ops/hibernate_verify.go+7 −7internal/ops/hibernate_verify_test.go+35 −0internal/ops/litestream.go+12 −5internal/ops/ops_test.go+9 −7
diff --git a/internal/ops/freshness.go b/internal/ops/freshness.go| index 48847a959..09b7f7516 100644 |
| --- a/internal/ops/freshness.go |
| +++ b/internal/ops/freshness.go |
| @@ -25,7 +25,10 @@ package ops |
| // process just read. |
| import ( |
| + "encoding/binary" |
| + "errors" |
| "fmt" |
| + "io" |
| "os" |
| "time" |
| @@ -47,24 +50,28 @@ const staleGrace = 15 * time.Minute |
| type freshness int |
| const ( |
| - // freshnessOK: the replica is level with its source, or trailing a source |
| - // that was written too recently to judge. |
| - freshnessOK freshness = iota |
| + // freshnessCurrent: the replica is level with or ahead of a source in |
| + // rollback-journal mode, whose change counter moves on every commit. The |
| + // only outcome that counts as current. |
| + freshnessCurrent freshness = iota |
| // freshnessStale: the source has been quiet for longer than staleGrace and |
| // the replica is STILL behind it. Replication is not happening. |
| freshnessStale |
| // freshnessNoSource: the config names a database that is not on disk. The |
| // replica cannot ever advance again, and nothing is watching the gap. |
| freshnessNoSource |
| - // freshnessUnknown: one of the two headers could not be read. Say so; |
| - // never let "could not tell" read as "fine". |
| + // freshnessUnknown: the comparison proves nothing either way. One of the |
| + // two headers could not be read, the source is in WAL mode (its counter |
| + // moves only at a checkpoint, so "level" is no evidence), or the replica |
| + // is behind a source written within staleGrace. Say so; never let |
| + // "could not tell" read as "fine". |
| freshnessUnknown |
| ) |
| func (f freshness) String() string { |
| switch f { |
| - case freshnessOK: |
| - return "ok" |
| + case freshnessCurrent: |
| + return "current" |
| case freshnessStale: |
| return "STALE" |
| case freshnessNoSource: |
| @@ -95,7 +102,7 @@ func replicaFreshness(srcPath, restoredPath string, srcModTime time.Time) (fresh |
| // hibernation drill, where lease.VerifyReplica reads the counter and then |
| // sweeps its throwaway copy in the same call. |
| func replicaFreshnessCounter(srcPath string, restoredCounter uint32, srcModTime time.Time) (freshness, string) { |
| - srcCounter, err := ChangeCounter(srcPath) |
| + srcCounter, wal, err := sourceHeader(srcPath) |
| if os.IsNotExist(err) { |
| return freshnessNoSource, "source database is not on disk — this replica can never advance again" |
| } |
| @@ -103,18 +110,46 @@ func replicaFreshnessCounter(srcPath string, restoredCounter uint32, srcModTime |
| return freshnessUnknown, fmt.Sprintf("source header unreadable: %v", err) |
| } |
| if restoredCounter >= srcCounter { |
| - return freshnessOK, "" |
| + if wal { |
| + // In WAL mode a commit does not move the counter; only a |
| + // checkpoint does. A copy level with it may still lack every |
| + // write since the last checkpoint. |
| + return freshnessUnknown, "WAL mode, where the change counter does not track writes" |
| + } |
| + return freshnessCurrent, "" |
| } |
| if quiet := time.Since(srcModTime); quiet <= staleGrace { |
| - // Behind, but the source was written within the grace window — this is |
| - // ordinary lag, and the next pass will judge it properly. |
| - return freshnessOK, "" |
| + // Behind, but the source was written within the grace window. That |
| + // is ordinary lag or the start of a stall, and the next pass will |
| + // judge it; either way the copy is behind, so it is not current. |
| + return freshnessUnknown, fmt.Sprintf("behind a write made in the last %d minutes", int(staleGrace/time.Minute)) |
| } |
| return freshnessStale, fmt.Sprintf( |
| "replica is at change %d, the live database at %d, and the database has been quiet since %s — replication has stopped", |
| restoredCounter, srcCounter, srcModTime.UTC().Format(time.RFC3339)) |
| } |
| +// sourceHeader reads the source database's change counter (header bytes |
| +// 24-27, as lease.ChangeCounter) and whether it is in WAL mode (header bytes |
| +// 18 and 19, the write and read versions, both 2), in one read. An error |
| +// opening the file is returned as it is, so os.IsNotExist sees it. |
| +func sourceHeader(path string) (counter uint32, wal bool, err error) { |
| + f, err := os.Open(path) |
| + if err != nil { |
| + return 0, false, err |
| + } |
| + defer f.Close() |
| + |
| + var header [28]byte |
| + if _, err := io.ReadFull(f, header[:]); err != nil { |
| + return 0, false, fmt.Errorf("read header: %w", err) |
| + } |
| + if string(header[:15]) != "SQLite format 3" { |
| + return 0, false, errors.New("not a SQLite database") |
| + } |
| + return binary.BigEndian.Uint32(header[24:28]), header[18] == 2 && header[19] == 2, nil |
| +} |
| + |
| // sourceModTime is the source database's mtime, or the zero time when it |
| // cannot be stated (which replicaFreshness will treat through its own paths). |
| func sourceModTime(path string) time.Time { |
diff --git a/internal/ops/freshness_test.go b/internal/ops/freshness_test.go| new file mode 100644 |
| index 000000000..28f55b322 |
| --- /dev/null |
| +++ b/internal/ops/freshness_test.go |
| @@ -0,0 +1,166 @@ |
| +package ops |
| + |
| +import ( |
| + "database/sql" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// writeWALCounterDB is writeCounterDB's source in WAL mode: the writes are |
| +// made with a rollback journal, so the counter is high, and then the file |
| +// is switched to WAL, which marks header bytes 18 and 19. |
| +func writeWALCounterDB(t *testing.T, path string, writes int) { |
| + t.Helper() |
| + writeCounterDB(t, path, writes) |
| + db, err := sql.Open("sqlite", path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := db.Exec("PRAGMA journal_mode=WAL"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := db.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + b, err := os.ReadFile(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(b) < 20 || b[18] != 2 || b[19] != 2 { |
| + t.Fatalf("fixture: %s is not marked WAL in its header", path) |
| + } |
| +} |
| + |
| +// Every row of the freshness table (spec §5.3): only affirmative evidence |
| +// is current. A copy behind a recently written source, and any copy of a |
| +// WAL-mode source that is not behind, could not be judged. |
| +func TestFreshnessOutcomes(t *testing.T) { |
| + dir := t.TempDir() |
| + journal := filepath.Join(dir, "journal.db") |
| + writeCounterDB(t, journal, 9) |
| + wal := filepath.Join(dir, "wal.db") |
| + writeWALCounterDB(t, wal, 9) |
| + behind := filepath.Join(dir, "behind.db") |
| + writeCounterDB(t, behind, 1) |
| + ahead := filepath.Join(dir, "ahead.db") |
| + writeCounterDB(t, ahead, 40) |
| + junk := filepath.Join(dir, "junk.db") |
| + if err := os.WriteFile(junk, []byte("nope"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + long := time.Now().Add(-2 * time.Hour) |
| + recent := time.Now() |
| + const lag = "behind a write made in the last 15 minutes" |
| + const walWhy = "WAL mode, where the change counter does not track writes" |
| + for _, c := range []struct { |
| + name, src, restored string |
| + modTime time.Time |
| + want freshness |
| + detail string // "" for any |
| + }{ |
| + {"journal, behind, quiet", journal, behind, long, freshnessStale, ""}, |
| + {"WAL, behind, quiet", wal, behind, long, freshnessStale, ""}, |
| + {"journal, behind, written recently", journal, behind, recent, freshnessUnknown, lag}, |
| + {"WAL, behind, written recently", wal, behind, recent, freshnessUnknown, lag}, |
| + {"WAL, level", wal, wal, long, freshnessUnknown, walWhy}, |
| + {"WAL, ahead", wal, ahead, long, freshnessUnknown, walWhy}, |
| + {"WAL, level, written recently", wal, wal, recent, freshnessUnknown, walWhy}, |
| + {"journal, level", journal, journal, long, freshnessCurrent, ""}, |
| + {"journal, ahead", journal, ahead, long, freshnessCurrent, ""}, |
| + {"journal, level, written recently", journal, journal, recent, freshnessCurrent, ""}, |
| + {"source missing", filepath.Join(dir, "absent.db"), behind, long, freshnessNoSource, ""}, |
| + {"source unreadable", junk, behind, long, freshnessUnknown, ""}, |
| + {"copy unreadable", journal, junk, long, freshnessUnknown, ""}, |
| + } { |
| + got, detail := replicaFreshness(c.src, c.restored, c.modTime) |
| + if got != c.want || (c.detail != "" && detail != c.detail) { |
| + t.Errorf("%s: %v (%q), want %v (%q)", c.name, got, detail, c.want, c.detail) |
| + } |
| + } |
| +} |
| + |
| +// The box drill says, for each copy, that it restored and what its |
| +// freshness is, and never counts an unknown freshness as current: the |
| +// summary says how many are current and how many could not be judged. An |
| +// unknown is no failure, so the run still exits clean, and each database is |
| +// restored once, as before. |
| +func TestRestoreVerifyUnknownIsNotCurrent(t *testing.T) { |
| + srcDir := t.TempDir() |
| + journal := filepath.Join(srcDir, "journal.db") |
| + writeCounterDB(t, journal, 3) |
| + wal := filepath.Join(srcDir, "wal.db") |
| + writeWALCounterDB(t, wal, 3) |
| + busy := filepath.Join(srcDir, "busy.db") |
| + writeCounterDB(t, busy, 1) |
| + busyCopy, err := os.ReadFile(busy) // replicated, then written again just now |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + writeCounterDB(t, busy, 5) |
| + |
| + copies := map[string][]byte{busy: busyCopy} |
| + for _, p := range []string{journal, wal} { |
| + b, err := os.ReadFile(p) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + copies[p] = b |
| + } |
| + var mu sync.Mutex |
| + restores := map[string]int{} |
| + prev := restoreAndCheckFn |
| + restoreAndCheckFn = func(_, _, dbPath, tmpDir string) error { |
| + mu.Lock() |
| + restores[dbPath]++ |
| + mu.Unlock() |
| + return os.WriteFile(filepath.Join(tmpDir, filepath.Base(dbPath)), copies[dbPath], 0o600) |
| + } |
| + t.Cleanup(func() { restoreAndCheckFn = prev }) |
| + |
| + run := func(dbs ...string) (string, error) { |
| + t.Helper() |
| + cfgPath := filepath.Join(t.TempDir(), "litestream.yml") |
| + if err := os.WriteFile(cfgPath, []byte(LitestreamConfig(dbs, "b", "p", "eu-west-1")), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + var err error |
| + out := captureStdout(t, func() { err = RestoreVerify("litestream", cfgPath, t.TempDir()) }) |
| + return out, err |
| + } |
| + |
| + out, err := run(journal, wal, busy) |
| + if err != nil { |
| + t.Fatalf("RestoreVerify = %v, want nil: an unknown freshness is not a failure", err) |
| + } |
| + for _, line := range []string{ |
| + "ok " + journal + " (restored clean, current)", |
| + "ok " + wal + " (restored clean, freshness unknown: WAL mode, where the change counter does not track writes)", |
| + "ok " + busy + " (restored clean, freshness unknown: behind a write made in the last 15 minutes)", |
| + "restore-verify: all 3 replicas restore clean; 1 are current, 2 could not be judged", |
| + } { |
| + if !strings.Contains(out, line+"\n") { |
| + t.Errorf("output lacks %q:\n%s", line, out) |
| + } |
| + } |
| + if strings.Contains(out, "and are current") { |
| + t.Errorf("a run with unknown freshness claimed every replica current:\n%s", out) |
| + } |
| + for _, p := range []string{journal, wal, busy} { |
| + if restores[p] != 1 { |
| + t.Errorf("%s restored %d times, want once", p, restores[p]) |
| + } |
| + } |
| + |
| + out, err = run(journal) |
| + if err != nil { |
| + t.Fatalf("RestoreVerify of a current replica = %v", err) |
| + } |
| + if want := "restore-verify: all 1 replicas restore clean and are current\n"; !strings.Contains(out, want) { |
| + t.Errorf("output lacks %q:\n%s", want, out) |
| + } |
| +} |
diff --git a/internal/ops/hibernate_verify.go b/internal/ops/hibernate_verify.go| index a99bd1c4f..141a6b9dc 100644 |
| --- a/internal/ops/hibernate_verify.go |
| +++ b/internal/ops/hibernate_verify.go |
| @@ -776,7 +776,7 @@ func (d Drill) freshness(ctx context.Context, rt HibernatingRoute, prefix string |
| // replica can never advance again. A failure, though staleness |
| // itself was not measured. |
| return dbverify.FreshnessUnknown, true, detail |
| - case freshnessOK: |
| + case freshnessCurrent: |
| if rt.DBPath == "" { |
| return dbverify.FreshnessUnknown, false, "" // nothing was compared |
| } |
| @@ -897,14 +897,14 @@ func OldestFirst(hosts []HibernatingRoute, prior *dbverify.Record) []Hibernating |
| // hibernateFreshness asks whether this replica is still tracking its source. |
| // |
| -// A route with no recorded DBPath yields "ok": there is nothing to compare |
| -// against, and mistaking "we do not know where the source lives" for "the |
| -// source is gone" would raise a false alarm on a healthy instance. |
| -// HibernatingHosts only yields routes with a DBPath, so this is a guard rather |
| -// than a path production takes. |
| +// A route with no recorded DBPath yields unknown: there is nothing to compare |
| +// against, so it is not current, and mistaking "we do not know where the |
| +// source lives" for "the source is gone" would raise a false alarm on a |
| +// healthy instance. HibernatingHosts only yields routes with a DBPath, so |
| +// this is a guard rather than a path production takes. |
| func hibernateFreshness(dbPath string, restoredCounter uint32) (freshness, string) { |
| if dbPath == "" { |
| - return freshnessOK, "" |
| + return freshnessUnknown, "" |
| } |
| return replicaFreshnessCounter(dbPath, restoredCounter, sourceModTime(dbPath)) |
| } |
diff --git a/internal/ops/hibernate_verify_test.go b/internal/ops/hibernate_verify_test.go| index fd3905c04..bcc3b245c 100644 |
| --- a/internal/ops/hibernate_verify_test.go |
| +++ b/internal/ops/hibernate_verify_test.go |
| @@ -1022,6 +1022,41 @@ func TestVerifyHibernatingFreshnessOnlyOnLeaseHolder(t *testing.T) { |
| t.Fatalf("verdict %+v, want passed/not_stale", v) |
| } |
| }) |
| + // The two unknowns of spec §5.3 pass the restore and are never |
| + // not_stale: a WAL-mode source's counter proves nothing when level, and |
| + // a copy behind a source written within the grace window is behind. |
| + unknowns := map[string]func(t *testing.T) (string, uint32){ |
| + "WAL-mode source, level": func(t *testing.T) (string, uint32) { |
| + p := filepath.Join(t.TempDir(), "wal.db") |
| + writeWALCounterDB(t, p, 30) |
| + n, err := ChangeCounter(p) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return p, n |
| + }, |
| + "behind a recent write": func(t *testing.T) (string, uint32) { |
| + p := filepath.Join(t.TempDir(), "busy.db") |
| + writeCounterDB(t, p, 30) |
| + return p, 2 |
| + }, |
| + } |
| + for name, source := range unknowns { |
| + t.Run("held by this box, "+name, func(t *testing.T) { |
| + dbPath, counter := source(t) |
| + fx := newDrillFx(t, "a.example.com") |
| + fx.stubVerify(func(context.Context, string, string, uint64) (uint32, error) { return counter, nil }) |
| + swap(t, &lockState, func(context.Context, string, string, string) (bool, string, time.Time, error) { |
| + return true, selfOwner(fxSelf), time.Now().Add(time.Minute), nil |
| + }) |
| + rt := fx.routes("a.example.com") |
| + rt[0].DBPath = dbPath |
| + v := fx.run(context.Background(), fx.drill(), rt, nil)["a.example.com"] |
| + if !v.OK() || v.Freshness != dbverify.FreshnessUnknown || fx.localReads.Load() != 1 { |
| + t.Fatalf("verdict %+v (%d local reads), want passed/unknown", v, fx.localReads.Load()) |
| + } |
| + }) |
| + } |
| } |
| // TestVerifyHibernatingBudget: the budget is measured on the run's clock; |
diff --git a/internal/ops/litestream.go b/internal/ops/litestream.go| index caa4873ca..d0bbee01f 100644 |
| --- a/internal/ops/litestream.go |
| +++ b/internal/ops/litestream.go |
| @@ -506,7 +506,7 @@ func RestoreVerify(litestreamBin, cfgPath, tmpDir string) error { |
| return fmt.Errorf("restore-verify: no databases in %s — regenerate it: carlos ops litestream", cfgPath) |
| } |
| - failures, stale := 0, 0 |
| + failures, stale, current, unknown := 0, 0, 0, 0 |
| for _, db := range dbs { |
| // Sweep this database's copy however the check ends — a failure must |
| // not leave the wreckage behind for the next restore to be charged for. |
| @@ -541,11 +541,14 @@ func RestoreVerify(litestreamBin, cfgPath, tmpDir string) error { |
| case freshnessNoSource: |
| stale++ |
| fmt.Printf("STALE %s: %s\n", db, freshDetail) |
| - case freshnessUnknown: |
| - // Never a pass and never an alarm — see the freshness doc. |
| - fmt.Printf("ok %s (freshness unknown: %s)\n", db, freshDetail) |
| + case freshnessCurrent: |
| + current++ |
| + fmt.Printf("ok %s (restored clean, current)\n", db) |
| default: |
| - fmt.Printf("ok %s\n", db) |
| + // The restore passed; its freshness is neither current nor an |
| + // alarm, and is counted apart — see the freshness doc. |
| + unknown++ |
| + fmt.Printf("ok %s (restored clean, freshness unknown: %s)\n", db, freshDetail) |
| } |
| } |
| switch { |
| @@ -562,6 +565,10 @@ func RestoreVerify(litestreamBin, cfgPath, tmpDir string) error { |
| return fmt.Errorf("restore-verify: %d of %d replicas restore clean but have STOPPED TRACKING their source — replication is broken for them", |
| stale, len(dbs)) |
| } |
| + if unknown > 0 { |
| + fmt.Printf("restore-verify: all %d replicas restore clean; %d are current, %d could not be judged\n", len(dbs), current, unknown) |
| + return nil |
| + } |
| fmt.Printf("restore-verify: all %d replicas restore clean and are current\n", len(dbs)) |
| return nil |
| } |
diff --git a/internal/ops/ops_test.go b/internal/ops/ops_test.go| index 1c35f36b3..c203d5c68 100644 |
| --- a/internal/ops/ops_test.go |
| +++ b/internal/ops/ops_test.go |
| @@ -515,15 +515,17 @@ func TestReplicaFreshness(t *testing.T) { |
| if v, detail := replicaFreshness(local, behind, long); v != freshnessStale { |
| t.Fatalf("a replica behind a long-quiet source = %v (%s), want stale", v, detail) |
| } |
| - // Written moments ago: the replica being a transaction or two behind is |
| - // ordinary lag, not a fault. Never cry wolf here — a drill that goes red |
| - // on healthy churn is a drill people stop reading. |
| - if v, _ := replicaFreshness(local, behind, recent); v != freshnessOK { |
| - t.Fatalf("a replica behind a just-written source = %v, want ok (still catching up)", v) |
| + // Written moments ago: the replica being a transaction or two behind may |
| + // be ordinary lag, so it is not a fault — never cry wolf here, a drill |
| + // that goes red on healthy churn is a drill people stop reading. Nor is |
| + // it current: it is behind, and only a later pass can say whether it |
| + // catches up. |
| + if v, _ := replicaFreshness(local, behind, recent); v != freshnessUnknown { |
| + t.Fatalf("a replica behind a just-written source = %v, want unknown (behind a recent write)", v) |
| } |
| // Caught up. |
| - if v, _ := replicaFreshness(local, local, long); v != freshnessOK { |
| - t.Fatalf("an up-to-date replica = %v, want ok", v) |
| + if v, _ := replicaFreshness(local, local, long); v != freshnessCurrent { |
| + t.Fatalf("an up-to-date replica = %v, want current", v) |
| } |
| // The source is gone: a config naming a database that no longer exists is |
| // its own finding — the replica can never advance again. |