ops: ack publishes, keep landings, rotate abandoned hosts (#898)
Final fix wave items 6 to 10. - Publish acknowledgement (Astra P2-2): the publisher reports whether the bucket took the record; a tick acknowledges its snapshot only on success, so a failed upload is retried on the next tick even with no new host. - Landing removal survives an overlapping run (Astra P2-4): every publish goes through dbverify.PublishOver with the hosts of the last record the run saw; a host the landing removed is dropped from that publish, every later one and the local alert copy. Streaks still come from the run-start record. - Abandoned hosts rotate (Fable P2-3): a host cut by the deadline or a stop gets a not_reached attempt marker; Merge stamps AttemptedAt on its verdict and OldestFirst orders by the later of VerifiedAt and AttemptedAt. - Crash leftovers (Fable P2-4, Astra P3): each run first removes carlos-hibernate-verify* directories in its own TmpDir older than two hours (longer than any run), never a symlink or a non-directory. - Boot catch-up (Fable P3-6): the unit already orders after carlos-edge.service, the agent, but the edge is Type=simple and self.json comes later; the run waits up to five minutes for a fresh one. Unit comment and a host test pin the ordering. - Tests for each; with each fix disabled the matching test fails.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+522
−38
internal/host/host_test.go+26 −0internal/host/units/carlos-hibernate-verify.service+4 −0internal/ops/hibernate_verify.go+41 −21internal/ops/hibernate_verify_run_test.go+327 −0internal/ops/hibernate_verify_test.go+11 −8internal/ops/ops.go+113 −9
diff --git a/internal/host/host_test.go b/internal/host/host_test.go| index 57ab8fceb..803c2db38 100644 |
| --- a/internal/host/host_test.go |
| +++ b/internal/host/host_test.go |
| @@ -1709,6 +1709,32 @@ func TestAppTemplateDeniesIMDS(t *testing.T) { |
| } |
| } |
| +// The drill reads the self.json the agent (carlos-edge.service) writes, so |
| +// it starts after the agent; a boot catch-up run then waits briefly for a |
| +// fresh record (ops hibernateRun.SelfWait) rather than giving up the night. |
| +func TestHibernateVerifyStartsAfterTheAgent(t *testing.T) { |
| + body, err := unitsFS.ReadFile("units/carlos-hibernate-verify.service") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var after string |
| + for _, line := range strings.Split(string(body), "\n") { |
| + if v, ok := strings.CutPrefix(line, "After="); ok { |
| + after += " " + v |
| + } |
| + } |
| + if !slices.Contains(strings.Fields(after), "carlos-edge.service") { |
| + t.Fatalf("carlos-hibernate-verify.service is not ordered after the agent's unit: After=%s", after) |
| + } |
| + agent, err := unitsFS.ReadFile("units/carlos-edge.service") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !strings.Contains(string(agent), "ExecStart=/opt/carlos/carlos agent") { |
| + t.Fatal("carlos-edge.service no longer runs the agent; order the drill after the unit that does") |
| + } |
| +} |
| + |
| func TestVerifyDrillsRestoreToDiskNotTmpfs(t *testing.T) { |
| for _, unit := range []string{"carlos-restore-verify.service", "carlos-hibernate-verify.service"} { |
| body, err := unitsFS.ReadFile("units/" + unit) |
diff --git a/internal/host/units/carlos-hibernate-verify.service b/internal/host/units/carlos-hibernate-verify.service| index 13cd5a7a1..9b4052e4c 100644 |
| --- a/internal/host/units/carlos-hibernate-verify.service |
| +++ b/internal/host/units/carlos-hibernate-verify.service |
| @@ -26,6 +26,10 @@ |
| # place of one it published before. |
| [Unit] |
| Description=carlos hibernate-verify (restore-drill the activator-owned replicas) |
| +# carlos-edge.service is the agent, which writes self.json. Ordering after |
| +# it is not enough on its own at boot (Persistent= catch-up): the edge is |
| +# Type=simple and the agent writes self.json only once it knows the box's |
| +# reference, so the drill also waits up to five minutes for a fresh one. |
| After=network-online.target carlos-edge.service |
| Wants=network-online.target |
diff --git a/internal/ops/hibernate_verify.go b/internal/ops/hibernate_verify.go| index 1a3b55498..5e813c9e6 100644 |
| --- a/internal/ops/hibernate_verify.go |
| +++ b/internal/ops/hibernate_verify.go |
| @@ -174,9 +174,13 @@ type Drill struct { |
| } |
| // 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. |
| +// verdict per host it finished. A host abandoned at the deadline (or when |
| +// the run is stopped) gets an attempt marker, not a verdict: unverified, |
| +// not_reached, AttemptedAt now, which Merge stamps on the verdict the host |
| +// already had, so OldestFirst puts it at the back of the next run (Fable |
| +// P2-3). 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 one run's budget is still covered completely, just over several |
| @@ -185,8 +189,10 @@ type Drill struct { |
| // publish (when not nil) is handed everything finished so far on a |
| // wall-clock ticker every PublishEvery, whatever the host in progress is |
| // doing, so a restore blocked for half an hour does not hold back the |
| -// verdicts finished before it, and once more at the end. A tick with |
| -// nothing new finished since the last publish is skipped. publish is never |
| +// verdicts finished before it, and once more at the end. It reports |
| +// whether the bucket took it: a tick is skipped only when nothing new has |
| +// finished since the last publish that succeeded, so a failed upload is |
| +// retried on the next tick (Astra P2-2). publish is never |
| // called twice at once, and never after VerifyHibernating returns: the |
| // ticker is stopped and its goroutine gone before the final publish. It |
| // must publish under its own context: the run's may have ended by then. |
| @@ -195,7 +201,7 @@ type Drill struct { |
| // 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 { |
| +func VerifyHibernating(ctx context.Context, d Drill, hosts []HibernatingRoute, now func() time.Time, publish func(map[string]dbverify.Verdict) bool) map[string]dbverify.Verdict { |
| start := now() |
| runCtx, cancel := ctx, context.CancelFunc(func() {}) |
| if d.Budget > 0 { |
| @@ -214,8 +220,8 @@ func VerifyHibernating(ctx context.Context, d Drill, hosts []HibernatingRoute, n |
| case <-done: |
| return |
| case <-ticks: |
| - if snap, ok := res.unpublished(); ok { |
| - publish(snap) |
| + if snap, version, ok := res.unpublished(); ok && publish(snap) { |
| + res.acknowledge(version) |
| } |
| publishTickDone() |
| } |
| @@ -249,7 +255,9 @@ func VerifyHibernating(ctx context.Context, d Drill, hosts []HibernatingRoute, n |
| 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) |
| + fmt.Printf("abandoned %s: the run ended during its test; no verdict, and it goes to the back of the next run\n", rt.Host) |
| + res.add(rt.Host, dbverify.Verdict{Result: dbverify.ResultUnverified, Reason: dbverify.ReasonNotReached, |
| + Prefix: activator.HibernatePrefix(d.Cfg.Prefix, rt.Host), AttemptedAt: now().UTC()}) |
| continue |
| } |
| res.add(rt.Host, v) |
| @@ -264,7 +272,7 @@ type runResults struct { |
| mu sync.Mutex |
| out map[string]dbverify.Verdict |
| version int // bumped by every add |
| - published int // the version the last ticker publish carried |
| + published int // the version the last successful ticker publish carried |
| } |
| func (r *runResults) add(host string, v dbverify.Verdict) { |
| @@ -284,16 +292,24 @@ func (r *runResults) all() map[string]dbverify.Verdict { |
| return cloneVerdicts(r.out) |
| } |
| -// unpublished is a copy of every verdict so far, when something was added |
| -// since the last time it said so. |
| -func (r *runResults) unpublished() (map[string]dbverify.Verdict, bool) { |
| +// unpublished is a copy of every verdict so far and its version, when |
| +// something was added since the last acknowledged publish. |
| +func (r *runResults) unpublished() (map[string]dbverify.Verdict, int, bool) { |
| r.mu.Lock() |
| defer r.mu.Unlock() |
| if r.version == r.published { |
| - return nil, false |
| + return nil, 0, false |
| + } |
| + return cloneVerdicts(r.out), r.version, true |
| +} |
| + |
| +// acknowledge records that the snapshot at version was published. |
| +func (r *runResults) acknowledge(version int) { |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + if version > r.published { |
| + r.published = version |
| } |
| - r.published = r.version |
| - return cloneVerdicts(r.out), true |
| } |
| func cloneVerdicts(m map[string]dbverify.Verdict) map[string]dbverify.Verdict { |
| @@ -601,16 +617,20 @@ func selectHosts(self boxself.Self, dataDir string, now time.Time, hosts []Hiber |
| return set, why |
| } |
| -// OldestFirst orders hosts by how long ago they were last verified, most |
| -// 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. |
| +// OldestFirst orders hosts by how long ago they were last verified or |
| +// attempted (the later of VerifiedAt and AttemptedAt), most stale first, |
| +// so a run that runs out of budget works through the fleet instead of |
| +// drilling the same alphabetical prefix every night, and a host that was |
| +// started and abandoned waits behind the others. 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 { |
| for h, v := range prior.Hosts { |
| stamp[h] = v.VerifiedAt |
| + if v.AttemptedAt.After(v.VerifiedAt) { |
| + stamp[h] = v.AttemptedAt |
| + } |
| } |
| } |
| ordered := append([]HibernatingRoute(nil), hosts...) |
diff --git a/internal/ops/hibernate_verify_run_test.go b/internal/ops/hibernate_verify_run_test.go| new file mode 100644 |
| index 000000000..a7e4e59de |
| --- /dev/null |
| +++ b/internal/ops/hibernate_verify_run_test.go |
| @@ -0,0 +1,327 @@ |
| +package ops |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/dbverify" |
| +) |
| + |
| +// A failed periodic upload is not acknowledged: the next tick publishes |
| +// again even though no host has finished since, and only a publish that |
| +// succeeded quiets the ticks that follow (Astra P2-2). |
| +func TestVerifyHibernatingRetriesAFailedPublish(t *testing.T) { |
| + fx := newDrillFx(t, "a.example.com", "b.example.com") |
| + ticker := swapTicker(t) |
| + handled := make(chan struct{}) |
| + swap(t, &publishTickDone, func() { handled <- struct{}{} }) |
| + blocked, release := make(chan struct{}), make(chan struct{}) |
| + fx.stubVerify(func(_ context.Context, prefix, _ string, _ uint64) (uint32, error) { |
| + if strings.HasSuffix(prefix, "b.example.com") { |
| + close(blocked) |
| + <-release |
| + } |
| + return 1, nil |
| + }) |
| + d := fx.drill() |
| + d.PublishEvery = 10 * time.Minute |
| + var mu sync.Mutex |
| + var calls []int |
| + up := false |
| + publish := func(r map[string]dbverify.Verdict) bool { |
| + mu.Lock() |
| + defer mu.Unlock() |
| + calls = append(calls, len(r)) |
| + return up |
| + } |
| + seen := func() []int { |
| + mu.Lock() |
| + defer mu.Unlock() |
| + return slices.Clone(calls) |
| + } |
| + done := make(chan struct{}) |
| + go func() { |
| + fx.run(context.Background(), d, fx.routes("a.example.com", "b.example.com"), publish) |
| + close(done) |
| + }() |
| + <-blocked // a has its verdict; b is in its download |
| + tick := func() { |
| + ticker.c <- fx.clock.Now() |
| + <-handled |
| + } |
| + tick() // the upload fails |
| + if got := seen(); !slices.Equal(got, []int{1}) { |
| + t.Fatalf("publishes %v, want one, of a", got) |
| + } |
| + mu.Lock() |
| + up = true |
| + mu.Unlock() |
| + tick() // nothing new finished, but the last upload failed: again |
| + if got := seen(); !slices.Equal(got, []int{1, 1}) { |
| + t.Fatalf("publishes %v, want the failed one retried", got) |
| + } |
| + tick() // published since: quiet |
| + if got := seen(); !slices.Equal(got, []int{1, 1}) { |
| + t.Fatalf("publishes %v, want nothing after a success with nothing new", got) |
| + } |
| + close(release) |
| + <-done |
| + if got := seen(); !slices.Equal(got, []int{1, 1, 2}) { |
| + t.Fatalf("publishes %v, want the final one too", got) |
| + } |
| +} |
| + |
| +// The publisher reports what the bucket said: false when the upload |
| +// failed, true when it landed. |
| +func TestVerifyPublisherReportsSuccess(t *testing.T) { |
| + fx := newDrillFx(t) |
| + store := &failingStore{ctxStore: ctxStore{Store: fx.store}, fail: true} |
| + pub := newVerifyPublisher(context.Background(), store, fxSelf, nil, []string{"a.example.com"}, nil, t.TempDir(), fx.clock.Now, t.Logf) |
| + if pub.publish(nil) { |
| + t.Fatal("a failed upload reported success") |
| + } |
| + store.fail = false |
| + if !pub.publish(nil) { |
| + t.Fatal("an upload that landed reported failure") |
| + } |
| +} |
| + |
| +// failingStore fails every put while fail is set. |
| +type failingStore struct { |
| + ctxStore |
| + fail bool |
| +} |
| + |
| +func (s *failingStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + if s.fail { |
| + return "", errors.New("s3: put: connection reset") |
| + } |
| + return s.ctxStore.Put(ctx, key, body, ifMatch) |
| +} |
| + |
| +// A landing move that removes a host from this box's record while a drill |
| +// runs is not undone by the run's later publishes, to the bucket or to the |
| +// local alert copy (Astra P2-4). Every write the run makes is recorded. |
| +func TestRunHibernateVerifyLandingSurvivesAnOverlappingRun(t *testing.T) { |
| + const moved = "moved.example.com" |
| + hosts := []string{"a.example.com", "b.example.com", moved} |
| + fx := newRunFx(t, hosts...) |
| + store := &ctxStore{Store: fx.store} |
| + under := fx.store |
| + fx.store = store |
| + fx.writeSelf(fxSelf, false) |
| + // moved was verified last, so the run drills it last. |
| + prior := &dbverify.Record{V: 2, Box: fxSelf, CheckedAt: at("2026-11-11T03:00:00Z"), Hosts: map[string]dbverify.Verdict{ |
| + "a.example.com": {Result: dbverify.ResultPassed, VerifiedAt: at("2026-11-09T03:00:00Z"), Identity: fx.identity("a.example.com")}, |
| + "b.example.com": {Result: dbverify.ResultPassed, VerifiedAt: at("2026-11-10T03:00:00Z"), Identity: fx.identity("b.example.com")}, |
| + moved: {Result: dbverify.ResultPassed, VerifiedAt: at("2026-11-11T03:00:00Z"), Identity: fx.identity(moved)}, |
| + }} |
| + if err := dbverify.Publish(context.Background(), under, prior); err != nil { |
| + t.Fatal(err) |
| + } |
| + ticker := swapTicker(t) |
| + handled := make(chan struct{}) |
| + swap(t, &publishTickDone, func() { handled <- struct{}{} }) |
| + landed := false |
| + fx.stubVerify(func(_ context.Context, prefix, _ string, _ uint64) (uint32, error) { |
| + switch filepath.Base(prefix) { |
| + case "b.example.com": |
| + ticker.c <- fx.clock.Now() // publishes a's verdict, moved still in it |
| + <-handled |
| + // The landing, between two of this run's publishes. |
| + if err := dbverify.RemoveHost(context.Background(), under, fxSelf, moved); err != nil { |
| + t.Error(err) |
| + } |
| + landed = true |
| + case moved: |
| + ticker.c <- fx.clock.Now() |
| + <-handled |
| + } |
| + return 1, nil |
| + }) |
| + if code := fx.runner().run(context.Background()); code != 0 { |
| + t.Fatalf("exited %d: %s", code, fx.logs) |
| + } |
| + if !landed { |
| + t.Fatal("the landing never ran") |
| + } |
| + puts := store.published() |
| + if len(puts) != 3 { |
| + t.Fatalf("%d publishes, want a tick before the landing, one after and the final one", len(puts)) |
| + } |
| + if _, ok := puts[0].Hosts[moved]; !ok { |
| + t.Fatalf("the publish before the landing lost %s: %v", moved, sortedHosts(puts[0])) |
| + } |
| + for i, rec := range puts[1:] { |
| + if _, ok := rec.Hosts[moved]; ok { |
| + t.Fatalf("publish %d after the landing put %s back: %v", i+2, moved, sortedHosts(rec)) |
| + } |
| + } |
| + if got := sortedHosts(fx.published(fxSelf)); !slices.Equal(got, hosts[:2]) { |
| + t.Fatalf("the bucket holds %v, want %v", got, hosts[:2]) |
| + } |
| + local, err := fx.localCopy() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := sortedHosts(local); !slices.Equal(got, hosts[:2]) { |
| + t.Fatalf("the local alert copy holds %v, want %v", got, hosts[:2]) |
| + } |
| +} |
| + |
| +// A host the deadline cuts keeps its verdict but carries the attempt, so |
| +// the next run starts with the hosts that never got a turn and leaves it |
| +// for last, instead of handing it the whole budget again (Fable P2-3). |
| +func TestVerifyHibernatingAbandonedHostGoesToTheBack(t *testing.T) { |
| + hosts := []string{"a.example.com", "b.example.com", "c.example.com"} |
| + fx := newDrillFx(t, hosts...) |
| + fx.stubVerify(func(ctx context.Context, prefix, _ string, _ uint64) (uint32, error) { |
| + if strings.HasSuffix(prefix, "a.example.com") { |
| + <-ctx.Done() |
| + return 0, fmt.Errorf("restore stopped: %w", ctx.Err()) |
| + } |
| + return 1, nil |
| + }) |
| + d := fx.drill() |
| + d.Budget = 300 * time.Millisecond |
| + got := fx.run(context.Background(), d, OldestFirst(fx.routes(hosts...), nil), nil) |
| + a, ok := got["a.example.com"] |
| + if !ok || !a.Unverified() || a.Reason != dbverify.ReasonNotReached || !a.AttemptedAt.Equal(fx.clock.Now()) { |
| + t.Fatalf("the abandoned host: %+v (present %v), want not_reached with its attempt", a, ok) |
| + } |
| + rec := dbverify.Merge(nil, fxSelf, fx.clock.Now(), hosts, got) |
| + if v := rec.Hosts["a.example.com"]; v.AttemptedAt.IsZero() { |
| + t.Fatalf("the record lost the attempt: %+v", v) |
| + } |
| + if v := rec.Hosts["b.example.com"]; !v.AttemptedAt.IsZero() { |
| + t.Fatalf("a host never started carries an attempt: %+v", v) |
| + } |
| + if order := hostsOf(OldestFirst(fx.routes(hosts...), rec)); !slices.Equal(order, []string{"b.example.com", "c.example.com", "a.example.com"}) { |
| + t.Fatalf("next night's order %v, want the abandoned host last", order) |
| + } |
| + // Against hosts verified before the attempt, the attempt still counts |
| + // as the newer time. |
| + fx.clock.Advance(24 * time.Hour) |
| + rec.Hosts["b.example.com"] = dbverify.Verdict{Result: dbverify.ResultPassed, VerifiedAt: fx.clock.Now().Add(-time.Hour)} |
| + rec.Hosts["c.example.com"] = dbverify.Verdict{Result: dbverify.ResultPassed, VerifiedAt: fx.clock.Now().Add(-48 * time.Hour)} |
| + if order := hostsOf(OldestFirst(fx.routes(hosts...), rec)); !slices.Equal(order, []string{"c.example.com", "a.example.com", "b.example.com"}) { |
| + t.Fatalf("order %v, want by the later of verified and attempted", order) |
| + } |
| +} |
| + |
| +// A run first removes the restored databases a killed run left in the |
| +// drill's own scratch root: carlos-hibernate-verify* directories older than |
| +// any run lasts. Nothing else there, nothing younger, nothing that is not |
| +// a directory, and nothing a symlink points at is touched (Fable P2-4). |
| +func TestRunHibernateVerifyClearsCrashedScratch(t *testing.T) { |
| + fx := newRunFx(t, "a.example.com") |
| + fx.writeSelf(fxSelf, false) |
| + now := fx.clock.Now() |
| + mk := func(name string, age time.Duration) string { |
| + p := filepath.Join(fx.tmp, name) |
| + if err := os.MkdirAll(filepath.Join(p, "drill-1"), 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.Join(p, "drill-1", "verify-a.example.com.db"), []byte("tenant data"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Chtimes(p, now.Add(-age), now.Add(-age)); err != nil { |
| + t.Fatal(err) |
| + } |
| + return p |
| + } |
| + stale := mk("carlos-hibernate-verify123456", 25*time.Hour) |
| + young := mk("carlos-hibernate-verify654321", 10*time.Minute) |
| + unrelated := mk("other-scratch", 48*time.Hour) |
| + file := filepath.Join(fx.tmp, "carlos-hibernate-verify-note") |
| + if err := os.WriteFile(file, []byte("x"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + outside := t.TempDir() |
| + link := filepath.Join(fx.tmp, "carlos-hibernate-verify777") |
| + if err := os.Symlink(outside, link); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Chtimes(file, now.Add(-48*time.Hour), now.Add(-48*time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + if code := fx.runner().run(context.Background()); code != 0 { |
| + t.Fatalf("exited %d: %s", code, fx.logs) |
| + } |
| + if _, err := os.Lstat(stale); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("the crashed run's scratch is still there: %v", err) |
| + } |
| + for _, p := range []string{young, unrelated, file, link, outside} { |
| + if _, err := os.Lstat(p); err != nil { |
| + t.Fatalf("%s was touched: %v", p, err) |
| + } |
| + } |
| + if !fx.published(fxSelf).Hosts["a.example.com"].OK() { |
| + t.Fatal("the run did not drill after clearing") |
| + } |
| +} |
| + |
| +// A boot catch-up run can start before the agent has written self.json: |
| +// the run waits briefly for a fresh one, and gives up (publishing nothing) |
| +// only when none comes (Fable P3-6). |
| +func TestRunHibernateVerifyWaitsBrieflyForSelf(t *testing.T) { |
| + t.Run("written while waiting", func(t *testing.T) { |
| + fx := newRunFx(t, "a.example.com") |
| + r := fx.runner() |
| + r.SelfWait = 5 * time.Minute |
| + waits := 0 |
| + r.Sleep = func(_ context.Context, d time.Duration) bool { |
| + waits++ |
| + fx.clock.Advance(d) |
| + if waits == 2 { |
| + fx.writeSelf(fxSelf, false) |
| + } |
| + return true |
| + } |
| + if code := r.run(context.Background()); code != 0 { |
| + t.Fatalf("exited %d: %s", code, fx.logs) |
| + } |
| + if waits != 2 || !fx.published(fxSelf).Hosts["a.example.com"].OK() { |
| + t.Fatalf("waited %d times; published %+v", waits, fx.published(fxSelf)) |
| + } |
| + }) |
| + t.Run("never written", func(t *testing.T) { |
| + fx := newRunFx(t, "a.example.com") |
| + r := fx.runner() |
| + r.SelfWait = 5 * time.Minute |
| + var waited time.Duration |
| + r.Sleep = func(_ context.Context, d time.Duration) bool { |
| + waited += d |
| + fx.clock.Advance(d) |
| + return true |
| + } |
| + if code := r.run(context.Background()); code == 0 { |
| + t.Fatal("exited 0 with no self record") |
| + } |
| + if waited < r.SelfWait || waited > r.SelfWait+selfPoll { |
| + t.Fatalf("waited %s, want about %s", waited, r.SelfWait) |
| + } |
| + if rec := fx.published(fxSelf); rec != nil { |
| + t.Fatalf("published %+v", rec) |
| + } |
| + }) |
| + t.Run("stopped while waiting", func(t *testing.T) { |
| + fx := newRunFx(t, "a.example.com") |
| + r := fx.runner() |
| + r.SelfWait = 5 * time.Minute |
| + waits := 0 |
| + r.Sleep = func(context.Context, time.Duration) bool { waits++; return false } |
| + if code := r.run(context.Background()); code == 0 || waits != 1 { |
| + t.Fatalf("exited %d after %d waits, want non-zero after one", code, waits) |
| + } |
| + }) |
| +} |
diff --git a/internal/ops/hibernate_verify_test.go b/internal/ops/hibernate_verify_test.go| index 00f01cd20..81b9afbd7 100644 |
| --- a/internal/ops/hibernate_verify_test.go |
| +++ b/internal/ops/hibernate_verify_test.go |
| @@ -340,7 +340,7 @@ func (fx *drillFx) routes(hosts ...string) []HibernatingRoute { |
| return out |
| } |
| -func (fx *drillFx) run(ctx context.Context, d Drill, hosts []HibernatingRoute, publish func(map[string]dbverify.Verdict)) map[string]dbverify.Verdict { |
| +func (fx *drillFx) run(ctx context.Context, d Drill, hosts []HibernatingRoute, publish func(map[string]dbverify.Verdict) bool) map[string]dbverify.Verdict { |
| return VerifyHibernating(ctx, d, hosts, fx.clock.Now, publish) |
| } |
| @@ -984,8 +984,9 @@ func TestVerifyHibernatingDeadlineStopsBlockedWork(t *testing.T) { |
| 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"]) |
| + // The abandoned host has no verdict, only its attempt (Fable P2-3). |
| + if v := got["c.example.com"]; v.Reason != dbverify.ReasonNotReached || v.AttemptedAt.IsZero() || v.TXID != 0 { |
| + t.Fatalf("the abandoned host: %+v, want not_reached with its attempt", v) |
| } |
| if _, ok := got["d.example.com"]; ok { |
| t.Fatal("a host after the deadline was drilled") |
| @@ -1056,9 +1057,10 @@ func TestVerifyHibernatingPublishesPeriodically(t *testing.T) { |
| published := make(chan map[string]dbverify.Verdict, 8) |
| done := make(chan map[string]dbverify.Verdict) |
| go func() { |
| - done <- fx.run(context.Background(), d, fx.routes(hosts...), func(r map[string]dbverify.Verdict) { |
| - pub.publish(r) |
| + done <- fx.run(context.Background(), d, fx.routes(hosts...), func(r map[string]dbverify.Verdict) bool { |
| + ok := pub.publish(r) |
| published <- r |
| + return ok |
| }) |
| }() |
| @@ -1120,7 +1122,7 @@ func TestVerifyHibernatingTickWithNothingNewIsQuiet(t *testing.T) { |
| var calls atomic.Int32 |
| done := make(chan struct{}) |
| go func() { |
| - fx.run(context.Background(), d, fx.routes("a.example.com"), func(map[string]dbverify.Verdict) { calls.Add(1) }) |
| + fx.run(context.Background(), d, fx.routes("a.example.com"), func(map[string]dbverify.Verdict) bool { calls.Add(1); return true }) |
| close(done) |
| }() |
| <-blocked |
| @@ -1171,9 +1173,10 @@ func TestVerifyHibernatingStreakOncePerRun(t *testing.T) { |
| 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...), func(r map[string]dbverify.Verdict) { |
| - pub.publish(r) |
| + fx.run(context.Background(), d, fx.routes(hosts...), func(r map[string]dbverify.Verdict) bool { |
| + ok := pub.publish(r) |
| published <- struct{}{} |
| + return ok |
| }) |
| puts := store.published()[1:] // the seeded prior is the first |
diff --git a/internal/ops/ops.go b/internal/ops/ops.go| index f4d534967..a3265183a 100644 |
| --- a/internal/ops/ops.go |
| +++ b/internal/ops/ops.go |
| @@ -14,10 +14,12 @@ import ( |
| "flag" |
| "fmt" |
| "io" |
| + "io/fs" |
| "log" |
| "os" |
| "os/exec" |
| "os/signal" |
| + "path/filepath" |
| "strings" |
| "syscall" |
| "time" |
| @@ -283,6 +285,19 @@ const ( |
| // publishTimeout bounds each publish, on a context of its own: the |
| // run's may already have ended (P-10). |
| publishTimeout = 30 * time.Second |
| + // selfWait is how long a run waits for a fresh self record before it |
| + // gives up, asking every selfPoll: the unit starts after carlos-edge |
| + // (the agent), but the agent writes self.json only once it knows the |
| + // box's reference, so a boot catch-up run can start first (Fable P3-6). |
| + selfWait = 5 * time.Minute |
| + selfPoll = 15 * time.Second |
| + // staleScratchAge is how old a carlos-hibernate-verify* scratch |
| + // directory must be before a run removes it as a killed run's: longer |
| + // than any run the unit starts (the 45-minute budget, then the final |
| + // publish), so a run never removes another's that is still going. |
| + staleScratchAge = 2 * time.Hour |
| + // scratchPrefix names each run's scratch directory under TmpDir. |
| + scratchPrefix = "carlos-hibernate-verify" |
| ) |
| // hibernateVerifyOpts are the verb's flags. |
| @@ -367,6 +382,8 @@ func runHibernateVerify(args []string) { |
| Budget: opts.budget, |
| Max: opts.max, |
| PublishEvery: opts.publishEvery, |
| + SelfWait: selfWait, |
| + Sleep: sleepCtx, |
| Logf: log.Printf, |
| } |
| if code := r.run(ctx); code != 0 { |
| @@ -398,7 +415,23 @@ type hibernateRun struct { |
| Budget time.Duration |
| Max int |
| PublishEvery time.Duration |
| - Logf func(format string, args ...any) |
| + // SelfWait is how long to wait for a fresh self record, asking every |
| + // selfPoll through Sleep (false: stopped while waiting). |
| + SelfWait time.Duration |
| + Sleep func(ctx context.Context, d time.Duration) bool |
| + Logf func(format string, args ...any) |
| +} |
| + |
| +// sleepCtx waits d, or until ctx ends (false). |
| +func sleepCtx(ctx context.Context, d time.Duration) bool { |
| + t := time.NewTimer(d) |
| + defer t.Stop() |
| + select { |
| + case <-ctx.Done(): |
| + return false |
| + case <-t.C: |
| + return true |
| + } |
| } |
| // run is the verb's body; it returns the exit code. |
| @@ -422,6 +455,15 @@ func (r hibernateRun) run(ctx context.Context) int { |
| return 0 |
| } |
| self, err := readBoxSelf(r.DataDir, r.Now(), selfMaxAge) |
| + for waited := time.Duration(0); err != nil && waited < r.SelfWait; waited += selfPoll { |
| + if waited == 0 { |
| + r.Logf("hibernate-verify: no fresh self record at %s yet (%v); waiting up to %s for the agent to write one", boxself.SelfPath(r.DataDir), err, r.SelfWait) |
| + } |
| + if !r.Sleep(ctx, selfPoll) { |
| + break |
| + } |
| + self, err = readBoxSelf(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 |
| @@ -483,7 +525,8 @@ func (r hibernateRun) run(ctx context.Context) int { |
| return 0 |
| } |
| - tmp, err := os.MkdirTemp(r.TmpDir, "carlos-hibernate-verify") |
| + r.clearCrashedScratch() |
| + tmp, err := os.MkdirTemp(r.TmpDir, scratchPrefix) |
| if err != nil { |
| r.Logf("hibernate-verify: NOT RUN: scratch: %v", err) |
| return 1 |
| @@ -513,10 +556,48 @@ func (r hibernateRun) run(ctx context.Context) int { |
| return 0 |
| } |
| +// clearCrashedScratch removes what a killed run left in the drill's own |
| +// scratch root (TmpDir, the unit's %C/carlos-verify): each directory whose |
| +// name starts with scratchPrefix and that is older than staleScratchAge, |
| +// which holds restored tenant databases a deferred removal never reached |
| +// (SIGKILL, an OOM kill, a power cut). Only TmpDir's own entries are |
| +// considered, no pattern is expanded, a symlink or anything that is not a |
| +// directory is left alone, and a failure is logged and does not stop the |
| +// run (Fable P2-4). |
| +func (r hibernateRun) clearCrashedScratch() { |
| + ents, err := os.ReadDir(r.TmpDir) |
| + if err != nil { |
| + r.Logf("hibernate-verify: clearing crashed runs' scratch in %s: %v", r.TmpDir, err) |
| + return |
| + } |
| + for _, e := range ents { |
| + if !strings.HasPrefix(e.Name(), scratchPrefix) || e.Type()&fs.ModeType != fs.ModeDir { |
| + continue |
| + } |
| + info, err := e.Info() |
| + if err != nil || r.Now().Sub(info.ModTime()) <= staleScratchAge { |
| + continue |
| + } |
| + p := filepath.Join(r.TmpDir, e.Name()) |
| + if err := os.RemoveAll(p); err != nil { |
| + r.Logf("hibernate-verify: clearing a crashed run's scratch %s: %v", p, err) |
| + continue |
| + } |
| + r.Logf("hibernate-verify: removed a crashed run's scratch %s (last changed %s)", p, info.ModTime().UTC().Format(time.RFC3339)) |
| + } |
| +} |
| + |
| // 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. |
| +// |
| +// Streaks come from the run-start record, but what is published respects |
| +// what a landing move removed meanwhile (Astra P2-4): known is the hosts |
| +// of the last record this run saw in the bucket (the run-start one, then |
| +// each it published), and a host in known that the bucket's record has |
| +// lost was removed by the landing. It is dropped from this publish and |
| +// every later one in the run, in the bucket and in the local copy. |
| type verifyPublisher struct { |
| ctx context.Context |
| store release.Store |
| @@ -528,12 +609,20 @@ type verifyPublisher struct { |
| now func() time.Time |
| logf func(string, ...any) |
| last *dbverify.Record |
| + known map[string]bool |
| + dropped map[string]bool |
| } |
| 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} |
| + p := &verifyPublisher{ctx: ctx, store: store, ref: ref, prior: prior, fleet: fleet, extra: extra, |
| + dataDir: dataDir, now: now, logf: logf, known: map[string]bool{}, dropped: map[string]bool{}} |
| + if prior != nil { |
| + for h := range prior.Hosts { |
| + p.known[h] = true |
| + } |
| + } |
| + return p |
| } |
| // publish is best-effort and LOUD when it fails: the drill's value is that |
| @@ -541,7 +630,8 @@ func newVerifyPublisher(ctx context.Context, store release.Store, ref string, pr |
| // 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) { |
| +// It reports whether the bucket took the record. |
| +func (p *verifyPublisher) publish(results map[string]dbverify.Verdict) bool { |
| all := make(map[string]dbverify.Verdict, len(results)+len(p.extra)) |
| for h, v := range p.extra { |
| all[h] = v |
| @@ -550,17 +640,31 @@ func (p *verifyPublisher) publish(results map[string]dbverify.Verdict) { |
| all[h] = v |
| } |
| rec := dbverify.Merge(p.prior, p.ref, p.now(), p.fleet, all) |
| - p.last = rec |
| + for h := range p.dropped { |
| + delete(rec.Hosts, h) |
| + } |
| 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 { |
| + gone, err := dbverify.PublishOver(ctx, p.store, rec, p.known) |
| + for _, h := range gone { |
| + p.dropped[h] = true |
| + fmt.Printf("hibernate-verify: %s left this box's record while the run went on (a move landed); not publishing it again\n", h) |
| + } |
| + p.last = rec |
| + ok := err == nil |
| + if ok { |
| + p.known = map[string]bool{} |
| + for h := range rec.Hosts { |
| + p.known[h] = true |
| + } |
| fmt.Printf("hibernate-verify: published %s (%d hosts, %d unverified)\n", dbverify.KeyFor(p.ref), len(rec.Hosts), rec.Unverified()) |
| + } else { |
| + p.logf("hibernate-verify: NOT PUBLISHED: %v; the verdicts exist only in this log and %s", err, localVerifyPath(p.dataDir)) |
| } |
| if err := writeLocalVerify(p.dataDir, rec); err != nil { |
| p.logf("hibernate-verify: local copy %s: %v", localVerifyPath(p.dataDir), err) |
| } |
| + return ok |
| } |
| // localVerifyPath is the local alert copy, beside the agent's self record: |