carlos / platform Public

host: drop missing-record lock checks that could stall departures

Let deleted records drop out of departure coverage so a stale lock owned by
an unreachable box cannot block finalization forever. Keep current hosts'
adoption and successor checks, the clean rescan, and exact edges deletion.

Replace the A1 regression with a production-wired case that retains edges
while a remaining host is pending, then completes with the deleted host's
lock unchanged. Retain A2, A4 and A5 and shorten the invariant comment.
Co-Authored-By: GPT-6 Astra <noreply@openai.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev d3166f0b0a9fa8cbff13be1523ab4f2f0bf04e60 parent ba4f795
2 files changed, +66 −125
  • internal/host/hadepartures_g3_test.go +64 −79
  • internal/host/hadepartures_scan.go +2 −46

Intent

Human

<task-notification> <task-id>bdmtvge9l</task-id> <tool-use-id>toolu_01BRsQ7DF9vzMgvDgimvBqra</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/f72ef775-81b3-4d2e-a18d-c8edb14aa192/tasks/bdmtvge9l.output</output-file> <status>completed</status> <summary>Background command "sleep 15; .superpowers/sdd/2026-11-07-region-ha-g3-fixes/wait.sh fw" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>bhmz22xpu</task-id> <tool-use-id>toolu_01VSmtcrugcXiW4KopV8yQCs</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/f72ef775-81b3-4d2e-a18d-c8edb14aa192/tasks/bhmz22xpu.output</output-file> <status>completed</status> <summary>Background command "sleep 120; until amadan ci status carlos/platform -branch region-ha-g3-fixes &gt;/dev/null 2&gt;&amp;1; rc=$?; [ $rc -le 1 ]; do sleep 60; done; amadan ci status carlos/platform -branch region-ha-g3-fixes 2&gt;&amp;1 | head -4" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>aa46dc03caaaf2ba2</task-id> <tool-use-id>toolu_011XDPhbn9AaWZB6TYtxL7GP</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/f72ef775-81b3-4d2e-a18d-c8edb14aa192/tasks/aa46dc03caaaf2ba2.output</output-file> <status>completed</status> <summary>Agent "Census review G3 fixes" 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>**Overall: APPROVED.** There are no P1 or P2 findings. I gave a verdict for 14 items: 8 units, 1 registry-schema closure, 4 envelopes (`internal/host`, `internal/provision`, `internal/registry`, `internal/steering`) and the record-write census changes. All 14 are approved, with file:line citations in the review file. - **New read units:** `retryScanAt`, `departureScanCoverage` and `steeringPassFor` are code moved out of existing functions, or in-memory counting. `checkMissingDepartureHosts` reads the same S3 lock prefix through the same reader that `ScanPass` already used. Its host names come only from `s.Hosts`, which is filled after the host-name validity check, and every bad case adds a blocker. Main ignored pending hosts that dropped out of inventory, so this tightens the scan rather than loosening it. - **`ScanPass` and `complete`:** completion is still gated on the rescan with `Unresolved + Waiting` both zero. A new or changed record still sends the departure back to scanning. The edges file is now always re-read, which covers everything the old `DeleteUncertain` re-read did. The new late-edges rebind needs a group ref, an exact identity match and matching edges-file contents. The key and the delete-at-that-ETag are unchanged. Root only compares the box-written JSON for equality and follows nothing in it. - **Quiet unit:** the Route read moved from `steeringLoop` into `steeringPassFor` in the same file, and the overlay says so. - **Registry schema:** the `@fields` closure differs from the previous one by exactly `Visited` and `Waiting`. - **Record-write census:** the `recordChanges` re-pin is only the deletes-before-upserts reorder. The `gcHealthChecks` entry has no `recordKey` call left anywhere, so it was retired and did not move. The Route 53 changes run before the shrink and conflict guards. Health-check cleanup now works from a fresh zone read and keeps every check a surviving record still uses. - **Census test:** `go test ./internal/provision/ -run 'Census' -count=1` passes at ba4f795a (16.6s). It failed first inside the sandbox because the Go build cache is mounted read-only there, so I ran it once outside the sandbox. Two P3 notes, neither blocking: - About `hadepartures_scan.go:313-314`, there are two lines of spec text pasted in as a code comment. They should be tidied. - `checkMissingDepartureHosts` keeps blocking on a lock that still names the departed box even after it expires. This is safe, but the departure can stall until the record comes back. It is a liveness issue, not a census one. Review file: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-g3-fixes/.superpowers/sdd/2026-11-07-region-ha-g3-fixes/census-review.md. I did not record the verdict on #280; that is still to do.</result> <usage><subagent_tokens>91009</subagent_tokens><tool_uses>18</tool_uses><duration_ms>235022</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a4b16d6eb5e93991f</task-id> <tool-use-id>toolu_01Q76g6C1boB6TgxAM7qjTRj</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/f72ef775-81b3-4d2e-a18d-c8edb14aa192/tasks/a4b16d6eb5e93991f.output</output-file> <status>completed</status> <summary>Agent "Scoped re-review of fix wave" 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>Every item (A1–A5, B, C) is ADDRESSED, but A1 adds one P1 liveness regression: a departure can now stall forever. I ran no tests. The verdicts and the P1 rest on reading the code, and the full departure, steering and census runs in the implementer's report are unverified. ## Per-item verdicts - **A1: ADDRESSED.** `internal/host/hadepartures_scan.go:319-321` calls `checkMissingDepartureHosts` (`:376-415`) on every finished, fresh walk, before the authority_complete decision. A host stays unresolved (`:396`, `:402`, `:408`) when: - the read fails, or - the lock still names the dead box as owner or releaser, or - the generation has not advanced, or - there is no successor validator, or - our own adoption receipt is unfinished, or - the successor fails validation. An absent lock or a verified newer owner resolves it. A resolved missing host does not let the adoption pass skip the clean rescan, since that rescan gate (`:322-344`) is unchanged. Test: `hadepartures_g3_test.go:668` (owned/released × absent/successor; edges kept, no ack while pending). - **A2: ADDRESSED.** `hadepartures_scan.go:554-556`: group refs now always read the edges file before deleting. A changed tag goes through the same `bindDepartureEdges` check as the earlier rebind (`:576`) before `DeleteRevision` (`:606`). The fixed-ref path is unchanged: it never deletes, and only absence or a verified newer incarnation discharges it. The late_edges exemption is gone (`hadepartures_g3_test.go:256`) and a no-page assertion was added (`:652`). - **A3: ADDRESSED.** The toy legacy-cursor loop is deleted from `TestDepartureG3InventoryWrites` (`:460`). The churn_* production modes remain (`:200`). - **A4: ADDRESSED.** Cursor is forced to 0 at `:131`, the `Cursor++` is removed, and coverage returns `len(current) == len(inv.Records)` (`:373`). Every checkpoint save, including the one before adoption, has Cursor 0. Test at `hadepartures_g3_test.go:750`. - **A5: ADDRESSED.** `:126-127`. The comment is accurate: after a restart the evidence map is empty, so the departure is re-observed and starts a fresh walk. - **B: ADDRESSED.** `internal/steering/route53.go:1048-1073`: one ERROR per (region, kept, dropped), with a name count and up to three sorted examples. It runs once per zone converge (the only caller is `:250`), so "per pass" holds per zone. Target selection is unchanged. - **C: ADDRESSED.** `haingress_g3_test.go:208`: the upper slack goes from 100 ms to 1 s. The lower bound, the parent-deadline equality and the 5/9/20 s production budgets are untouched. ## New breakage in the fix diff **P1: A1 can stall a departure forever when a pending host's record is deleted for good.** - A host enters `s.Hosts` as `"pending"` in two cases: - it is dead-owned and cannot be adopted (non-HA, or wrong pool; `:285-290`, also added to `blockers`); - it is HA and waiting for the dead lease to expire. - If its record is then deleted for good, the lock keeps naming the dead box. Examples: a user deletes the instance during the outage, or the operator follows the page's own advice, "Check the box's wake state before removing its records" (`hadepartures_wiring.go:118`, `hadepartures_scan.go:456`). - Nothing rewrites that lock. The dead box can't, and I found no sweep that deletes lock.json for deleted hosts. - Before this wave, removing the record let the departure finish. Now `:396` keeps it unresolved for good: - the edges file is never deleted and the receipt is never acknowledged; - every claimed retry restarts the full walk, so every lock in the inventory is read again (S3 cost); - the page arrives, but names no host, because missing hosts never join `blockers`. - The only way out is deleting lock.json in the bucket by hand, which nothing documents. The same applies to: - a permanent read error such as AccessDenied (`:396`); - our own unfinished adoption receipt for a host that no longer has a record (`:400-403`), which cannot resume without the record. - The brief asked for "blocker semantics as today", but today's documented remedy (remove the record) stops working. - **Suggested fix:** treat a missing host as gone for good once both hold: - it has stayed missing across a fresh inventory taken a bounded time after it first went missing (longer than any delete-then-create window, for example 2× ChangeIndexBackstop), or its lifetime has a completed retirement or tombstone; - it has not reappeared. Also pass missing hosts to the page with a host-named line, and fix the "removing its records" text, which needs copy review. **P3: request budget.** `checkMissingDepartureHosts` has no 32-per-pass cap and makes serial 5 s reads per missing pending host. It also calls HAAdoption and ValidateSuccessor. It runs only once per finished walk, and read or context errors turn into Unresolved, which is safe. The cost is the forever re-walk above. **P3: A2 race window.** If a second publication lands between the read and `DeleteRevision`, the delete still fails the ETag check. That costs one CAS error, and possibly one page, on that attempt. The next attempt then rebinds, since DeleteUncertain is set. This is safe because the delete is pinned to the ETag, and the window is much narrower than the old first-attempt conflict. The check is no weaker: it is the same `bindDepartureEdges`. One new dependency: group completions now need GetObject on `control/edges/*`, which the fixed path already uses. **A4 check.** No production code reads `HADepartureScan.Cursor` any more. The Cursor in `hadeparture_identity.go:251,296` belongs to a different struct. The page budget is `count == 32`, independent of Cursor. `:134` is now redundant but harmless. On rollback, a cf762224 binary that reads a new checkpoint starts at 0. With a matching Generation and Rescan=true it does a full rescan walk. It ignores missing-host duties, which is expected: A1 simply doesn't exist in the old binary. ## Deferred - **Moves under a new lifetime.** When a record comes back with a different lifetime, the existing rule at `:167-171` drops its `s.Hosts` entry, so A1's protection ends at recreation. Check whether moves keep the lifetime; if they don't, the move scenario A1 targets is only half covered. - **Census overlay (D).** It re-freezes units this wave did not touch (`retryScanAt`, `steeringPassFor`, and the removal of `steeringLoop`). That looks like a branch-wide catch-up; the D reviewer should confirm. Nothing else looked obviously wrong.</result> <usage><subagent_tokens>113324</subagent_tokens><tool_uses>40</tool_uses><duration_ms>323161</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bissyto5u</task-id> <tool-use-id>toolu_01Q6sgjinGvGYw69fHSJaiYQ</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/f72ef775-81b3-4d2e-a18d-c8edb14aa192/tasks/bissyto5u.output</output-file> <status>completed</status> <summary>Background command "sleep 90; until amadan ci status carlos/platform -branch region-ha-g3-fixes &gt;/dev/null 2&gt;&amp;1; rc=$?; [ $rc -le 1 ]; do sleep 60; done; amadan ci status carlos/platform -branch region-ha-g3-fixes 2&gt;&amp;1 | grep -v '^20[0-9][0-9]/\|^go: downloading' | grep -E 'CI |FAIL|step|terminated|panic' | head -20" completed (exit code 0)</summary> </task-notification>

