carlos / platform Public

ops: hibernate-verify drills per box, bracketed, on a budget (#898)

The nightly run publishes control/verify/<ref>.json under the agent's
self reference (refusing to run without a fresh self.json), binds each
verdict to the instance identity captured before planning and confirmed
after the restore, restores exactly the planned TXID (one replan when
compaction moves it, then plan_moved), and judges freshness only when
this box holds the live lease. A group box drills only the hosts its
run-start assignment gives it; the rest of its hosts are no_assignment.

The 45-minute budget is a deadline every step runs under; each publish
(every 10 minutes and at the end) merges into the run-start record on
its own 30-second context and rewrites <data>/monitor/verify.json. An
empty fleet clears an existing record. -max now defaults to 0.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 6de4a16fc69f12a1c4994a177df59dbc3877a63f parent 7af5822
3 files changed, +1,945 −237
  • internal/ops/hibernate_verify.go +403 −72
  • internal/ops/hibernate_verify_test.go +1,269 −88
  • internal/ops/ops.go +273 −77

Intent

Human

<task-notification> <task-id>a11baaeb200927c29</task-id> <tool-use-id>toolu_01U9E5jcvhKeQRnrMNys4pSi</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ab362fc0-f177-4a7f-a92e-4a29ea210aad/tasks/a11baaeb200927c29.output</output-file> <status>completed</status> <summary>Agent "Implement slice 2a Task 4" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Status:** DONE. All three fixes are in commit 7af5822e on top of 750bd288 (not pushed). 1. **Identity across incarnations:** a verdict with no identity now keeps the previous verdict's last known identity. In the sequence A passed, unknown night, B, B now starts with fresh `FirstSeen`, `LastDecidedAt` and streak instead of A's. A, unknown, A still carries everything through. 2. **One ref validator:** `KeyFor` now calls `boxself.ValidRef`, which was already exported, and the copy is gone. `go list -deps` shows boxself uses only the standard library and is dbverify's only new project dependency, so there is no import cycle. 3. **Streak hold:** I added `ReasonNoAssignment` ("no_assignment"). `not_reached` and `no_assignment` now leave `UnverifiedRuns` as it was. Other unverified reasons add one, and passed or failed resets it to 0. **Tests:** I added `TestMergeNotReachedHoldsTheStreak` and `TestMergeUnknownIdentityKeepsTheLastKnown`, and extended the A, unknown, A case. Both new tests failed before the fix and pass after it. The targeted dbverify, release and hostops tests pass, as do the ops hibernate tests and the root moves-copy scan. `go build ./...` and `go vet` are clean, and the host and ops tests compile. **Concerns:** `TestPlan9B8RecordWriteCensus` still fails as expected and is left for Task 9. For Task 5: the temporary ops code records a run cut short as `not_reached`, which now holds the streak, so Task 5 should record a group host with no usable assignment as `ReasonNoAssignment`. **Report** (fix round appended): /home/paulca/amadan.net/carlos/platform/.claude/worktrees/member-backups-2a/.superpowers/sdd/2026-11-11-member-backups-slice2a/task-4-report.md</result> <usage><subagent_tokens>162195</subagent_tokens><tool_uses>7</tool_uses><duration_ms>175052</duration_ms></usage> </task-notification>

Attributed to this commit: 24.1 g CO₂e (3,055,993 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on member-backups-2a, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/ops/hibernate_verify.go b/internal/ops/hibernate_verify.go
index acc540aba..6b892ac25 100644
--- a/internal/ops/hibernate_verify.go
+++ b/internal/ops/hibernate_verify.go
@@ -21,22 +21,35 @@ import (
"context"
"errors"
"fmt"
+ "os"
+ "slices"
"sort"
"time"
+ "github.com/benbjohnson/litestream"
+
"github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/boxself"
+ "github.com/carlosframework/platform/internal/dbdoor"
+ "github.com/carlosframework/platform/internal/dbreads"
"github.com/carlosframework/platform/internal/dbverify"
+ "github.com/carlosframework/platform/internal/hafresh"
"github.com/carlosframework/platform/internal/lease"
"github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
)
// HibernatingRoute is one instance this drill owns: the host names its replica
// prefix, and DBPath is the live database the replica is supposed to be
// tracking — carried because "restores clean" and "is current" are two
-// different questions and the second one needs the source.
+// different questions and the second one needs the source. Account and App
+// name the instance's provision record, which the identity bracket reads:
+// Account as the record files it (a route's "" is the ops account).
type HibernatingRoute struct {
- Host string
- DBPath string
+ Host string
+ DBPath string
+ Account string
+ App string
}
// HibernatingHosts lists the routes whose replication the activator owns —
@@ -58,100 +71,404 @@ func HibernatingHosts(reg *registry.Registry) ([]HibernatingRoute, error) {
// FleetDBsWithSkipped's exclusion, the same expression: a resident
// rootfs row is drilled here, never by box-wide litestream.
if !r.Stateless && r.ActivatorLeased() && r.DBPath != "" {
- hosts = append(hosts, HibernatingRoute{Host: r.Host, DBPath: r.DBPath})
+ hosts = append(hosts, HibernatingRoute{Host: r.Host, DBPath: r.DBPath,
+ Account: registry.EffectiveAccount(r.Account), App: r.App})
}
}
sort.Slice(hosts, func(i, j int) bool { return hosts[i].Host < hosts[j].Host })
return hosts, nil
}
-// verifyOne is the seam the tests drive; production points it at S3.
-var verifyOne = lease.VerifyReplica
+// The reasons the drill gives a failed or unverified verdict, besides
+// dbverify's own not_reached and no_assignment.
+const (
+ // ReasonRecordChanged: the instance's record was missing, refused, or
+ // named another instance when the bracket opened or closed.
+ ReasonRecordChanged = "record_changed"
+ // ReasonMoving: the instance was mid-move when the bracket opened or
+ // closed.
+ ReasonMoving = "moving"
+ // ReasonRecordUnreadable: the record could not be read to open or close
+ // the bracket, so nothing the restore found can be bound to an
+ // instance.
+ ReasonRecordUnreadable = "record_unreadable"
+ // ReasonNothingReplicated: the replica holds nothing to restore yet.
+ ReasonNothingReplicated = "nothing_replicated"
+ // ReasonPlanMoved: the planned position was compacted away before it
+ // could be restored, twice running.
+ ReasonPlanMoved = "plan_moved"
+ // ReasonRestoreError: the replica would not plan, restore or pass its
+ // integrity check (a failed verdict).
+ ReasonRestoreError = "restore_error"
+ // ReasonStale: on the box holding the lease, the replica restores but
+ // has stopped tracking the live database (a failed verdict).
+ ReasonStale = "stale"
+)
+
+// assignmentMaxAge is how old a group box's drill assignment may be when
+// the run reads it: the agent rewrites it every five minutes, so an older
+// one comes from an agent that has stopped.
+const assignmentMaxAge = 15 * time.Minute
+
+// The seams the tests drive; production points them at the hibernate
+// bucket and the box's own disk.
+var (
+ openReplica = func(ctx context.Context, bucket, prefix, region string) (dbdoor.ReplicaReader, error) {
+ return lease.ReadReplicaClient(ctx, bucket, prefix, region)
+ }
+ verifyAt = lease.VerifyReplicaAt
+ lockState = lease.LockState
+ localFreshness = hibernateFreshness
+)
-// VerifyHibernating restore-drills up to max of the given hosts and returns a
-// verdict per host it VISITED. Hosts beyond the cap are simply absent from
-// the result — Merge keeps their previous verdict and its old timestamp
-// rather than inventing coverage for them.
+// Drill is one run's settings. Cfg names the hibernate bucket; Store is the
+// deployment bucket the provision records are read from; Region is this
+// box's region, which an instance's record must name; SelfRef is this
+// box's reference, the owner its lease locks carry; TmpDir is the on-disk
+// scratch each restore lands in.
+//
+// Budget is the run's deadline (none when zero): no host starts once it is
+// spent by the run's clock, and the context every step runs under ends
+// when it passes, so a restore blocked in its download is abandoned too.
+// Max caps the hosts drilled (none when zero). PublishEvery is how often
+// the run hands what it has finished to its publisher (only at the end
+// when zero).
+type Drill struct {
+ Cfg *activator.Config
+ Store release.Store
+ Region string
+ SelfRef string
+ TmpDir string
+ Budget time.Duration
+ Max int
+ PublishEvery time.Duration
+}
+
+// VerifyHibernating restore-drills the given hosts in order and returns a
+// verdict per host it finished. A host abandoned at the deadline, and the
+// hosts after the budget or the cap, are absent: Merge keeps their earlier
+// verdict, or records them not_reached, rather than inventing coverage.
//
// Order is the caller's: pass hosts oldest-verified-first so a fleet larger
-// than the cap is still covered completely, just over several days.
+// than one run's budget is still covered completely, just over several
+// nights.
+//
+// publish (when not nil) is handed everything finished so far at the first
+// host boundary past each PublishEvery mark and once at the end, always
+// from this goroutine. It must publish under its own context: the run's
+// may have ended by then.
//
-// The cap is not squeamishness — it is the same request-cost discipline that
-// set LeaseTTL. Each verification is a full restore: in-region S3→EC2
-// transfer is free, but the GETs and the restore CPU are not, and an
-// unbounded nightly drill over a growing fleet is a bill that grows with it.
-func VerifyHibernating(ctx context.Context, cfg *activator.Config, hosts []HibernatingRoute, max int, now time.Time, tmpDir string) map[string]dbverify.Verdict {
+// Each host is bracketed (P-11): its record is read before planning and
+// again after the last replica byte, and any difference discards what the
+// restore found. Freshness is judged only on the box that provably holds
+// the live lease (P-14).
+func VerifyHibernating(ctx context.Context, d Drill, hosts []HibernatingRoute, now func() time.Time, publish func(map[string]dbverify.Verdict)) map[string]dbverify.Verdict {
+ start := now()
+ runCtx, cancel := ctx, context.CancelFunc(func() {})
+ if d.Budget > 0 {
+ runCtx, cancel = context.WithTimeout(ctx, d.Budget)
+ }
+ defer cancel()
+
out := map[string]dbverify.Verdict{}
- for i, rt := range hosts {
- if max > 0 && i >= max {
+ snapshot := func() {
+ if publish != nil {
+ publish(cloneVerdicts(out))
+ }
+ }
+ next := start.Add(d.PublishEvery)
+ visited := 0
+ for _, rt := range hosts {
+ if d.Max > 0 && visited >= d.Max {
+ // A silent cap reads as full coverage: say what was left.
+ fmt.Printf("hibernate-verify: %d of %d hosts this run (--max %d); the rest keep their previous verdict\n",
+ visited, len(hosts), d.Max)
break
}
- host := rt.Host
- prefix := activator.HibernatePrefix(cfg.Prefix, host)
- counter, err := verifyOne(ctx, cfg.Bucket, prefix, cfg.Region, tmpDir)
- switch {
- case err == nil:
- // Restores clean — now the second question: is it CURRENT? 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.
- if f, detail := hibernateFreshness(rt.DBPath, counter); f == freshnessStale || f == freshnessNoSource {
- fresh := dbverify.FreshnessStale
- if f == freshnessNoSource {
- fresh = dbverify.FreshnessUnknown
+ if runCtx.Err() != nil || (d.Budget > 0 && !now().Before(start.Add(d.Budget))) {
+ fmt.Printf("hibernate-verify: the run's budget (%s) is spent after %d of %d hosts; the rest keep their previous verdict\n",
+ d.Budget, visited, len(hosts))
+ break
+ }
+ visited++
+ v, ok := d.drillOne(runCtx, rt, now)
+ if !ok {
+ fmt.Printf("abandoned %s: the run ended during its test; no verdict\n", rt.Host)
+ continue
+ }
+ out[rt.Host] = v
+ printVerdict(rt.Host, v)
+ if d.PublishEvery > 0 {
+ if t := now(); !t.Before(next) {
+ for !t.Before(next) {
+ next = next.Add(d.PublishEvery)
}
- out[host] = dbverify.Verdict{Result: dbverify.ResultFailed, Reason: "stale", Freshness: fresh, Prefix: prefix, VerifiedAt: now.UTC(), Detail: detail}
- fmt.Printf("STALE %s: %s\n", host, detail)
- continue
- }
- fresh := dbverify.FreshnessNotStale
- if rt.DBPath == "" {
- fresh = dbverify.FreshnessUnknown // nothing was compared
+ snapshot()
}
- out[host] = dbverify.Verdict{Result: dbverify.ResultPassed, Freshness: fresh, Prefix: prefix, VerifiedAt: now.UTC()}
- fmt.Printf("ok %s\n", host)
- case errors.Is(err, lease.ErrNoReplica):
- // Never replicated: a registered instance that has not woken yet.
- // Not a failure — but not a pass either, because nothing was
- // proven about anything.
- out[host] = dbverify.Verdict{Result: dbverify.ResultUnverified, Reason: "nothing_replicated", Prefix: prefix, VerifiedAt: now.UTC(), Detail: "no replica yet"}
- fmt.Printf("unverified %s: no replica yet (never woken)\n", host)
- case ctx.Err() != nil:
- // The run is being torn down; what we could not reach is
- // unverified, never failed.
- out[host] = dbverify.Verdict{Result: dbverify.ResultUnverified, Reason: dbverify.ReasonNotReached, Prefix: prefix, VerifiedAt: now.UTC(), Detail: err.Error()}
- fmt.Printf("unverified %s: %v\n", host, err)
- default:
- out[host] = dbverify.Verdict{Result: dbverify.ResultFailed, Reason: "restore_error", Prefix: prefix, VerifiedAt: now.UTC(), Detail: err.Error()}
- fmt.Printf("FAIL %s: %v\n", host, err)
}
}
- if max > 0 && len(hosts) > max {
- // A silent cap reads as full coverage — say what was left.
- fmt.Printf("hibernate-verify: %d of %d hosts this run (--max %d); the rest keep their previous verdict\n",
- max, len(hosts), max)
+ snapshot()
+ return out
+}
+
+func cloneVerdicts(m map[string]dbverify.Verdict) map[string]dbverify.Verdict {
+ out := make(map[string]dbverify.Verdict, len(m))
+ for k, v := range m {
+ out[k] = v
}
return out
}
-// 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.
-func hibernateFreshness(dbPath string, restoredCounter uint32) (freshness, string) {
- if dbPath == "" {
- return freshnessOK, ""
+func printVerdict(host string, v dbverify.Verdict) {
+ switch {
+ case v.OK():
+ fmt.Printf("ok %s (txid %d, freshness %s)\n", host, v.TXID, v.Freshness)
+ case v.Unverified():
+ fmt.Printf("unverified %s: %s %s\n", host, v.Reason, v.Detail)
+ default:
+ fmt.Printf("FAIL %s: %s %s\n", host, v.Reason, v.Detail)
}
- return replicaFreshnessCounter(dbPath, restoredCounter, sourceModTime(dbPath))
+}
+
+// restoreKind is what the restore of one host came to, before the bracket
+// closes.
+type restoreKind int
+
+const (
+ restoreClean restoreKind = iota
+ restoreNothing
+ restorePlanMoved
+ restoreFailed
+)
+
+type restoreResult struct {
+ kind restoreKind
+ plan dbdoor.RestorePlan
+ counter uint32
+ err error
+}
+
+// drillOne tests one host. ok is false when the run's context ended while
+// the host was in progress: the host is abandoned, with no verdict.
+func (d Drill) drillOne(ctx context.Context, rt HibernatingRoute, now func() time.Time) (dbverify.Verdict, bool) {
+ prefix := activator.HibernatePrefix(d.Cfg.Prefix, rt.Host)
+ v := dbverify.Verdict{Prefix: prefix, BracketOpenedAt: now().UTC()}
+ unverified := func(reason, detail string) (dbverify.Verdict, bool) {
+ v.Result, v.Reason, v.Detail = dbverify.ResultUnverified, reason, detail
+ v.VerifiedAt = now().UTC()
+ return v, true
+ }
+
+ id, _, code, err := dbreads.CaptureIdentity(ctx, d.Store, d.Region, rt.Account, rt.App, rt.Host)
+ if err != nil {
+ if ctx.Err() != nil {
+ return dbverify.Verdict{}, false
+ }
+ return unverified(ReasonRecordUnreadable, err.Error())
+ }
+ v.Identity = dbverify.Identity(id)
+ if code != "" {
+ return unverified(bracketReason(code), "the instance's record refused the test when it began")
+ }
+
+ // Each host restores into its own scratch directory, removed whatever
+ // happens, so an abandoned download leaves nothing behind.
+ // A box that cannot make one has learned nothing about the replica: no
+ // verdict, as for a host the run did not reach.
+ scratch, err := os.MkdirTemp(d.TmpDir, "drill-")
+ if err != nil {
+ fmt.Printf("hibernate-verify: %s: no scratch directory on this box: %v\n", rt.Host, err)
+ return dbverify.Verdict{}, false
+ }
+ defer os.RemoveAll(scratch)
+
+ res := d.restore(ctx, prefix, scratch)
+ if res.err != nil && ctx.Err() != nil {
+ return dbverify.Verdict{}, false
+ }
+ // Freshness is read before the bracket closes, so a record change
+ // while it is read discards it too.
+ var fresh string
+ var stale bool
+ var staleDetail string
+ if res.kind == restoreClean {
+ fresh, stale, staleDetail = d.freshness(ctx, rt, prefix, res.counter)
+ if ctx.Err() != nil {
+ return dbverify.Verdict{}, false
+ }
+ }
+
+ _, code, err = dbreads.ConfirmIdentity(ctx, d.Store, id)
+ if err != nil {
+ if ctx.Err() != nil {
+ return dbverify.Verdict{}, false
+ }
+ return unverified(ReasonRecordUnreadable, "the record could not be read again after the restore, so its result was discarded: "+err.Error())
+ }
+ if code != "" {
+ return unverified(bracketReason(code), "the instance changed during the test, so its result was discarded")
+ }
+
+ v.VerifiedAt = now().UTC()
+ switch res.kind {
+ case restoreNothing:
+ v.Result, v.Reason, v.Detail = dbverify.ResultUnverified, ReasonNothingReplicated, "no replica yet"
+ return v, true
+ case restorePlanMoved:
+ v.Result, v.Reason, v.Detail = dbverify.ResultUnverified, ReasonPlanMoved, res.err.Error()
+ return v, true
+ case restoreFailed:
+ v.Result, v.Reason, v.Detail = dbverify.ResultFailed, ReasonRestoreError, res.err.Error()
+ return v, true
+ }
+ v.TXID, v.WrittenAt, v.RestoredBytes = res.plan.TXID, res.plan.At, res.plan.RestoredBytes
+ v.Freshness = fresh
+ if stale {
+ v.Result, v.Reason, v.Detail = dbverify.ResultFailed, ReasonStale, staleDetail
+ return v, true
+ }
+ v.Result = dbverify.ResultPassed
+ return v, true
+}
+
+// bracketReason is the verdict reason for a bracket code.
+func bracketReason(code string) string {
+ if code == dbreads.CodeMoving {
+ return ReasonMoving
+ }
+ return ReasonRecordChanged
+}
+
+// restore plans the newest copy and restores exactly the planned position.
+// Compaction between the two can make that position unrestorable; that is
+// not a failure, so it plans once more, and a second miss is
+// restorePlanMoved.
+func (d Drill) restore(ctx context.Context, prefix, dir string) restoreResult {
+ var last restoreResult
+ for attempt := 0; attempt < 2; attempt++ {
+ plan, err := d.plan(ctx, prefix)
+ switch {
+ case errors.Is(err, dbdoor.ErrNothingReplicated):
+ return restoreResult{kind: restoreNothing, err: err}
+ case err != nil:
+ return restoreResult{kind: restoreFailed, err: fmt.Errorf("plan: %w", err)}
+ }
+ counter, err := verifyAt(ctx, d.Cfg.Bucket, prefix, d.Cfg.Region, dir, plan.TXID)
+ switch {
+ case err == nil:
+ return restoreResult{kind: restoreClean, plan: plan, counter: counter}
+ case errors.Is(err, litestream.ErrTxNotAvailable) && ctx.Err() == nil:
+ last = restoreResult{kind: restorePlanMoved, plan: plan, err: err}
+ continue
+ case errors.Is(err, lease.ErrNoReplica):
+ return restoreResult{kind: restoreNothing, err: err}
+ }
+ return restoreResult{kind: restoreFailed, plan: plan, err: err}
+ }
+ return last
+}
+
+func (d Drill) plan(ctx context.Context, prefix string) (dbdoor.RestorePlan, error) {
+ rd, err := openReplica(ctx, d.Cfg.Bucket, prefix, d.Cfg.Region)
+ if err != nil {
+ return dbdoor.RestorePlan{}, err
+ }
+ return dbdoor.PlanFrom(ctx, rd, time.Time{})
+}
+
+// freshness judges whether a clean replica is still tracking its source,
+// and only where that can be told (P-14): this box must provably hold the
+// live lease, the lock read without error, held, and owned by this box's
+// reference. Anywhere else the live database is somewhere this box cannot
+// see, so the answer is unknown and the local file is not opened. A group
+// box's sleeping host carries a release marker, which ParseOwner refuses:
+// unknown, as the plan expects.
+func (d Drill) freshness(ctx context.Context, rt HibernatingRoute, prefix string, counter uint32) (fresh string, stale bool, detail string) {
+ held, owner, _, err := lockState(ctx, d.Cfg.Bucket, prefix, d.Cfg.Region)
+ if err != nil || !held {
+ return dbverify.FreshnessUnknown, false, ""
+ }
+ if o, ok := hafresh.ParseOwner(owner); !ok || o.Ref != d.SelfRef {
+ return dbverify.FreshnessUnknown, false, ""
+ }
+ switch f, detail := localFreshness(rt.DBPath, counter); f {
+ case freshnessStale:
+ return dbverify.FreshnessStale, true, detail
+ case freshnessNoSource:
+ // This box holds the lease and the database is not on disk: the
+ // replica can never advance again. A failure, though staleness
+ // itself was not measured.
+ return dbverify.FreshnessUnknown, true, detail
+ case freshnessOK:
+ if rt.DBPath == "" {
+ return dbverify.FreshnessUnknown, false, "" // nothing was compared
+ }
+ return dbverify.FreshnessNotStale, false, ""
+ default:
+ return dbverify.FreshnessUnknown, false, ""
+ }
+}
+
+// drillSet is a run's hosts as this box records them: Drill to test, and
+// NoAssignment verdicts for the group box's hosts no usable assignment
+// gave it. Fleet is every host the box's record keeps, the two together;
+// a host assigned to another box is in neither.
+type drillSet struct {
+ Drill []HibernatingRoute
+ NoAssignment map[string]dbverify.Verdict
+ Fleet []string
+}
+
+// selectHosts picks this run's hosts (P-9, P2-9). A fixed box drills every
+// local sleeping host. A group box reads its assignment once, here, and
+// keeps it for the whole run (F2-6); it drills the hosts assigned to its
+// own reference. A host listed unknown, one in neither the assigned nor
+// the unknown list, and every host when the assignment is missing,
+// unreadable or older than assignmentMaxAge, is recorded no_assignment, so
+// coverage alerts still see it (F2-1). why says what made the assignment
+// unusable, "" when it was usable or not needed.
+func selectHosts(self boxself.Self, dataDir string, now time.Time, hosts []HibernatingRoute, hibPrefix string) (set drillSet, why string) {
+ set.NoAssignment = map[string]dbverify.Verdict{}
+ if !self.Group {
+ set.Drill = slices.Clone(hosts)
+ for _, h := range hosts {
+ set.Fleet = append(set.Fleet, h.Host)
+ }
+ return set, ""
+ }
+ a, err := boxself.ReadAssignment(dataDir)
+ switch {
+ case err != nil:
+ why = fmt.Sprintf("no usable drill assignment at %s: %v", boxself.AssignmentPath(dataDir), err)
+ case now.Sub(a.At) > assignmentMaxAge || a.At.Sub(now) > time.Minute:
+ why = fmt.Sprintf("the drill assignment at %s was computed at %s, not within %s of now (%s)",
+ boxself.AssignmentPath(dataDir), a.At.UTC().Format(time.RFC3339), assignmentMaxAge, now.UTC().Format(time.RFC3339))
+ }
+ unknown := map[string]bool{}
+ for _, h := range a.Unknown {
+ unknown[h] = true
+ }
+ for _, h := range hosts {
+ ref, assigned := a.Hosts[h.Host]
+ switch {
+ case why == "" && !unknown[h.Host] && assigned && ref == self.Ref:
+ set.Drill = append(set.Drill, h)
+ case why == "" && !unknown[h.Host] && assigned:
+ continue // another box's: not in this box's record
+ default:
+ set.NoAssignment[h.Host] = dbverify.Verdict{Result: dbverify.ResultUnverified, Reason: dbverify.ReasonNoAssignment,
+ Prefix: activator.HibernatePrefix(hibPrefix, h.Host), Detail: "no drill assignment names a box for this host"}
+ }
+ set.Fleet = append(set.Fleet, h.Host)
+ }
+ return set, why
}
// OldestFirst orders hosts by how long ago they were last verified, most
-// stale first, so a capped run works through the fleet instead of drilling
-// the same alphabetical prefix every night. Hosts with no verdict at all sort
-// first — never verified is staler than any timestamp.
+// stale first, so a run that runs out of budget works through the fleet
+// instead of drilling the same alphabetical prefix every night. Hosts with
+// no verdict at all sort first — never verified is staler than any
+// timestamp.
func OldestFirst(hosts []HibernatingRoute, prior *dbverify.Record) []HibernatingRoute {
stamp := map[string]time.Time{}
if prior != nil {
@@ -173,3 +490,17 @@ func OldestFirst(hosts []HibernatingRoute, prior *dbverify.Record) []Hibernating
})
return ordered
}
+
+// 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.
+func hibernateFreshness(dbPath string, restoredCounter uint32) (freshness, string) {
+ if dbPath == "" {
+ return freshnessOK, ""
+ }
+ return replicaFreshnessCounter(dbPath, restoredCounter, sourceModTime(dbPath))
+}
diff --git a/internal/ops/hibernate_verify_test.go b/internal/ops/hibernate_verify_test.go
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)
}
}
diff --git a/internal/ops/ops.go b/internal/ops/ops.go
index 6482f823b..369d34230 100644
--- a/internal/ops/ops.go
+++ b/internal/ops/ops.go
@@ -9,16 +9,23 @@ import (
"github.com/carlosframework/platform/internal/clireg"
"context"
+ "encoding/json"
"errors"
"flag"
"fmt"
+ "io"
"log"
"os"
"os/exec"
+ "os/signal"
+ "path/filepath"
"strings"
+ "syscall"
"time"
"github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/boxself"
+ "github.com/carlosframework/platform/internal/dbreads"
"github.com/carlosframework/platform/internal/dbverify"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
@@ -263,30 +270,73 @@ func firstLine(s string) string {
return line
}
-// defaultHibernateMax caps one drill run. Each verification is a full restore
-// from S3, so an uncapped nightly pass over a growing fleet is a bill that
-// grows with it (the request-cost discipline internal/lease's LeaseTTL comment
-// records). 25 covers today's fleets in a single run and keeps a large one
-// fully covered within days, oldest-first.
-const defaultHibernateMax = 25
+// The nightly drill's defaults. The budget is the run's deadline: a box
+// whose fleet takes longer works through it over several nights, oldest
+// first, rather than restoring into the working day. There is no count cap
+// by default; the budget bounds the run.
+const (
+ defaultHibernateBudget = 45 * time.Minute
+ defaultHibernateMax = 0
+ defaultHibernatePublish = 10 * time.Minute
+ // selfMaxAge is how old the agent's self record may be: it rewrites it
+ // every few minutes, so an older one names a box whose agent stopped.
+ selfMaxAge = 15 * time.Minute
+ // publishTimeout bounds each publish, on a context of its own: the
+ // run's may already have ended (P-10).
+ publishTimeout = 30 * time.Second
+)
+
+// hibernateVerifyOpts are the verb's flags.
+type hibernateVerifyOpts struct {
+ regPath, data string
+ max int
+ budget time.Duration
+ publishEvery time.Duration
+}
+
+func parseHibernateVerifyFlags(args []string) (hibernateVerifyOpts, error) {
+ return parseHibernateVerifyFlagsTo(os.Stderr, args)
+}
+
+// parseHibernateVerifyFlagsTo parses the flags, writing usage and errors to
+// w. -publish-every is for tests and drills of the drill, so the usage text
+// leaves it out.
+func parseHibernateVerifyFlagsTo(w io.Writer, args []string) (hibernateVerifyOpts, error) {
+ var o hibernateVerifyOpts
+ fs := flag.NewFlagSet("ops hibernate-verify", flag.ContinueOnError)
+ fs.SetOutput(w)
+ fs.StringVar(&o.regPath, "registry", "", "registry database (default <data>/registry.db)")
+ fs.StringVar(&o.data, "data", "", "data directory (default $CARLOS_DATA_DIR or "+defaultDataDir+")")
+ fs.DurationVar(&o.budget, "budget", defaultHibernateBudget, "how long one run may take; hosts it does not reach keep their previous verdict")
+ fs.IntVar(&o.max, "max", defaultHibernateMax, "most replicas to restore in one run (0 = no cap)")
+ visible := flag.NewFlagSet(fs.Name(), flag.ContinueOnError)
+ visible.SetOutput(w)
+ fs.VisitAll(func(f *flag.Flag) { visible.Var(f.Value, f.Name, f.Usage) })
+ fs.DurationVar(&o.publishEvery, "publish-every", defaultHibernatePublish, "how often a run publishes what it has finished")
+ fs.Usage = cliflag.Usage(visible, "")
+ if err := fs.Parse(args); err != nil {
+ return hibernateVerifyOpts{}, err
+ }
+ return o, nil
+}
// runHibernateVerify — restore-drill the hibernating instances' replicas, the
-// set /etc/litestream.yml deliberately omits, and publish the verdicts.
+// set /etc/litestream.yml deliberately omits, and publish the verdicts to
+// this box's own record, control/verify/<ref>.json.
//
-// Exit status carries corruption only: a damaged replica fails the run (the
-// oneshot unit lands in 'failed' where fleet sweeps see it), while replicas
-// the pass could not decide are recorded as unverified and do NOT fail it.
-// Conflating the two would either cry wolf on every S3 blip or — worse —
-// train an operator to ignore a red run.
+// Exit status carries corruption, and a run that could not start: a damaged
+// replica fails the run (the oneshot unit lands in 'failed' where fleet
+// sweeps see it), while replicas the pass could not decide are recorded as
+// unverified and do NOT fail it. Conflating the two would either cry wolf on
+// every S3 blip or — worse — train an operator to ignore a red run.
func runHibernateVerify(args []string) {
- fs := flag.NewFlagSet("ops hibernate-verify", flag.ExitOnError)
- regPath := fs.String("registry", "", "registry database (default <data>/registry.db)")
- data := fs.String("data", "", "data directory (default $CARLOS_DATA_DIR or "+defaultDataDir+")")
- max := fs.Int("max", defaultHibernateMax, "most replicas to restore in one run (0 = no cap)")
- fs.Usage = cliflag.Usage(fs, "")
- _ = fs.Parse(args)
-
- ctx := context.Background()
+ opts, err := parseHibernateVerifyFlags(args)
+ if errors.Is(err, flag.ErrHelp) {
+ return
+ }
+ if err != nil {
+ os.Exit(2)
+ }
cfg, err := activator.ConfigFromEnv()
if err != nil {
log.Fatalf("hibernate-verify: %v", err)
@@ -297,71 +347,136 @@ func runHibernateVerify(args []string) {
fmt.Println("hibernate-verify: CARLOS_HIBERNATE_BUCKET unset — no hibernating replicas on this box")
return
}
-
- dir := dataDir(*data)
- rp := *regPath
+ // A stop (systemd's SIGTERM) abandons the host in progress and still
+ // publishes what the run finished.
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ defer stop()
+ dir := dataDir(opts.data)
+ rp := opts.regPath
if rp == "" {
rp = dir + "/registry.db"
}
- reg, err := registry.Open(rp)
+ r := hibernateRun{
+ Cfg: cfg,
+ OpenStore: openDeployStore,
+ Region: strings.TrimSpace(os.Getenv("CARLOS_REGION")),
+ DataDir: dir,
+ RegPath: rp,
+ TmpDir: os.TempDir(), // the unit points TMPDIR at disk
+ Now: time.Now,
+ Budget: opts.budget,
+ Max: opts.max,
+ PublishEvery: opts.publishEvery,
+ Logf: log.Printf,
+ }
+ if code := r.run(ctx); code != 0 {
+ stop()
+ os.Exit(code)
+ }
+}
+
+// hibernateRun is one run of the verb with everything it reads from the
+// box named, so a test can run it whole.
+type hibernateRun struct {
+ Cfg *activator.Config
+ OpenStore func(context.Context) (release.Store, error)
+ Region string // CARLOS_REGION: the region an instance's record must name
+ DataDir string
+ RegPath string
+ TmpDir string
+ Now func() time.Time
+ Budget time.Duration
+ Max int
+ PublishEvery time.Duration
+ Logf func(format string, args ...any)
+}
+
+// run is the verb's body; it returns the exit code.
+//
+// It refuses to run (non-zero, nothing published) without a fresh self
+// record from the agent: the record's key is this box's reference, and a
+// run that guessed one (the hostname) would publish under a name no reader
+// looks for, or another box's.
+func (r hibernateRun) run(ctx context.Context) int {
+ if r.Cfg == nil {
+ fmt.Println("hibernate-verify: CARLOS_HIBERNATE_BUCKET unset — no hibernating replicas on this box")
+ return 0
+ }
+ self, err := boxself.ReadFresh(r.DataDir, r.Now(), selfMaxAge)
+ if err != nil {
+ r.Logf("hibernate-verify: NOT RUN: no fresh self record at %s (%v); publishing nothing rather than under a name that may not be this box's", boxself.SelfPath(r.DataDir), err)
+ return 1
+ }
+ if !dbreads.ValidRegion(r.Region) {
+ r.Logf("hibernate-verify: NOT RUN: CARLOS_REGION %q is not a region, so no verdict could be bound to an instance", r.Region)
+ return 1
+ }
+ store, err := r.OpenStore(ctx)
+ if err != nil {
+ r.Logf("hibernate-verify: NOT RUN: the deployment bucket, which holds the instances' records and this box's verdicts: %v", err)
+ return 1
+ }
+ reg, err := registry.Open(r.RegPath)
if err != nil {
- log.Fatalf("hibernate-verify: open registry %s: %v", rp, err)
+ r.Logf("hibernate-verify: NOT RUN: open registry %s: %v", r.RegPath, err)
+ return 1
}
hosts, err := HibernatingHosts(reg)
+ reg.Close()
if err != nil {
- log.Fatalf("hibernate-verify: %v", err)
+ r.Logf("hibernate-verify: NOT RUN: %v", err)
+ return 1
}
- if len(hosts) == 0 {
- fmt.Println("hibernate-verify: no hibernating instances registered on this box")
- return
+
+ // The record loaded at the start is every publish's prior in this run,
+ // never the run's own last publish, so a streak moves once per run
+ // (P2-16). It also orders the run, stalest first.
+ ref := self.Ref
+ prior, err := dbverify.Load(ctx, store, ref)
+ if err != nil {
+ if len(hosts) == 0 {
+ r.Logf("hibernate-verify: reading %s: %v; no hosts here, and whether a record needs clearing is unknown, so nothing is published", dbverify.KeyFor(ref), err)
+ return 1
+ }
+ r.Logf("hibernate-verify: reading %s: %v (continuing; this run starts the record over)", dbverify.KeyFor(ref), err)
+ prior = nil
}
- // The prior record does two jobs: it orders this run (stalest first) and
- // it carries the verdicts this run's cap will not revisit.
- // ref names this box's own record. Until the drill reads the agent's
- // self reference it is boxLabel(), as before.
- ref := boxLabel()
- store, storeErr := openDeployStore(ctx)
- var prior *dbverify.Record
- if storeErr == nil {
- if prior, err = dbverify.Load(ctx, store, ref); err != nil {
- log.Printf("hibernate-verify: reading %s: %v (continuing; this run starts the record over)", dbverify.KeyFor(ref), err)
- prior = nil
+ set, why := selectHosts(self, r.DataDir, r.Now(), hosts, r.Cfg.Prefix)
+ if why != "" {
+ r.Logf("hibernate-verify: %s; this box drills none of its %d hosts and records each as no_assignment", why, len(set.NoAssignment))
+ }
+ pub := newVerifyPublisher(ctx, store, ref, prior, set.Fleet, set.NoAssignment, r.DataDir, r.Now, r.Logf)
+
+ if len(set.Fleet) == 0 {
+ // Nothing for this box to vouch for (P-13). A record left from
+ // earlier runs would keep vouching, or alarming, for hosts long
+ // gone, so an existing one is replaced by an empty one; with none,
+ // there is nothing to say.
+ if prior == nil {
+ fmt.Println("hibernate-verify: no hibernating instances for this box to drill")
+ return 0
}
+ pub.publish(nil)
+ fmt.Println("hibernate-verify: no hibernating instances for this box to drill; its record is cleared")
+ return 0
}
- tmp, err := os.MkdirTemp("", "carlos-hibernate-verify")
+ tmp, err := os.MkdirTemp(r.TmpDir, "carlos-hibernate-verify")
if err != nil {
- log.Fatalf("hibernate-verify: %v", err)
+ r.Logf("hibernate-verify: NOT RUN: scratch: %v", err)
+ return 1
}
defer os.RemoveAll(tmp)
- now := time.Now()
- results := VerifyHibernating(ctx, cfg, OldestFirst(hosts, prior), *max, now, tmp)
- fleet := make([]string, 0, len(hosts))
- for _, h := range hosts {
- fleet = append(fleet, h.Host)
- }
- rec := dbverify.Merge(prior, ref, now, fleet, results)
-
- // Publication is best-effort and LOUD when it fails: the drill's value is
- // that someone can read the result without a session on this box, so a
- // silent failure to publish would leave exactly the blind spot this verb
- // exists to remove.
- switch {
- case storeErr != nil:
- log.Printf("hibernate-verify: NOT PUBLISHED (%v) — the verdicts below exist only in this log", storeErr)
- default:
- if err := dbverify.Publish(ctx, store, rec); err != nil {
- log.Printf("hibernate-verify: NOT PUBLISHED: %v — the verdicts below exist only in this log", err)
- } else {
- fmt.Printf("hibernate-verify: published %s (%d hosts, %d unverified)\n", dbverify.KeyFor(ref), len(rec.Hosts), rec.Unverified())
- }
- }
+ d := Drill{Cfg: r.Cfg, Store: store, Region: r.Region, SelfRef: ref, TmpDir: tmp,
+ Budget: r.Budget, Max: r.Max, PublishEvery: r.PublishEvery}
+ results := VerifyHibernating(ctx, d, OldestFirst(set.Drill, prior), r.Now, pub.publish)
+ rec := pub.last
if n := rec.Failures(); n > 0 {
- os.RemoveAll(tmp) // log.Fatal skips the defer
- log.Fatalf("hibernate-verify: %d replica(s) did not restore clean", n)
+ r.Logf("hibernate-verify: %d replica(s) did not restore clean", n)
+ return 1
}
// Count what was PROVEN, not what was visited: an unverified host is not
// coverage, and a summary that said otherwise would be the same comfortable
@@ -372,20 +487,101 @@ func runHibernateVerify(args []string) {
proven++
}
}
- fmt.Printf("hibernate-verify: %d of %d hibernating replicas proven this run (%d visited, %d in the fleet)\n",
- proven, len(hosts), len(results), len(hosts))
+ fmt.Printf("hibernate-verify: %d of %d replicas this box drills proven this run (%d visited, %d in its record)\n",
+ proven, len(set.Drill), len(results), len(set.Fleet))
+ return 0
+}
+
+// verifyPublisher publishes a run's results: each call merges everything
+// the run has finished so far, plus the hosts with no assignment, into the
+// record loaded at the run's start, publishes it to this box's key and
+// writes the local alert copy.
+type verifyPublisher struct {
+ ctx context.Context
+ store release.Store
+ ref string
+ prior *dbverify.Record
+ fleet []string
+ extra map[string]dbverify.Verdict
+ dataDir string
+ now func() time.Time
+ logf func(string, ...any)
+ last *dbverify.Record
+}
+
+func newVerifyPublisher(ctx context.Context, store release.Store, ref string, prior *dbverify.Record, fleet []string,
+ extra map[string]dbverify.Verdict, dataDir string, now func() time.Time, logf func(string, ...any)) *verifyPublisher {
+ return &verifyPublisher{ctx: ctx, store: store, ref: ref, prior: prior, fleet: fleet, extra: extra,
+ dataDir: dataDir, now: now, logf: logf}
+}
+
+// publish is best-effort and LOUD when it fails: the drill's value is that
+// someone can read the result without a session on this box. Its context
+// is its own, 30 seconds, and survives the run's: a run out of time, or
+// stopped, still publishes what it finished. The local copy is written
+// whether or not the publish succeeded, so the box's own alerts see it.
+func (p *verifyPublisher) publish(results map[string]dbverify.Verdict) {
+ all := make(map[string]dbverify.Verdict, len(results)+len(p.extra))
+ for h, v := range p.extra {
+ all[h] = v
+ }
+ for h, v := range results {
+ all[h] = v
+ }
+ rec := dbverify.Merge(p.prior, p.ref, p.now(), p.fleet, all)
+ p.last = rec
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(p.ctx), publishTimeout)
+ defer cancel()
+ if err := dbverify.Publish(ctx, p.store, rec); err != nil {
+ p.logf("hibernate-verify: NOT PUBLISHED: %v; the verdicts exist only in this log and %s", err, localVerifyPath(p.dataDir))
+ } else {
+ fmt.Printf("hibernate-verify: published %s (%d hosts, %d unverified)\n", dbverify.KeyFor(p.ref), len(rec.Hosts), rec.Unverified())
+ }
+ if err := writeLocalVerify(p.dataDir, rec); err != nil {
+ p.logf("hibernate-verify: local copy %s: %v", localVerifyPath(p.dataDir), err)
+ }
}
-// boxLabel names the writing box in the published record. The hostname is
-// enough — the record is informational, unlike the cold-standby snapshot
-// sidecar, whose Box field guards against a standby clobbering the dead box's
-// registry.
-func boxLabel() string {
- h, err := os.Hostname()
- if err != nil || h == "" {
- return "unknown"
+// localVerifyPath is the local alert copy, beside the agent's self record:
+// <data>/monitor/verify.json.
+func localVerifyPath(dataDir string) string {
+ return filepath.Join(filepath.Dir(boxself.SelfPath(dataDir)), "verify.json")
+}
+
+// writeLocalVerify writes rec to the local alert copy whole (a temp file
+// synced and renamed into place), mode 0644, so the agent reads one version
+// or the other and never half of one.
+func writeLocalVerify(dataDir string, rec *dbverify.Record) error {
+ body, err := json.Marshal(rec)
+ if err != nil {
+ return err
+ }
+ path := localVerifyPath(dataDir)
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ return err
+ }
+ f, err := os.CreateTemp(filepath.Dir(path), ".verify-*.tmp")
+ if err != nil {
+ return err
+ }
+ tmp := f.Name()
+ _, err = f.Write(body)
+ if err == nil {
+ err = f.Chmod(0o644)
+ }
+ if err == nil {
+ err = f.Sync()
+ }
+ if cerr := f.Close(); err == nil {
+ err = cerr
+ }
+ if err == nil {
+ err = os.Rename(tmp, path)
+ }
+ if err != nil {
+ os.Remove(tmp)
}
- return h
+ return err
}
// openDeployStore resolves the deployment bucket the same way the agent's