| index a3826526c..913f099b4 100644 |
| --- a/internal/ops/hibernate_verify_test.go |
| +++ b/internal/ops/hibernate_verify_test.go |
| @@ -1,19 +1,33 @@ |
| package ops |
| |
| import ( |
| + "bytes" |
| "context" |
| + "encoding/json" |
| "errors" |
| + "fmt" |
| "os" |
| "path/filepath" |
| "slices" |
| "strings" |
| + "sync" |
| + "sync/atomic" |
| "testing" |
| "time" |
| |
| + "github.com/benbjohnson/litestream" |
| + lsfile "github.com/benbjohnson/litestream/file" |
| + "github.com/superfly/ltx" |
| + |
| "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/boxself" |
| + "github.com/carlosframework/platform/internal/dbdoor" |
| + "github.com/carlosframework/platform/internal/dbdoor/dbdoortest" |
| "github.com/carlosframework/platform/internal/dbverify" |
| - "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| ) |
| |
| func at(s string) time.Time { |
| @@ -79,16 +93,30 @@ func TestHibernatingHostsIsTheComplementOfFleetDBs(t *testing.T) { |
| } |
| } |
| |
| -// routes builds the drill's input from bare host names. The DBPath is left |
| -// empty on purpose: these tests drive the RESTORE outcomes, and an absent |
| -// source is reported as its own verdict, which TestVerifyHibernatingStale |
| -// covers explicitly. |
| -func routes(hosts ...string) []HibernatingRoute { |
| - out := make([]HibernatingRoute, 0, len(hosts)) |
| - for _, h := range hosts { |
| - out = append(out, HibernatingRoute{Host: h}) |
| +// The drill binds each verdict to the instance its provision record names, |
| +// so a route must carry the record's account and app: the account as the |
| +// record files it (a route's "" is the ops account). |
| +func TestHibernatingHostsCarryTheRecordsAccountAndApp(t *testing.T) { |
| + dir := t.TempDir() |
| + reg, err := registry.Open(filepath.Join(dir, "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + db := filepath.Join(dir, "x.db") |
| + if err := reg.Upsert(registry.Route{Host: "a.example.com", DBPath: db, Hibernate: true, Account: "acme", App: "shop"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := reg.Upsert(registry.Route{Host: "b.example.com", DBPath: db, Hibernate: true, App: "blog"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + got := mustHibernating(t, reg) |
| + want := []HibernatingRoute{ |
| + {Host: "a.example.com", DBPath: db, Account: "acme", App: "shop"}, |
| + {Host: "b.example.com", DBPath: db, Account: registry.EffectiveAccount(""), App: "blog"}, |
| + } |
| + if !slices.Equal(got, want) { |
| + t.Fatalf("HibernatingHosts = %+v, want %+v", got, want) |
| } |
| - return out |
| } |
| |
| func hostsOf(rs []HibernatingRoute) []string { |
| @@ -108,88 +136,370 @@ func mustHibernating(t *testing.T, reg *registry.Registry) []HibernatingRoute { |
| return got |
| } |
| |
| -// swapVerifyOne points the restore seam at a stub. |
| -func swapVerifyOne(t *testing.T, fn func(ctx context.Context, bucket, prefix, region, dir string) (uint32, error)) { |
| +// --- the drill fixture ------------------------------------------------------- |
| + |
| +const ( |
| + fxAccount = "bab" |
| + fxApp = "shop" |
| + fxRegion = "uk" |
| + fxSelf = "box-a" |
| +) |
| + |
| +// swap points a seam at v for the rest of the test. |
| +func swap[T any](t *testing.T, p *T, v T) { |
| t.Helper() |
| - prev := verifyOne |
| - verifyOne = fn |
| - t.Cleanup(func() { verifyOne = prev }) |
| + old := *p |
| + *p = v |
| + t.Cleanup(func() { *p = old }) |
| +} |
| + |
| +// fakeClock is the drill's now: tests move it, nothing else does. |
| +type fakeClock struct { |
| + mu sync.Mutex |
| + t time.Time |
| +} |
| + |
| +func (c *fakeClock) Now() time.Time { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.t |
| +} |
| + |
| +func (c *fakeClock) Advance(d time.Duration) { |
| + c.mu.Lock() |
| + c.t = c.t.Add(d) |
| + c.mu.Unlock() |
| +} |
| + |
| +// drillFx is a deployment store holding a provision record per host, one |
| +// real litestream replica every host plans from (unless replicaFor says |
| +// otherwise), and stubs for the restore, the lock read and the local |
| +// comparison, so a test drives each outcome. |
| +type drillFx struct { |
| + t *testing.T |
| + store release.Store |
| + replica string |
| + empty string |
| + clock *fakeClock |
| + cfg *activator.Config |
| + tmp string |
| + |
| + mu sync.Mutex |
| + replicaFor map[string]string // prefix -> replica dir |
| + onList map[string]func() // prefix -> hook run when planning lists it |
| + verifies []uint64 // the txids verifyAt was asked for |
| + localReads atomic.Int32 |
| +} |
| + |
| +var ( |
| + sharedReplicaOnce sync.Once |
| + sharedReplicaDir string |
| + sharedReplicaErr error |
| +) |
| + |
| +// sharedReplica is one real replica the whole package's tests plan from: |
| +// it is only ever read, so building it once keeps the tests quick. |
| +func sharedReplica(t *testing.T) string { |
| + t.Helper() |
| + sharedReplicaOnce.Do(func() { |
| + dir, err := os.MkdirTemp("", "ops-drill-replica-") |
| + if err != nil { |
| + sharedReplicaErr = err |
| + return |
| + } |
| + sharedReplicaDir = dir |
| + dbdoortest.Replicate(t, dir, 3) |
| + }) |
| + if sharedReplicaErr != nil { |
| + t.Fatal(sharedReplicaErr) |
| + } |
| + return sharedReplicaDir |
| +} |
| + |
| +func TestMain(m *testing.M) { |
| + code := m.Run() |
| + if sharedReplicaDir != "" { |
| + os.RemoveAll(sharedReplicaDir) |
| + } |
| + os.Exit(code) |
| +} |
| + |
| +func newDrillFx(t *testing.T, hosts ...string) *drillFx { |
| + t.Helper() |
| + fx := &drillFx{ |
| + t: t, |
| + store: release.NewDirStore(t.TempDir()), |
| + replica: sharedReplica(t), |
| + empty: t.TempDir(), |
| + clock: &fakeClock{t: at("2026-11-12T03:00:00Z")}, |
| + cfg: &activator.Config{Bucket: "instances", Prefix: "hib", Region: "eu-west-1"}, |
| + tmp: t.TempDir(), |
| + replicaFor: map[string]string{}, |
| + onList: map[string]func(){}, |
| + } |
| + for _, h := range hosts { |
| + fx.putRecord(fxAccount, h, time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC), nil) |
| + } |
| + swap(t, &openReplica, func(_ context.Context, bucket, prefix, region string) (dbdoor.ReplicaReader, error) { |
| + if bucket != fx.cfg.Bucket || region != fx.cfg.Region { |
| + t.Errorf("replica opened in %s/%s, want %s/%s", bucket, region, fx.cfg.Bucket, fx.cfg.Region) |
| + } |
| + fx.mu.Lock() |
| + dir, ok := fx.replicaFor[prefix] |
| + hook := fx.onList[prefix] |
| + fx.mu.Unlock() |
| + if !ok { |
| + dir = fx.replica |
| + } |
| + return &hookReader{ReplicaReader: lsfile.NewReplicaClient(dir), hook: hook}, nil |
| + }) |
| + swap(t, &verifyAt, func(context.Context, string, string, string, string, uint64) (uint32, error) { |
| + return 1, nil |
| + }) |
| + swap(t, &lockState, func(context.Context, string, string, string) (bool, string, time.Time, error) { |
| + return false, "", time.Time{}, nil |
| + }) |
| + real := localFreshness |
| + swap(t, &localFreshness, func(dbPath string, counter uint32) (freshness, string) { |
| + fx.localReads.Add(1) |
| + return real(dbPath, counter) |
| + }) |
| + return fx |
| +} |
| + |
| +// stubVerify replaces the restore; it records the txid it was asked for. |
| +func (fx *drillFx) stubVerify(fn func(ctx context.Context, prefix, dir string, txid uint64) (uint32, error)) { |
| + swap(fx.t, &verifyAt, func(ctx context.Context, bucket, prefix, region, dir string, txid uint64) (uint32, error) { |
| + if bucket != fx.cfg.Bucket || region != fx.cfg.Region { |
| + fx.t.Errorf("restore from %s/%s, want %s/%s", bucket, region, fx.cfg.Bucket, fx.cfg.Region) |
| + } |
| + fx.mu.Lock() |
| + fx.verifies = append(fx.verifies, txid) |
| + fx.mu.Unlock() |
| + return fn(ctx, prefix, dir, txid) |
| + }) |
| +} |
| + |
| +func (fx *drillFx) prefix(host string) string { return activator.HibernatePrefix(fx.cfg.Prefix, host) } |
| + |
| +func (fx *drillFx) putRecord(acct, host string, created time.Time, mutate func(*provision.Record)) { |
| + fx.t.Helper() |
| + yes := true |
| + rec := provision.Record{Account: acct, App: fxApp, Host: host, Region: fxRegion, CreatedAt: created, Hibernate: &yes} |
| + if mutate != nil { |
| + mutate(&rec) |
| + } |
| + body, err := json.Marshal(rec) |
| + if err != nil { |
| + fx.t.Fatal(err) |
| + } |
| + key := provision.RecordKey(acct, fxApp, host) |
| + if err := fx.store.Delete(context.Background(), key); err != nil { |
| + fx.t.Fatal(err) |
| + } |
| + if _, err := fx.store.Put(context.Background(), key, body, ""); err != nil { |
| + fx.t.Fatal(err) |
| + } |
| +} |
| + |
| +func (fx *drillFx) deleteRecord(acct, host string) { |
| + fx.t.Helper() |
| + if err := fx.store.Delete(context.Background(), provision.RecordKey(acct, fxApp, host)); err != nil { |
| + fx.t.Fatal(err) |
| + } |
| +} |
| + |
| +func (fx *drillFx) record(host string) provision.Record { |
| + fx.t.Helper() |
| + rec, err := provision.GetRecord(context.Background(), fx.store, fxAccount, fxApp, host) |
| + if err != nil { |
| + fx.t.Fatal(err) |
| + } |
| + return *rec |
| +} |
| + |
| +func (fx *drillFx) identity(host string) dbverify.Identity { |
| + fx.t.Helper() |
| + rec := fx.record(host) |
| + inc, err := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt) |
| + if err != nil { |
| + fx.t.Fatal(err) |
| + } |
| + return dbverify.Identity{Account: fxAccount, App: fxApp, Host: host, Region: fxRegion, Incarnation: inc} |
| +} |
| + |
| +func (fx *drillFx) drill() Drill { |
| + return Drill{Cfg: fx.cfg, Store: fx.store, Region: fxRegion, SelfRef: fxSelf, TmpDir: fx.tmp} |
| +} |
| + |
| +func (fx *drillFx) routes(hosts ...string) []HibernatingRoute { |
| + out := make([]HibernatingRoute, 0, len(hosts)) |
| + for _, h := range hosts { |
| + out = append(out, HibernatingRoute{Host: h, Account: fxAccount, App: fxApp}) |
| + } |
| + return out |
| +} |
| + |
| +func (fx *drillFx) run(ctx context.Context, d Drill, hosts []HibernatingRoute, publish func(map[string]dbverify.Verdict)) map[string]dbverify.Verdict { |
| + return VerifyHibernating(ctx, d, hosts, fx.clock.Now, publish) |
| +} |
| + |
| +// plan is the plan the shared replica gives today. |
| +func (fx *drillFx) plan() dbdoor.RestorePlan { |
| + fx.t.Helper() |
| + p, err := dbdoor.PlanFrom(context.Background(), lsfile.NewReplicaClient(fx.replica), time.Time{}) |
| + if err != nil { |
| + fx.t.Fatal(err) |
| + } |
| + return p |
| } |
| |
| -// The three verdicts, and — most importantly — that an S3 failure is |
| -// "unverified", not a corruption alarm, and a never-woken instance is neither. |
| +func (fx *drillFx) scratchEmpty() { |
| + fx.t.Helper() |
| + ents, err := os.ReadDir(fx.tmp) |
| + if err != nil { |
| + fx.t.Fatal(err) |
| + } |
| + if len(ents) != 0 { |
| + var names []string |
| + for _, e := range ents { |
| + names = append(names, e.Name()) |
| + } |
| + fx.t.Fatalf("scratch left behind in %s: %v", fx.tmp, names) |
| + } |
| +} |
| + |
| +// hookReader runs hook once, when the planner first lists the replica. |
| +type hookReader struct { |
| + dbdoor.ReplicaReader |
| + hook func() |
| + once sync.Once |
| +} |
| + |
| +func (r *hookReader) LTXFiles(ctx context.Context, level int, seek ltx.TXID, useMetadata bool) (ltx.FileIterator, error) { |
| + if r.hook != nil { |
| + r.once.Do(r.hook) |
| + } |
| + return r.ReplicaReader.LTXFiles(ctx, level, seek, useMetadata) |
| +} |
| + |
| +// --- the verdicts -------------------------------------------------------------- |
| + |
| +// The three results, and that a never-woken instance is neither a pass nor |
| +// a failure. |
| func TestVerifyHibernatingVerdicts(t *testing.T) { |
| - now := at("2026-08-15T09:00:00Z") |
| - swapVerifyOne(t, func(_ context.Context, _, prefix, _, _ string) (uint32, error) { |
| - switch { |
| - case strings.Contains(prefix, "good"): |
| - return 1, nil |
| - case strings.Contains(prefix, "damaged"): |
| + fx := newDrillFx(t, "good.example.com", "damaged.example.com", "new.example.com") |
| + fx.replicaFor[fx.prefix("new.example.com")] = fx.empty |
| + fx.stubVerify(func(_ context.Context, prefix, _ string, _ uint64) (uint32, error) { |
| + if strings.Contains(prefix, "damaged") { |
| return 0, errors.New("integrity_check: page 4 corrupt") |
| - case strings.Contains(prefix, "new"): |
| - return 0, lease.ErrNoReplica |
| } |
| - return 0, errors.New("unexpected host") |
| + return 1, nil |
| }) |
| + got := fx.run(context.Background(), fx.drill(), |
| + fx.routes("good.example.com", "damaged.example.com", "new.example.com"), nil) |
| |
| - cfg := &activator.Config{Bucket: "instances", Prefix: "hib", Region: "eu-west-1"} |
| - got := VerifyHibernating(context.Background(), cfg, |
| - routes("good.example.com", "damaged.example.com", "new.example.com"), 0, now, t.TempDir()) |
| - |
| - if v := got["good.example.com"]; !v.OK() || v.Unverified() { |
| + if v := got["good.example.com"]; !v.OK() { |
| t.Fatalf("clean replica verdict = %+v", v) |
| } |
| - if v := got["damaged.example.com"]; v.OK() || v.Unverified() { |
| + if v := got["damaged.example.com"]; v.Result != dbverify.ResultFailed || v.Reason != ReasonRestoreError { |
| t.Fatalf("damaged replica must be a failure, got %+v", v) |
| } |
| - if v := got["new.example.com"]; v.OK() || !v.Unverified() { |
| - t.Fatalf("never-woken instance must be unverified (nothing was proven), got %+v", v) |
| + if v := got["new.example.com"]; !v.Unverified() || v.Reason != ReasonNothingReplicated { |
| + t.Fatalf("never-woken instance must be unverified, nothing_replicated, got %+v", v) |
| } |
| |
| - rec := dbverify.Merge(nil, "box-a", now, |
| + rec := dbverify.Merge(nil, fxSelf, fx.clock.Now(), |
| []string{"good.example.com", "damaged.example.com", "new.example.com"}, got) |
| - if rec.Failures() != 1 { |
| - t.Fatalf("Failures() = %d, want 1 — only the damaged replica", rec.Failures()) |
| - } |
| - if rec.Unverified() != 1 { |
| - t.Fatalf("Unverified() = %d, want 1", rec.Unverified()) |
| + if rec.Failures() != 1 || rec.Unverified() != 1 { |
| + t.Fatalf("Failures() = %d, Unverified() = %d; want 1 and 1", rec.Failures(), rec.Unverified()) |
| } |
| + fx.scratchEmpty() |
| } |
| |
| // The per-host prefix must be the one the activator actually writes to, or |
| -// every drill reports "no replica" over perfectly good backups. |
| +// every drill reports "no replica" over perfectly good backups; the lock |
| +// read is the same prefix's. |
| func TestVerifyHibernatingUsesTheActivatorsPrefix(t *testing.T) { |
| - var seen string |
| - swapVerifyOne(t, func(_ context.Context, _, prefix, _, _ string) (uint32, error) { |
| - seen = prefix |
| + fx := newDrillFx(t, "x.example.com") |
| + want := activator.HibernatePrefix("hib", "x.example.com") |
| + var planned, restored, locked string |
| + real := openReplica |
| + swap(t, &openReplica, func(ctx context.Context, bucket, prefix, region string) (dbdoor.ReplicaReader, error) { |
| + planned = prefix |
| + return real(ctx, bucket, prefix, region) |
| + }) |
| + fx.stubVerify(func(_ context.Context, prefix, _ string, _ uint64) (uint32, error) { |
| + restored = prefix |
| return 1, nil |
| }) |
| - cfg := &activator.Config{Bucket: "instances", Prefix: "hib"} |
| - VerifyHibernating(context.Background(), cfg, routes("x.example.com"), 0, time.Now(), t.TempDir()) |
| + swap(t, &lockState, func(_ context.Context, bucket, location, region string) (bool, string, time.Time, error) { |
| + locked = location |
| + return false, "", time.Time{}, nil |
| + }) |
| + got := fx.run(context.Background(), fx.drill(), fx.routes("x.example.com"), nil) |
| |
| - want := activator.HibernatePrefix("hib", "x.example.com") |
| - if seen != want { |
| - t.Fatalf("drilled prefix %q, activator writes %q", seen, want) |
| + if planned != want || restored != want || locked != want { |
| + t.Fatalf("planned %q, restored %q, read the lock at %q; the activator writes %q", planned, restored, locked, want) |
| + } |
| + if got["x.example.com"].Prefix != want { |
| + t.Fatalf("verdict prefix %q, want %q", got["x.example.com"].Prefix, want) |
| } |
| } |
| |
| -// A capped run visits the cap and no more — the rest keep their old verdict |
| -// via Merge, which is what stops a cap from reading as full coverage. |
| +// A capped run visits the cap and no more; the default is no cap. |
| func TestVerifyHibernatingHonoursTheCap(t *testing.T) { |
| + fx := newDrillFx(t, "a.example.com", "b.example.com", "c.example.com") |
| calls := 0 |
| - swapVerifyOne(t, func(context.Context, string, string, string, string) (uint32, error) { |
| + fx.stubVerify(func(context.Context, string, string, uint64) (uint32, error) { |
| calls++ |
| return 1, nil |
| }) |
| - cfg := &activator.Config{Bucket: "instances"} |
| - got := VerifyHibernating(context.Background(), cfg, |
| - routes("a.example.com", "b.example.com", "c.example.com"), 2, time.Now(), t.TempDir()) |
| + d := fx.drill() |
| + d.Max = 2 |
| + got := fx.run(context.Background(), d, fx.routes("a.example.com", "b.example.com", "c.example.com"), nil) |
| + if calls != 2 || len(got) != 2 { |
| + t.Fatalf("restored %d replicas, returned %d verdicts under --max 2", calls, len(got)) |
| + } |
| |
| - if calls != 2 { |
| - t.Fatalf("restored %d replicas under --max 2", calls) |
| + opts, err := parseHibernateVerifyFlags(nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if opts.max != 0 { |
| + t.Fatalf("--max defaults to %d, want 0 (no cap)", opts.max) |
| + } |
| + calls = 0 |
| + d.Max = opts.max |
| + got = fx.run(context.Background(), d, fx.routes("a.example.com", "b.example.com", "c.example.com"), nil) |
| + if calls != 3 || len(got) != 3 { |
| + t.Fatalf("with no cap: restored %d, %d verdicts; want 3 and 3", calls, len(got)) |
| + } |
| +} |
| + |
| +// The flags: a 45-minute budget, no cap, a 10-minute publish interval kept |
| +// out of the usage text. |
| +func TestHibernateVerifyFlags(t *testing.T) { |
| + opts, err := parseHibernateVerifyFlags(nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if opts.budget != 45*time.Minute || opts.max != 0 || opts.publishEvery != 10*time.Minute { |
| + t.Fatalf("defaults budget %s, max %d, publish-every %s; want 45m, 0, 10m", opts.budget, opts.max, opts.publishEvery) |
| + } |
| + opts, err = parseHibernateVerifyFlags([]string{"-budget", "5m", "-max", "3", "-publish-every", "1m"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if opts.budget != 5*time.Minute || opts.max != 3 || opts.publishEvery != time.Minute { |
| + t.Fatalf("parsed %+v", opts) |
| } |
| - if len(got) != 2 { |
| - t.Fatalf("returned %d verdicts under --max 2: %v", len(got), got) |
| + var usage bytes.Buffer |
| + if _, err := parseHibernateVerifyFlagsTo(&usage, []string{"-h"}); err == nil { |
| + t.Fatal("-h parsed as a run") |
| + } |
| + if !strings.Contains(usage.String(), "--budget") || strings.Contains(usage.String(), "publish-every") { |
| + t.Fatalf("usage should name --budget and hide --publish-every:\n%s", usage.String()) |
| } |
| } |
| |
| @@ -200,58 +510,929 @@ func TestOldestFirstPutsNeverVerifiedThenStalest(t *testing.T) { |
| "recent.example.com": {Result: dbverify.ResultPassed, VerifiedAt: at("2026-08-14T00:00:00Z")}, |
| "stale.example.com": {Result: dbverify.ResultPassed, VerifiedAt: at("2026-08-01T00:00:00Z")}, |
| }} |
| - got := hostsOf(OldestFirst(routes("recent.example.com", "stale.example.com", "never.example.com"), prior)) |
| + got := hostsOf(OldestFirst(bare("recent.example.com", "stale.example.com", "never.example.com"), prior)) |
| want := []string{"never.example.com", "stale.example.com", "recent.example.com"} |
| if !slices.Equal(got, want) { |
| t.Fatalf("OldestFirst = %v, want %v", got, want) |
| } |
| |
| // With no prior record at all, the order must still be deterministic. |
| - if got := hostsOf(OldestFirst(routes("b.example.com", "a.example.com"), nil)); !slices.Equal(got, []string{"a.example.com", "b.example.com"}) { |
| + if got := hostsOf(OldestFirst(bare("b.example.com", "a.example.com"), nil)); !slices.Equal(got, []string{"a.example.com", "b.example.com"}) { |
| t.Fatalf("OldestFirst with no prior record = %v", got) |
| } |
| } |
| |
| -// A hibernating instance's replica has a live owner — the activator's embedded |
| -// replicator, under the lease — and an owner that has stopped writing leaves a |
| -// replica that still restores perfectly. Same blind spot as the box-wide |
| -// drill, same signal: the replica's change counter stopped moving while the |
| -// database it mirrors did not. |
| +func bare(hosts ...string) []HibernatingRoute { |
| + out := make([]HibernatingRoute, 0, len(hosts)) |
| + for _, h := range hosts { |
| + out = append(out, HibernatingRoute{Host: h}) |
| + } |
| + return out |
| +} |
| + |
| +// selfOwner is a lock owner string this box wrote. |
| +func selfOwner(ref string) string { |
| + return hafresh.OwnerFor(hafresh.Self{Ref: ref, IID: "i-0123"}, 4242, false) |
| +} |
| + |
| +// A replica restores clean but stopped moving while the database it |
| +// mirrors kept writing: on the box that holds the lease, that is a failure. |
| func TestVerifyHibernatingCatchesAStaleReplica(t *testing.T) { |
| - dir := t.TempDir() |
| - live := filepath.Join(dir, "live.db") |
| + fx := newDrillFx(t, "frozen.example.com") |
| + live := filepath.Join(t.TempDir(), "live.db") |
| writeCounterDB(t, live, 30) |
| - // Quiet for longer than the grace window: unambiguously "replication |
| - // stopped", not "still catching up". |
| old := time.Now().Add(-2 * time.Hour) |
| if err := os.Chtimes(live, old, old); err != nil { |
| t.Fatal(err) |
| } |
| - |
| - // The replica restores clean, but at a change counter from long ago. |
| - swapVerifyOne(t, func(context.Context, string, string, string, string) (uint32, error) { |
| - return 2, nil |
| + fx.stubVerify(func(context.Context, string, string, uint64) (uint32, error) { return 2, 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 |
| }) |
| - |
| - now := at("2026-08-15T09:00:00Z") |
| - got := VerifyHibernating(context.Background(), &activator.Config{Bucket: "instances"}, |
| - []HibernatingRoute{{Host: "frozen.example.com", DBPath: live}}, 0, now, t.TempDir()) |
| + rt := fx.routes("frozen.example.com") |
| + rt[0].DBPath = live |
| + got := fx.run(context.Background(), fx.drill(), rt, nil) |
| |
| v := got["frozen.example.com"] |
| - if v.OK() { |
| - t.Fatalf("a replica frozen while its instance kept writing was reported OK: %+v", v) |
| - } |
| - if v.Unverified() { |
| - t.Fatalf("a stale replica must be a FAILURE, not merely unverified: %+v", v) |
| + if v.Result != dbverify.ResultFailed || v.Reason != ReasonStale || v.Freshness != dbverify.FreshnessStale { |
| + t.Fatalf("a replica frozen while its instance kept writing: %+v", v) |
| } |
| if !strings.Contains(v.Detail, "replication has stopped") { |
| t.Fatalf("verdict does not say what is wrong: %q", v.Detail) |
| } |
| +} |
| + |
| +// TestVerifyHibernatingBindsIdentity: a pass names the instance it tested, |
| +// the position it restored (the plan's, which the restore was pinned to), |
| +// and when the bracket opened. |
| +func TestVerifyHibernatingBindsIdentity(t *testing.T) { |
| + fx := newDrillFx(t, "shop.example.com") |
| + plan := fx.plan() |
| + opened := fx.clock.Now() |
| + fx.stubVerify(func(context.Context, string, string, uint64) (uint32, error) { |
| + fx.clock.Advance(3 * time.Minute) |
| + return 1, nil |
| + }) |
| + got := fx.run(context.Background(), fx.drill(), fx.routes("shop.example.com"), nil) |
| + |
| + v := got["shop.example.com"] |
| + want := dbverify.Verdict{ |
| + Result: dbverify.ResultPassed, Identity: fx.identity("shop.example.com"), Prefix: fx.prefix("shop.example.com"), |
| + BracketOpenedAt: opened, VerifiedAt: opened.Add(3 * time.Minute), |
| + TXID: plan.TXID, WrittenAt: plan.At, RestoredBytes: plan.RestoredBytes, |
| + Freshness: dbverify.FreshnessUnknown, |
| + } |
| + v.Detail = "" |
| + if v != want { |
| + t.Fatalf("verdict\n got %+v\nwant %+v", v, want) |
| + } |
| + if plan.TXID == 0 || plan.RestoredBytes == 0 || plan.At.IsZero() { |
| + t.Fatalf("the fixture's plan is empty: %+v", plan) |
| + } |
| + if !slices.Equal(fx.verifies, []uint64{plan.TXID}) { |
| + t.Fatalf("restores pinned to %v, want the plan's %d", fx.verifies, plan.TXID) |
| + } |
| +} |
| + |
| +// TestVerifyHibernatingBracket: whatever the restore found, an instance |
| +// whose record changed between the capture and the confirm gets no verdict |
| +// from the copy: always unverified, record_changed or moving (P-11). |
| +func TestVerifyHibernatingBracket(t *testing.T) { |
| + const host = "shop.example.com" |
| + recreated := time.Date(2026, 11, 12, 3, 1, 0, 0, time.UTC) |
| + changes := map[string]struct { |
| + change func(fx *drillFx) |
| + reason string |
| + }{ |
| + "deleted": {func(fx *drillFx) { fx.deleteRecord(fxAccount, host) }, ReasonRecordChanged}, |
| + "recreated same account": {func(fx *drillFx) { fx.putRecord(fxAccount, host, recreated, nil) }, ReasonRecordChanged}, |
| + "recreated another account": {func(fx *drillFx) { |
| + fx.deleteRecord(fxAccount, host) |
| + fx.putRecord("cde", host, recreated, nil) |
| + }, ReasonRecordChanged}, |
| + "moving": {func(fx *drillFx) { |
| + fx.putRecord(fxAccount, host, time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC), func(r *provision.Record) { |
| + r.Move = &provision.MoveState{ID: "mv_x", To: "ie", State: "requested"} |
| + }) |
| + }, ReasonMoving}, |
| + } |
| + outcomes := map[string]struct { |
| + empty bool |
| + err error |
| + }{ |
| + "restored": {}, |
| + "empty plan": {empty: true}, |
| + "restore error": {err: errors.New("restore: decode header: EOF")}, |
| + "integrity failure": {err: errors.New("integrity_check: page 4 corrupt")}, |
| + } |
| + for cname, c := range changes { |
| + for _, when := range []string{"planning", "download"} { |
| + for oname, o := range outcomes { |
| + if o.empty && when == "download" { |
| + continue // an empty plan downloads nothing |
| + } |
| + t.Run(cname+"/"+when+"/"+oname, func(t *testing.T) { |
| + fx := newDrillFx(t, host) |
| + want := fx.identity(host) |
| + if o.empty { |
| + fx.replicaFor[fx.prefix(host)] = fx.empty |
| + } |
| + if when == "planning" { |
| + fx.onList[fx.prefix(host)] = func() { c.change(fx) } |
| + } |
| + restores := 0 |
| + fx.stubVerify(func(context.Context, string, string, uint64) (uint32, error) { |
| + restores++ |
| + if when == "download" { |
| + c.change(fx) |
| + } |
| + return 1, o.err |
| + }) |
| + got := fx.run(context.Background(), fx.drill(), fx.routes(host), nil) |
| + v, ok := got[host] |
| + if !ok { |
| + t.Fatal("no verdict at all") |
| + } |
| + if v.Result != dbverify.ResultUnverified || v.Reason != c.reason { |
| + t.Fatalf("verdict %s/%s, want unverified/%s (%+v)", v.Result, v.Reason, c.reason, v) |
| + } |
| + if v.Identity != want { |
| + t.Fatalf("verdict names %+v, want the instance the bracket opened on, %+v", v.Identity, want) |
| + } |
| + if v.TXID != 0 || v.RestoredBytes != 0 || v.Freshness == dbverify.FreshnessStale { |
| + t.Fatalf("a discarded restore left its findings in the verdict: %+v", v) |
| + } |
| + if o.empty && restores != 0 { |
| + t.Fatalf("an empty plan was restored %d times", restores) |
| + } |
| + fx.scratchEmpty() |
| + }) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// A record that already refuses when the bracket opens is not drilled. |
| +func TestVerifyHibernatingRefusesBeforePlanning(t *testing.T) { |
| + fx := newDrillFx(t, "moving.example.com") |
| + fx.putRecord(fxAccount, "moving.example.com", time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC), func(r *provision.Record) { |
| + r.Move = &provision.MoveState{ID: "mv_x", To: "ie", State: "requested"} |
| + }) |
| + planned := false |
| + swap(t, &openReplica, func(context.Context, string, string, string) (dbdoor.ReplicaReader, error) { |
| + planned = true |
| + return nil, errors.New("not reached") |
| + }) |
| + got := fx.run(context.Background(), fx.drill(), fx.routes("moving.example.com", "gone.example.com"), nil) |
| + if planned { |
| + t.Fatal("a refused capture went on to plan") |
| + } |
| + if v := got["moving.example.com"]; v.Reason != ReasonMoving || !v.Unverified() || v.Identity.Host != "moving.example.com" { |
| + t.Fatalf("moving: %+v", v) |
| + } |
| + if v := got["gone.example.com"]; v.Reason != ReasonRecordChanged || !v.Unverified() { |
| + t.Fatalf("no record: %+v", v) |
| + } |
| +} |
| + |
| +// Compaction between the plan and the restore makes the planned position |
| +// unrestorable: not a failure. The drill plans again once; twice is |
| +// unverified, plan_moved. |
| +func TestVerifyHibernatingReplansOnceWhenThePlanMoves(t *testing.T) { |
| + moved := fmt.Errorf("restore: %w", litestream.ErrTxNotAvailable) |
| + t.Run("once", func(t *testing.T) { |
| + fx := newDrillFx(t, "a.example.com") |
| + n := 0 |
| + fx.stubVerify(func(context.Context, string, string, uint64) (uint32, error) { |
| + n++ |
| + if n == 1 { |
| + return 0, moved |
| + } |
| + return 1, nil |
| + }) |
| + v := fx.run(context.Background(), fx.drill(), fx.routes("a.example.com"), nil)["a.example.com"] |
| + if !v.OK() || n != 2 { |
| + t.Fatalf("after one replan: %+v (%d restores)", v, n) |
| + } |
| + }) |
| + t.Run("twice", func(t *testing.T) { |
| + fx := newDrillFx(t, "a.example.com") |
| + n := 0 |
| + fx.stubVerify(func(context.Context, string, string, uint64) (uint32, error) { |
| + n++ |
| + return 0, moved |
| + }) |
| + v := fx.run(context.Background(), fx.drill(), fx.routes("a.example.com"), nil)["a.example.com"] |
| + if !v.Unverified() || v.Reason != ReasonPlanMoved || n != 2 { |
| + t.Fatalf("after two moved plans: %+v (%d restores)", v, n) |
| + } |
| + fx.scratchEmpty() |
| + }) |
| +} |
| + |
| +// TestVerifyHibernatingFreshnessOnlyOnLeaseHolder: the local database is |
| +// compared only when this box provably holds the live lease (P-14). |
| +func TestVerifyHibernatingFreshnessOnlyOnLeaseHolder(t *testing.T) { |
| + live := filepath.Join(t.TempDir(), "live.db") |
| + writeCounterDB(t, live, 30) |
| + old := time.Now().Add(-2 * time.Hour) |
| + if err := os.Chtimes(live, old, old); err != nil { |
| + t.Fatal(err) |
| + } |
| + type lock struct { |
| + held bool |
| + owner string |
| + err error |
| + } |
| + for name, l := range map[string]lock{ |
| + "held by another box": {true, selfOwner("box-b"), nil}, |
| + "expired, self-owned": {false, selfOwner(fxSelf), nil}, |
| + "absent": {false, "", nil}, |
| + "malformed owner": {true, fxSelf + ":4242", nil}, |
| + "release marker": {true, hafresh.MarkerOwner(hafresh.Marker{Box: fxSelf}), nil}, |
| + "unreadable": {false, "", errors.New("lease: decode lock.json: unexpected EOF")}, |
| + "unreadable but held": {true, selfOwner(fxSelf), errors.New("lease: read: timeout")}, |
| + "held, owner names ref": {true, "box/v1;ref=" + fxSelf, nil}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + fx := newDrillFx(t, "a.example.com") |
| + fx.stubVerify(func(context.Context, string, string, uint64) (uint32, error) { return 2, nil }) |
| + swap(t, &lockState, func(context.Context, string, string, string) (bool, string, time.Time, error) { |
| + return l.held, l.owner, time.Now(), l.err |
| + }) |
| + rt := fx.routes("a.example.com") |
| + rt[0].DBPath = live |
| + v := fx.run(context.Background(), fx.drill(), rt, nil)["a.example.com"] |
| + if !v.OK() || v.Freshness != dbverify.FreshnessUnknown { |
| + t.Fatalf("verdict %+v, want passed with unknown freshness", v) |
| + } |
| + if n := fx.localReads.Load(); n != 0 { |
| + t.Fatalf("the local database was read %d times without the lease", n) |
| + } |
| + }) |
| + } |
| + t.Run("held by this box", func(t *testing.T) { |
| + fx := newDrillFx(t, "a.example.com") |
| + fx.stubVerify(func(context.Context, string, string, uint64) (uint32, error) { return 2, 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 = live |
| + v := fx.run(context.Background(), fx.drill(), rt, nil)["a.example.com"] |
| + if v.Result != dbverify.ResultFailed || v.Freshness != dbverify.FreshnessStale || fx.localReads.Load() != 1 { |
| + t.Fatalf("verdict %+v (%d local reads), want failed/stale", v, fx.localReads.Load()) |
| + } |
| + }) |
| + t.Run("held by this box, keeping up", func(t *testing.T) { |
| + fx := newDrillFx(t, "a.example.com") |
| + fx.stubVerify(func(context.Context, string, string, uint64) (uint32, error) { return 1 << 20, 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 = live |
| + v := fx.run(context.Background(), fx.drill(), rt, nil)["a.example.com"] |
| + if !v.OK() || v.Freshness != dbverify.FreshnessNotStale { |
| + t.Fatalf("verdict %+v, want passed/not_stale", v) |
| + } |
| + }) |
| +} |
| + |
| +// TestVerifyHibernatingBudget: the budget is measured on the run's clock; |
| +// once it is spent no further host starts, and those left keep their |
| +// earlier verdict (or are not_reached) through Merge. Oldest first means the |
| +// hosts dropped are the most recently verified. |
| +func TestVerifyHibernatingBudget(t *testing.T) { |
| + hosts := []string{"a.example.com", "b.example.com", "c.example.com", "d.example.com", "e.example.com", "f.example.com"} |
| + fx := newDrillFx(t, hosts...) |
| + prior := &dbverify.Record{V: 2, Box: fxSelf, Hosts: map[string]dbverify.Verdict{ |
| + "a.example.com": {Result: dbverify.ResultPassed, VerifiedAt: at("2026-11-10T03:00:00Z"), Identity: fx.identity("a.example.com")}, |
| + "b.example.com": {Result: dbverify.ResultPassed, VerifiedAt: at("2026-11-11T03:00:00Z"), Identity: fx.identity("b.example.com")}, |
| + "c.example.com": {Result: dbverify.ResultPassed, VerifiedAt: at("2026-11-05T03:00:00Z"), Identity: fx.identity("c.example.com")}, |
| + }} |
| + fx.stubVerify(func(context.Context, string, string, uint64) (uint32, error) { |
| + fx.clock.Advance(10 * time.Minute) |
| + return 1, nil |
| + }) |
| + d := fx.drill() |
| + d.Budget = 25 * time.Minute |
| + ordered := OldestFirst(fx.routes(hosts...), prior) |
| + got := fx.run(context.Background(), d, ordered, nil) |
| + |
| + // Never verified (d, e, f) first, then c (oldest); 0, 10 and 20 |
| + // minutes in a host starts, at 30 the budget is spent. |
| + var visited []string |
| + for h := range got { |
| + visited = append(visited, h) |
| + } |
| + slices.Sort(visited) |
| + if want := []string{"d.example.com", "e.example.com", "f.example.com"}; !slices.Equal(visited, want) { |
| + t.Fatalf("visited %v, want %v", visited, want) |
| + } |
| + rec := dbverify.Merge(prior, fxSelf, fx.clock.Now(), hosts, got) |
| + for _, h := range []string{"a.example.com", "b.example.com", "c.example.com"} { |
| + if v := rec.Hosts[h]; v != prior.Hosts[h] { |
| + t.Fatalf("%s lost its earlier verdict: %+v", h, v) |
| + } |
| + } |
| + |
| + // With no earlier verdict, an unreached host is not_reached. |
| + fx2 := newDrillFx(t, hosts...) |
| + fx2.stubVerify(func(context.Context, string, string, uint64) (uint32, error) { |
| + fx2.clock.Advance(10 * time.Minute) |
| + return 1, nil |
| + }) |
| + d2 := fx2.drill() |
| + d2.Budget = 25 * time.Minute |
| + got = fx2.run(context.Background(), d2, fx2.routes(hosts...), nil) |
| + rec = dbverify.Merge(nil, fxSelf, fx2.clock.Now(), hosts, got) |
| + for _, h := range hosts[3:] { |
| + if v := rec.Hosts[h]; !v.Unverified() || v.Reason != dbverify.ReasonNotReached { |
| + t.Fatalf("%s past the budget: %+v, want not_reached", h, v) |
| + } |
| + } |
| +} |
| + |
| +// ctxStore fails any write made under a context that has already ended, |
| +// which is how a publish through the run's own (expired) context would |
| +// look in S3. |
| +type ctxStore struct { |
| + release.Store |
| + mu sync.Mutex |
| + puts []*dbverify.Record |
| +} |
| + |
| +func (s *ctxStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + if err := ctx.Err(); err != nil { |
| + return "", err |
| + } |
| + if strings.HasPrefix(key, "control/verify/") { |
| + var rec dbverify.Record |
| + if err := json.Unmarshal(body, &rec); err == nil { |
| + s.mu.Lock() |
| + s.puts = append(s.puts, &rec) |
| + s.mu.Unlock() |
| + } |
| + } |
| + return s.Store.Put(ctx, key, body, ifMatch) |
| +} |
| + |
| +func (s *ctxStore) published() []*dbverify.Record { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return slices.Clone(s.puts) |
| +} |
| + |
| +// TestVerifyHibernatingDeadlineStopsBlockedWork: the budget is a deadline, |
| +// not only a start cut-off. A restore blocked in its download returns at |
| +// the deadline, its scratch is removed and it gets no verdict, and what |
| +// finished before it is published through the publisher's own context |
| +// (P-10). |
| +func TestVerifyHibernatingDeadlineStopsBlockedWork(t *testing.T) { |
| + fx := newDrillFx(t, "a.example.com", "b.example.com", "c.example.com", "d.example.com") |
| + store := &ctxStore{Store: fx.store} |
| + fx.store = store |
| + fx.stubVerify(func(ctx context.Context, prefix, dir string, _ uint64) (uint32, error) { |
| + if !strings.HasSuffix(prefix, "c.example.com") { |
| + return 1, nil |
| + } |
| + // A partial download, then a stall only the deadline ends. |
| + if err := os.WriteFile(filepath.Join(dir, "verify-c.example.com.db.tmp"), []byte("partial"), 0o600); err != nil { |
| + t.Error(err) |
| + } |
| + <-ctx.Done() |
| + return 0, fmt.Errorf("restore stopped: %w", ctx.Err()) |
| + }) |
| + d := fx.drill() |
| + d.Budget = 300 * time.Millisecond |
| + dataDir := t.TempDir() |
| + pub := newVerifyPublisher(context.Background(), store, fxSelf, nil, |
| + []string{"a.example.com", "b.example.com", "c.example.com", "d.example.com"}, nil, dataDir, fx.clock.Now, t.Logf) |
| + |
| + start := time.Now() |
| + got := fx.run(context.Background(), d, fx.routes("a.example.com", "b.example.com", "c.example.com", "d.example.com"), pub.publish) |
| + if el := time.Since(start); el > 10*time.Second { |
| + t.Fatalf("the blocked restore held the run for %s", el) |
| + } |
| + if _, ok := got["c.example.com"]; ok { |
| + t.Fatalf("the abandoned host has a verdict: %+v", got["c.example.com"]) |
| + } |
| + if _, ok := got["d.example.com"]; ok { |
| + t.Fatal("a host after the deadline was drilled") |
| + } |
| + fx.scratchEmpty() |
| + |
| + rec, err := dbverify.Load(context.Background(), store, fxSelf) |
| + if err != nil || rec == nil { |
| + t.Fatalf("nothing published after the deadline: %v", err) |
| + } |
| + for _, h := range []string{"a.example.com", "b.example.com"} { |
| + if !rec.Hosts[h].OK() { |
| + t.Fatalf("%s finished before the deadline but published %+v", h, rec.Hosts[h]) |
| + } |
| + } |
| + for _, h := range []string{"c.example.com", "d.example.com"} { |
| + if v := rec.Hosts[h]; v.Reason != dbverify.ReasonNotReached { |
| + t.Fatalf("%s: %+v, want not_reached", h, v) |
| + } |
| + } |
| +} |
| |
| - // And it must reach the published record as a failure, so the operator |
| - // sees it without a session on the box. |
| - rec := dbverify.Merge(nil, "box-a", now, []string{"frozen.example.com"}, got) |
| - if rec.Failures() != 1 { |
| - t.Fatalf("Failures() = %d, want 1", rec.Failures()) |
| +// TestVerifyHibernatingPublishesPeriodically: a publish at each interval |
| +// mark with everything finished so far, and one at the end; a run killed |
| +// between marks has what the last publish held in the bucket. |
| +func TestVerifyHibernatingPublishesPeriodically(t *testing.T) { |
| + var hosts []string |
| + for i := 0; i < 7; i++ { |
| + hosts = append(hosts, fmt.Sprintf("h%d.example.com", i)) |
| + } |
| + fx := newDrillFx(t, hosts...) |
| + store := &ctxStore{Store: fx.store} |
| + fx.store = store |
| + var atSeventh *dbverify.Record |
| + fx.stubVerify(func(_ context.Context, prefix, _ string, _ uint64) (uint32, error) { |
| + if strings.HasSuffix(prefix, "h6.example.com") { |
| + // What a kill here would leave in the bucket. |
| + atSeventh, _ = dbverify.Load(context.Background(), store, fxSelf) |
| + } |
| + fx.clock.Advance(4 * time.Minute) |
| + return 1, nil |
| + }) |
| + d := fx.drill() |
| + d.PublishEvery = 10 * time.Minute |
| + var sizes []int |
| + pub := newVerifyPublisher(context.Background(), store, fxSelf, nil, hosts, nil, t.TempDir(), fx.clock.Now, t.Logf) |
| + fx.run(context.Background(), d, fx.routes(hosts...), func(r map[string]dbverify.Verdict) { |
| + sizes = append(sizes, len(r)) |
| + pub.publish(r) |
| + }) |
| + // Hosts end at 4, 8, 12, 16, 20, 24 and 28 minutes: the 10-minute mark |
| + // is first seen at 12, the 20-minute one at 20, then the end. |
| + if !slices.Equal(sizes, []int{3, 5, 7}) { |
| + t.Fatalf("published with %v verdicts, want [3 5 7]", sizes) |
| + } |
| + if atSeventh == nil { |
| + t.Fatal("nothing in the bucket before the last host") |
| + } |
| + passed := 0 |
| + for _, v := range atSeventh.Hosts { |
| + if v.OK() { |
| + passed++ |
| + } |
| + } |
| + if passed != 5 { |
| + t.Fatalf("a run killed during the seventh host leaves %d passes in the bucket, want 5", passed) |
| + } |
| +} |
| + |
| +// TestVerifyHibernatingStreakOncePerRun: every publish in a run merges into |
| +// the record loaded at its start, so an unverified streak moves by one per |
| +// run however many times the run publishes (P2-16). |
| +func TestVerifyHibernatingStreakOncePerRun(t *testing.T) { |
| + hosts := []string{"moving.example.com", "b.example.com", "c.example.com", "d.example.com", "e.example.com"} |
| + fx := newDrillFx(t, hosts...) |
| + fx.putRecord(fxAccount, "moving.example.com", time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC), func(r *provision.Record) { |
| + r.Move = &provision.MoveState{ID: "mv_x", To: "ie", State: "requested"} |
| + }) |
| + store := &ctxStore{Store: fx.store} |
| + fx.store = store |
| + id := fx.identity("moving.example.com") |
| + prior := &dbverify.Record{V: 2, Box: fxSelf, CheckedAt: at("2026-11-11T03:00:00Z"), Hosts: map[string]dbverify.Verdict{ |
| + "moving.example.com": {Result: dbverify.ResultUnverified, Reason: ReasonMoving, Identity: id, UnverifiedRuns: 2, |
| + FirstSeen: at("2026-11-01T03:00:00Z"), VerifiedAt: at("2026-11-11T03:00:00Z")}, |
| + }} |
| + if err := dbverify.Publish(context.Background(), store, prior); err != nil { |
| + t.Fatal(err) |
| + } |
| + fx.stubVerify(func(context.Context, string, string, uint64) (uint32, error) { |
| + fx.clock.Advance(10 * time.Minute) |
| + return 1, nil |
| + }) |
| + d := fx.drill() |
| + d.PublishEvery = 10 * time.Minute |
| + pub := newVerifyPublisher(context.Background(), store, fxSelf, prior, hosts, nil, t.TempDir(), fx.clock.Now, t.Logf) |
| + // The unverified host first, so every publish of the run carries it. |
| + fx.run(context.Background(), d, fx.routes(hosts...), pub.publish) |
| + |
| + puts := store.published()[1:] // the seeded prior is the first |
| + if len(puts) != 5 { |
| + t.Fatalf("%d publishes, want four periodic and a final one", len(puts)) |
| + } |
| + for i, rec := range puts { |
| + if n := rec.Hosts["moving.example.com"].UnverifiedRuns; n != 3 { |
| + t.Fatalf("publish %d: the streak is %d, want 3", i, n) |
| + } |
| + } |
| +} |
| + |
| +// --- host selection on group boxes ------------------------------------------- |
| + |
| +// The run-level fixture: a registry of sleeping hosts, this box's self |
| +// record, and a hibernateRun over the drill fixture. |
| +type runFx struct { |
| + *drillFx |
| + dataDir string |
| + regPath string |
| + logs *bytes.Buffer |
| +} |
| + |
| +func newRunFx(t *testing.T, hosts ...string) *runFx { |
| + t.Helper() |
| + fx := &runFx{drillFx: newDrillFx(t, hosts...), dataDir: t.TempDir(), logs: &bytes.Buffer{}} |
| + fx.regPath = filepath.Join(fx.dataDir, "registry.db") |
| + reg, err := registry.Open(fx.regPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, h := range hosts { |
| + if err := reg.Upsert(registry.Route{Host: h, DBPath: filepath.Join(fx.dataDir, h+".db"), Hibernate: true, Account: fxAccount, App: fxApp}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + reg.Close() |
| + return fx |
| +} |
| + |
| +func (fx *runFx) writeSelf(ref string, group bool) { |
| + fx.t.Helper() |
| + if err := boxself.Write(fx.dataDir, boxself.Self{Ref: ref, Group: group, At: fx.clock.Now()}); err != nil { |
| + fx.t.Fatal(err) |
| + } |
| +} |
| + |
| +func (fx *runFx) writeAssignment(at time.Time, hosts map[string]string, unknown ...string) { |
| + fx.t.Helper() |
| + if err := boxself.WriteAssignment(fx.dataDir, boxself.Assignment{At: at, Hosts: hosts, Unknown: unknown}); err != nil { |
| + fx.t.Fatal(err) |
| + } |
| +} |
| + |
| +func (fx *runFx) runner() hibernateRun { |
| + return hibernateRun{ |
| + Cfg: fx.cfg, |
| + OpenStore: func(context.Context) (release.Store, error) { return fx.store, nil }, |
| + Region: fxRegion, |
| + DataDir: fx.dataDir, |
| + RegPath: fx.regPath, |
| + TmpDir: fx.tmp, |
| + Now: fx.clock.Now, |
| + Budget: 45 * time.Minute, |
| + PublishEvery: 10 * time.Minute, |
| + Logf: func(f string, a ...any) { fmt.Fprintf(fx.logs, f+"\n", a...) }, |
| + } |
| +} |
| + |
| +func (fx *runFx) published(ref string) *dbverify.Record { |
| + fx.t.Helper() |
| + rec, err := dbverify.Load(context.Background(), fx.store, ref) |
| + if err != nil { |
| + fx.t.Fatal(err) |
| + } |
| + return rec |
| +} |
| + |
| +func (fx *runFx) localCopy() (*dbverify.Record, error) { |
| + body, err := os.ReadFile(filepath.Join(fx.dataDir, "monitor", "verify.json")) |
| + if err != nil { |
| + return nil, err |
| + } |
| + var rec dbverify.Record |
| + if err := json.Unmarshal(body, &rec); err != nil { |
| + return nil, err |
| + } |
| + return &rec, nil |
| +} |
| + |
| +func sortedHosts(rec *dbverify.Record) []string { |
| + if rec == nil { |
| + return nil |
| + } |
| + var out []string |
| + for h := range rec.Hosts { |
| + out = append(out, h) |
| + } |
| + slices.Sort(out) |
| + return out |
| +} |
| + |
| +// TestVerifyHibernatingGroupAssignment (P-9, P2-9, F2-1, F2-6). |
| +func TestVerifyHibernatingGroupAssignment(t *testing.T) { |
| + hosts := []string{"a.example.com", "b.example.com", "c.example.com", "d.example.com", "e.example.com", "f.example.com"} |
| + assign := map[string]string{ |
| + "a.example.com": "box-a", "b.example.com": "box-b", "c.example.com": "box-c", |
| + "d.example.com": "box-a", "e.example.com": "box-b", "f.example.com": "box-c", |
| + } |
| + |
| + t.Run("three boxes drill disjoint sets covering every host", func(t *testing.T) { |
| + store := release.NewDirStore(t.TempDir()) |
| + drilled := map[string][]string{} |
| + for _, ref := range []string{"box-a", "box-b", "box-c"} { |
| + fx := newRunFx(t, hosts...) |
| + fx.store = store |
| + for _, h := range hosts { |
| + fx.putRecord(fxAccount, h, time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC), nil) |
| + } |
| + fx.writeSelf(ref, true) |
| + fx.writeAssignment(fx.clock.Now().Add(-time.Minute), assign) |
| + var mine []string |
| + fx.stubVerify(func(_ context.Context, prefix, _ string, _ uint64) (uint32, error) { |
| + mine = append(mine, filepath.Base(prefix)) |
| + return 1, nil |
| + }) |
| + if code := fx.runner().run(context.Background()); code != 0 { |
| + t.Fatalf("%s exited %d: %s", ref, code, fx.logs) |
| + } |
| + slices.Sort(mine) |
| + drilled[ref] = mine |
| + if got := sortedHosts(fx.published(ref)); !slices.Equal(got, mine) { |
| + t.Fatalf("%s's record names %v, it drilled %v", ref, got, mine) |
| + } |
| + } |
| + var all []string |
| + for ref, hs := range drilled { |
| + for _, h := range hs { |
| + if assign[h] != ref { |
| + t.Fatalf("%s drilled %s, assigned to %s", ref, h, assign[h]) |
| + } |
| + } |
| + all = append(all, hs...) |
| + } |
| + slices.Sort(all) |
| + if !slices.Equal(all, hosts) { |
| + t.Fatalf("drilled together %v, want each of %v once", all, hosts) |
| + } |
| + }) |
| + |
| + for name, write := range map[string]func(fx *runFx){ |
| + "stale assignment": func(fx *runFx) { fx.writeAssignment(fx.clock.Now().Add(-16*time.Minute), assign) }, |
| + "missing assignment": func(*runFx) {}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + fx := newRunFx(t, hosts...) |
| + fx.writeSelf("box-a", true) |
| + write(fx) |
| + fx.stubVerify(func(_ context.Context, prefix, _ string, _ uint64) (uint32, error) { |
| + t.Errorf("drilled %s with no usable assignment", prefix) |
| + return 1, nil |
| + }) |
| + if code := fx.runner().run(context.Background()); code != 0 { |
| + t.Fatalf("exited %d: %s", code, fx.logs) |
| + } |
| + rec := fx.published("box-a") |
| + if got := sortedHosts(rec); !slices.Equal(got, hosts) { |
| + t.Fatalf("record names %v, want every local host %v", got, hosts) |
| + } |
| + for h, v := range rec.Hosts { |
| + if !v.Unverified() || v.Reason != dbverify.ReasonNoAssignment { |
| + t.Fatalf("%s: %+v, want unverified/no_assignment", h, v) |
| + } |
| + } |
| + if !strings.Contains(fx.logs.String(), boxself.AssignmentPath(fx.dataDir)) { |
| + t.Fatalf("the log does not name the assignment file:\n%s", fx.logs) |
| + } |
| + }) |
| + } |
| + |
| + t.Run("unknown and unlisted hosts", func(t *testing.T) { |
| + fx := newRunFx(t, hosts...) |
| + fx.writeSelf("box-a", true) |
| + fx.writeAssignment(fx.clock.Now(), map[string]string{"a.example.com": "box-a", "b.example.com": "box-b"}, |
| + "c.example.com", "d.example.com") |
| + if code := fx.runner().run(context.Background()); code != 0 { |
| + t.Fatalf("exited %d: %s", code, fx.logs) |
| + } |
| + rec := fx.published("box-a") |
| + want := []string{"a.example.com", "c.example.com", "d.example.com", "e.example.com", "f.example.com"} |
| + if got := sortedHosts(rec); !slices.Equal(got, want) { |
| + t.Fatalf("record names %v, want %v (b is box-b's)", got, want) |
| + } |
| + if !rec.Hosts["a.example.com"].OK() { |
| + t.Fatalf("a: %+v", rec.Hosts["a.example.com"]) |
| + } |
| + for _, h := range want[1:] { |
| + if v := rec.Hosts[h]; v.Reason != dbverify.ReasonNoAssignment { |
| + t.Fatalf("%s: %+v, want no_assignment", h, v) |
| + } |
| + } |
| + }) |
| + |
| + t.Run("rewriting the assignment mid-run changes nothing", func(t *testing.T) { |
| + fx := newRunFx(t, hosts...) |
| + fx.writeSelf("box-a", true) |
| + fx.writeAssignment(fx.clock.Now(), assign) |
| + var mine []string |
| + fx.stubVerify(func(_ context.Context, prefix, _ string, _ uint64) (uint32, error) { |
| + mine = append(mine, filepath.Base(prefix)) |
| + everything := map[string]string{} |
| + for _, h := range hosts { |
| + everything[h] = "box-b" |
| + } |
| + fx.writeAssignment(fx.clock.Now(), everything) |
| + return 1, nil |
| + }) |
| + if code := fx.runner().run(context.Background()); code != 0 { |
| + t.Fatalf("exited %d: %s", code, fx.logs) |
| + } |
| + slices.Sort(mine) |
| + if want := []string{"a.example.com", "d.example.com"}; !slices.Equal(mine, want) { |
| + t.Fatalf("drilled %v, want the run-start assignment's %v", mine, want) |
| + } |
| + if got := sortedHosts(fx.published("box-a")); !slices.Equal(got, mine) { |
| + t.Fatalf("record names %v", got) |
| + } |
| + }) |
| +} |
| + |
| +// A fixed box drills every local sleeping host, whatever an assignment file |
| +// says. |
| +func TestRunHibernateVerifyFixedBoxDrillsEveryHost(t *testing.T) { |
| + fx := newRunFx(t, "a.example.com", "b.example.com") |
| + fx.writeSelf(fxSelf, false) |
| + fx.writeAssignment(fx.clock.Now(), map[string]string{"a.example.com": "box-b", "b.example.com": "box-b"}) |
| + if code := fx.runner().run(context.Background()); code != 0 { |
| + t.Fatalf("exited %d: %s", code, fx.logs) |
| + } |
| + rec := fx.published(fxSelf) |
| + for _, h := range []string{"a.example.com", "b.example.com"} { |
| + if !rec.Hosts[h].OK() { |
| + t.Fatalf("%s: %+v", h, rec.Hosts[h]) |
| + } |
| + } |
| +} |
| + |
| +// --- the run ------------------------------------------------------------------- |
| + |
| +// TestRunHibernateVerifyRefusesWithoutSelfRef: a box whose agent has not |
| +// written (or stopped rewriting) its self record publishes nothing rather |
| +// than publish under a name that is not its own. |
| +func TestRunHibernateVerifyRefusesWithoutSelfRef(t *testing.T) { |
| + for name, setup := range map[string]func(fx *runFx){ |
| + "no self.json": func(*runFx) {}, |
| + "stale self.json": func(fx *runFx) { |
| + if err := boxself.Write(fx.dataDir, boxself.Self{Ref: fxSelf, At: fx.clock.Now().Add(-16 * time.Minute)}); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + fx := newRunFx(t, "a.example.com") |
| + setup(fx) |
| + restored := false |
| + fx.stubVerify(func(context.Context, string, string, uint64) (uint32, error) { |
| + restored = true |
| + return 1, nil |
| + }) |
| + if code := fx.runner().run(context.Background()); code == 0 { |
| + t.Fatal("exited 0 with no fresh self record") |
| + } |
| + if restored { |
| + t.Fatal("drilled with no self record") |
| + } |
| + keys, err := fx.store.List(context.Background(), "control/") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(keys) != 0 { |
| + t.Fatalf("published %v", keys) |
| + } |
| + if !strings.Contains(fx.logs.String(), boxself.SelfPath(fx.dataDir)) { |
| + t.Fatalf("the log does not name %s:\n%s", boxself.SelfPath(fx.dataDir), fx.logs) |
| + } |
| + if _, err := fx.localCopy(); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("a local copy was written: %v", err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestRunHibernateVerifyWritesLocalAlertCopy: the local copy is the record |
| +// as published, for the agent's alert loop. |
| +func TestRunHibernateVerifyWritesLocalAlertCopy(t *testing.T) { |
| + fx := newRunFx(t, "a.example.com", "b.example.com") |
| + fx.writeSelf(fxSelf, false) |
| + if code := fx.runner().run(context.Background()); code != 0 { |
| + t.Fatalf("exited %d: %s", code, fx.logs) |
| + } |
| + local, err := fx.localCopy() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + pub := fx.published(fxSelf) |
| + lb, _ := json.Marshal(local) |
| + pb, _ := json.Marshal(pub) |
| + if !bytes.Equal(lb, pb) { |
| + t.Fatalf("local copy\n%s\ndiffers from the published record\n%s", lb, pb) |
| + } |
| + st, err := os.Stat(filepath.Join(fx.dataDir, "monitor", "verify.json")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if st.Mode().Perm() != 0o644 { |
| + t.Fatalf("local copy mode %v, want 0644", st.Mode().Perm()) |
| + } |
| + ents, _ := os.ReadDir(filepath.Join(fx.dataDir, "monitor")) |
| + for _, e := range ents { |
| + if strings.HasSuffix(e.Name(), ".tmp") { |
| + t.Fatalf("scratch %s left in monitor/", e.Name()) |
| + } |
| + } |
| + fx.scratchEmpty() |
| +} |
| + |
| +// A damaged replica fails the run; an unverified one does not. |
| +func TestRunHibernateVerifyExitCarriesFailuresOnly(t *testing.T) { |
| + fx := newRunFx(t, "a.example.com", "b.example.com") |
| + fx.writeSelf(fxSelf, false) |
| + fx.deleteRecord(fxAccount, "b.example.com") |
| + if code := fx.runner().run(context.Background()); code != 0 { |
| + t.Fatalf("an unverified host failed the run: %d", code) |
| + } |
| + fx.stubVerify(func(context.Context, string, string, uint64) (uint32, error) { |
| + return 0, errors.New("integrity_check: page 4 corrupt") |
| + }) |
| + if code := fx.runner().run(context.Background()); code == 0 { |
| + t.Fatal("a damaged replica exited 0") |
| + } |
| +} |
| + |
| +// TestRunHibernateVerifyEmptyFleetClearsPrior (P-13). |
| +func TestRunHibernateVerifyEmptyFleetClearsPrior(t *testing.T) { |
| + t.Run("with a prior record", func(t *testing.T) { |
| + fx := newRunFx(t) |
| + fx.writeSelf(fxSelf, false) |
| + prior := &dbverify.Record{V: 2, Box: fxSelf, CheckedAt: at("2026-11-11T03:00:00Z"), Hosts: map[string]dbverify.Verdict{ |
| + "gone.example.com": {Result: dbverify.ResultFailed, Reason: ReasonRestoreError}, |
| + }} |
| + if err := dbverify.Publish(context.Background(), fx.store, prior); err != nil { |
| + t.Fatal(err) |
| + } |
| + if code := fx.runner().run(context.Background()); code != 0 { |
| + t.Fatalf("exited %d: %s", code, fx.logs) |
| + } |
| + rec := fx.published(fxSelf) |
| + if rec == nil || len(rec.Hosts) != 0 || !rec.CheckedAt.Equal(fx.clock.Now()) { |
| + t.Fatalf("published %+v, want an empty record checked now", rec) |
| + } |
| + local, err := fx.localCopy() |
| + if err != nil || len(local.Hosts) != 0 { |
| + t.Fatalf("local copy %+v, %v; want an empty record", local, err) |
| + } |
| + }) |
| + t.Run("with none", func(t *testing.T) { |
| + fx := newRunFx(t) |
| + fx.writeSelf(fxSelf, false) |
| + if code := fx.runner().run(context.Background()); code != 0 { |
| + t.Fatalf("exited %d: %s", code, fx.logs) |
| + } |
| + if rec := fx.published(fxSelf); rec != nil { |
| + t.Fatalf("published %+v with nothing to clear", rec) |
| + } |
| + if _, err := fx.localCopy(); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("a local copy was written: %v", err) |
| + } |
| + }) |
| + t.Run("every host assigned elsewhere", func(t *testing.T) { |
| + fx := newRunFx(t, "a.example.com") |
| + fx.writeSelf(fxSelf, true) |
| + fx.writeAssignment(fx.clock.Now(), map[string]string{"a.example.com": "box-b"}) |
| + prior := &dbverify.Record{V: 2, Box: fxSelf, Hosts: map[string]dbverify.Verdict{ |
| + "a.example.com": {Result: dbverify.ResultPassed}, |
| + }} |
| + if err := dbverify.Publish(context.Background(), fx.store, prior); err != nil { |
| + t.Fatal(err) |
| + } |
| + if code := fx.runner().run(context.Background()); code != 0 { |
| + t.Fatalf("exited %d: %s", code, fx.logs) |
| + } |
| + if rec := fx.published(fxSelf); rec == nil || len(rec.Hosts) != 0 { |
| + t.Fatalf("published %+v, want an empty record", rec) |
| + } |
| + }) |
| +} |
| + |
| +// Review focus 1: a host that moved off this box leaves its record on the |
| +// next run, and a host mid-move gets no pass or failure. |
| +func TestRunHibernateVerifyDropsAMovedHost(t *testing.T) { |
| + fx := newRunFx(t, "stays.example.com", "moving.example.com") |
| + fx.writeSelf(fxSelf, false) |
| + fx.putRecord(fxAccount, "moving.example.com", time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC), func(r *provision.Record) { |
| + r.Move = &provision.MoveState{ID: "mv_x", To: "ie", State: "requested"} |
| + }) |
| + prior := &dbverify.Record{V: 2, Box: fxSelf, Hosts: map[string]dbverify.Verdict{ |
| + "left.example.com": {Result: dbverify.ResultPassed, VerifiedAt: at("2026-11-10T03:00:00Z")}, |
| + }} |
| + if err := dbverify.Publish(context.Background(), fx.store, prior); err != nil { |
| + t.Fatal(err) |
| + } |
| + if code := fx.runner().run(context.Background()); code != 0 { |
| + t.Fatalf("exited %d: %s", code, fx.logs) |
| + } |
| + rec := fx.published(fxSelf) |
| + if want := []string{"moving.example.com", "stays.example.com"}; !slices.Equal(sortedHosts(rec), want) { |
| + t.Fatalf("record names %v, want %v", sortedHosts(rec), want) |
| + } |
| + if v := rec.Hosts["moving.example.com"]; !v.Unverified() || v.Reason != ReasonMoving { |
| + t.Fatalf("mid-move host: %+v", v) |
| } |
| } |