diff --git a/internal/host/hadepartures_g3_test.go b/internal/host/hadepartures_g3_test.go
index 6207774cf..c468c7977 100644
--- a/internal/host/hadepartures_g3_test.go
+++ b/internal/host/hadepartures_g3_test.go
@@ -6,10 +6,8 @@ import (
"errors"
"fmt"
"math/rand"
- "net/http"
"os"
"path/filepath"
- "strings"
"testing"
"time"
@@ -666,85 +664,72 @@ func TestDepartureG3LateEdges(t *testing.T) {
}
func TestDepartureG3MissingPendingRecord(t *testing.T) {
- for _, state := range []string{"owned", "released"} {
- for _, resolution := range []string{"absent", "successor"} {
- t.Run(state+"/"+resolution, func(t *testing.T) {
- x := newG3Departure(t, 65)
- rec := x.records[0]
- if state == "released" {
- entry, _ := provision.LifetimeEntryOf(rec)
- raw, _ := hafresh.MarkerBody(5, hafresh.Marker{V: 1, Box: x.dead.Ref, IID: x.dead.InstanceID, Lifetime: entry.ID})
- x.fx.PutLock("instances/"+rec.Host, raw)
- // Leave the real importer pending on an unreadable wake state.
- x.fx.FailNextMatching("GET", 403, func(key string, _ []byte) bool {
- return strings.Contains(key, "/files/")
- })
- }
- if err := x.c.step(t.Context()); err != nil {
- t.Fatal(err)
- }
- scan, err := x.a.Registry.DepartureScan(t.Context(), x.id)
- if err != nil || scan.Hosts[rec.Host].Result != "pending" {
- t.Fatalf("host not pending: %+v %v", scan.Hosts[rec.Host], err)
- }
- if err = provision.DeleteRecord(t.Context(), x.store, rec.Account, rec.App, rec.Host); err != nil {
- t.Fatal(err)
- }
- x.records = x.records[1:]
- x.reconcile(t)
- sawBlocked := false
- for range 5 {
- x.now = x.row(t).NextAttempt
- if err = x.c.step(t.Context()); err != nil {
- t.Fatal(err)
- }
- sawBlocked = sawBlocked || x.row(t).LastError == "blocked"
- }
- if d := x.row(t); d.Phase == "complete" || !sawBlocked || x.pages == 0 {
- t.Fatalf("missing dead-owned record did not block: %+v pages=%d", d, x.pages)
- }
- if _, _, err = x.store.Get(t.Context(), x.edgesKey); err != nil {
- t.Fatal("edges deleted while missing host was pending", err)
- }
- _, _, acks := x.queue.counts()
- if acks != 0 {
- t.Fatal("pending departure acknowledged")
- }
- if resolution == "absent" {
- req, err := http.NewRequestWithContext(t.Context(), http.MethodDelete, x.fx.URL+"/"+x.fx.Bucket+"/instances/"+rec.Host+"/lock.json", nil)
- if err != nil {
- t.Fatal(err)
- }
- resp, err := http.DefaultClient.Do(req)
- if err != nil {
- t.Fatal(err)
- }
- resp.Body.Close()
- if resp.StatusCode != http.StatusNoContent {
- t.Fatal(resp.Status)
- }
- } else {
- raw, _ := json.Marshal(hafresh.Lock{Generation: 6, Owner: hafresh.OwnerFor(hafresh.Self{Ref: x.peer.Ref, IID: x.peer.InstanceID}, 1, true), ExpiresAt: x.expiry.Add(time.Hour)})
- x.fx.PutLock("instances/"+rec.Host, raw)
- }
- for range 8 {
- x.now = x.row(t).NextAttempt
- if err = x.c.step(t.Context()); err != nil {
- t.Fatal(err)
- }
- if x.row(t).Phase == "complete" {
- break
- }
- }
- if d := x.row(t); d.Phase != "complete" {
- t.Fatalf("resolved missing host did not complete: %+v", d)
- }
- if _, _, err = x.store.Get(t.Context(), x.edgesKey); !errors.Is(err, os.ErrNotExist) {
- t.Fatal("edges retained after resolution", err)
- }
- })
+ x := newG3Departure(t, 65)
+ removed, remaining := x.records[0], x.records[1]
+ deadLock := x.fx.LockBody("instances/" + removed.Host)
+ x.fx.PutLock("instances/"+remaining.Host, deadLock)
+ if err := x.c.step(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ scan, err := x.a.Registry.DepartureScan(t.Context(), x.id)
+ if err != nil || scan.Hosts[removed.Host].Result != "pending" || scan.Hosts[remaining.Host].Result != "pending" {
+ t.Fatalf("hosts not pending: %+v %v", scan.Hosts, err)
+ }
+ if err = provision.DeleteRecord(t.Context(), x.store, removed.Account, removed.App, removed.Host); err != nil {
+ t.Fatal(err)
+ }
+ x.records = x.records[1:]
+ x.reconcile(t)
+ sawBlocked := false
+ for range 5 {
+ x.now = x.row(t).NextAttempt
+ if err = x.c.step(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ sawBlocked = sawBlocked || x.row(t).LastError == "blocked"
+ if d := x.row(t); d.Phase == "complete" {
+ t.Fatalf("completed before remaining host was superseded: %+v", d)
+ }
+ if _, _, err = x.store.Get(t.Context(), x.edgesKey); err != nil {
+ t.Fatal("edges deleted while remaining host was pending", err)
+ }
+ if _, _, acks := x.queue.counts(); acks != 0 {
+ t.Fatal("pending departure acknowledged")
+ }
+ }
+ if !sawBlocked {
+ t.Fatal("remaining dead-owned host did not block")
+ }
+ raw, err := json.Marshal(hafresh.Lock{Generation: 6, Owner: hafresh.OwnerFor(hafresh.Self{Ref: x.peer.Ref, IID: x.peer.InstanceID}, 1, true), ExpiresAt: x.expiry.Add(time.Hour)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ x.fx.PutLock("instances/"+remaining.Host, raw)
+ for range 8 {
+ x.now = x.row(t).NextAttempt
+ if err = x.c.step(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ if x.row(t).Phase == "complete" {
+ break
}
}
+ if d := x.row(t); d.Phase != "complete" {
+ t.Fatalf("deleted record stalled departure: %+v", d)
+ }
+ scan, err = x.a.Registry.DepartureScan(t.Context(), x.id)
+ if err != nil || scan.Hosts[remaining.Host].Result != "superseded" {
+ t.Fatalf("remaining host not superseded: %+v %v", scan.Hosts[remaining.Host], err)
+ }
+ if got := x.fx.LockBody("instances/" + removed.Host); string(got) != string(deadLock) {
+ t.Fatalf("removed record's dead-owned lock changed: %s", got)
+ }
+ if _, _, err = x.store.Get(t.Context(), x.edgesKey); !errors.Is(err, os.ErrNotExist) {
+ t.Fatal("edges retained after remaining hosts resolved", err)
+ }
+ if _, _, acks := x.queue.counts(); acks != 1 {
+ t.Fatalf("completed departure acknowledgements: %d", acks)
+ }
}
func TestDepartureG3RollbackCheckpoint(t *testing.T) {
diff --git a/internal/host/hadepartures_scan.go b/internal/host/hadepartures_scan.go
index c20653649..eda9e1cfb 100644
--- a/internal/host/hadepartures_scan.go
+++ b/internal/host/hadepartures_scan.go
@@ -309,16 +309,13 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
if ctx.Err() != nil {
return true, errors.Join(ctx.Err(), c.retryScan(ctx, d, nil, "scan_timeout", true))
}
- // a departure finalizes within a bounded time after every dead-owned lease has expired, unless a
- // real blocker exists, and never deletes the edges file before every dead-owned host is adopted or superseded
+ // Finalize promptly after lease expiry unless blocked; retain edges until
+ // all current dead-owned hosts are adopted or superseded.
// Keep visits across inventory publications. A changed or added record must
// be read at its current revision; unrelated writes cannot restart the walk.
inv = c.cfg.Inventory()
finished := departureScanCoverage(&s, inv)
s.Generation = departureInventoryDigest(inv)
- if finished && inv.FreshAfter(d.ObservedAt) {
- c.checkMissingDepartureHosts(ctx, d, &s, inv, reader)
- }
blocked := s.Unresolved > 0
phase := "scanning"
next := c.now().Add(30 * time.Second)
@@ -373,47 +370,6 @@ func departureScanCoverage(s *registry.HADepartureScan, inv provision.InventoryS
return len(current) == len(inv.Records)
}
-// A missing record can be the gap between deleting and recreating a moved
-// record. Retain its pending duty until its lock is absent or a verified newer
-// owner has superseded the departed box.
-func (c *Controller) checkMissingDepartureHosts(ctx context.Context, d registry.HADeparture, s *registry.HADepartureScan, inv provision.InventorySnapshot, reader DepartureLockReader) {
- present := make(map[string]bool, len(inv.Records))
- for _, h := range inv.Records {
- present[h.Host] = true
- }
- for host, old := range s.Hosts {
- if present[host] || old.Result != "pending" {
- continue
- }
- call, cancel := context.WithTimeout(ctx, 5*time.Second)
- v, err := reader.ReadLock(call, d.Box.Scope.DataBucket, c.cfg.Prefix(host))
- cancel()
- if err == nil && v.Absent {
- continue
- }
- ref, iid, valid := departureLockIdentity(v, old.Lifetime)
- if err != nil || !valid || MatchesDeparture(v, d.Box.Ref, d.Box.InstanceID, old.Lifetime) || v.Lock.Generation <= old.Observed.Lock.Generation || c.cfg.ValidateSuccessor == nil {
- s.Unresolved++
- continue
- }
- if ref == c.cfg.Self.Ref && iid == c.cfg.Self.InstanceID {
- receipt, found, err := c.cfg.Registry.HAAdoption(ctx, host, old.Lifetime, d.ID)
- if err != nil || found && receipt.Phase != "adopted" {
- s.Unresolved++
- continue
- }
- }
- ok, err := c.cfg.ValidateSuccessor(ctx, ref, iid)
- if err != nil || !ok {
- s.Unresolved++
- continue
- }
- old.Result = "superseded"
- old.NotBefore = time.Time{}
- s.Hosts[host] = old
- }
-}
-
// Operator text for two departure faults (copy approved by delegation, one
// Luna pass, 2026-11-03). Each journal line ends with its machine code in
// parentheses, so a search for the code still finds it.