carlos / platform Public

host: retain pending departure duties across missing records

Check missing pending hosts before completing a walk so record moves cannot
release edges while the dead box still owns or released the lock. Read late
group edges revisions before deleting, retaining exact revision validation.

Keep Cursor zero for rollback readers and progress in Visited. Exercise the
production departure path and remove the toy cursor simulation.
Co-Authored-By: GPT-6 Astra <noreply@openai.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev afff5794a44c5e9cc1228fe5c6ab3701d3610706 parent f81cfd5
4 files changed, +197 −38
  • internal/host/hadepartures_g3_test.go +138 −31
  • internal/host/hadepartures_retained_test.go +5 −1
  • internal/host/hadepartures_scan.go +52 −4
  • internal/host/hadepartures_scan_test.go +2 −2

Intent

Human

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

Human

<task-notification> <task-id>a14266e8e8bb49445</task-id> <tool-use-id>toolu_01BdqVJffpVqoQ9JqSChjxdW</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/f72ef775-81b3-4d2e-a18d-c8edb14aa192/tasks/a14266e8e8bb49445.output</output-file> <status>completed</status> <summary>Agent "Review Task 2 (departures)" 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>### Spec Compliance ✅ **Overall: the task meets its requirements.** I found no P1. I could not verify the cf762224 overlay result myself; see item 5. - ✅ **Item 1. Waits are tracked apart from blockers.** Each record's visit stores `Unresolved` and `NotBefore` (`internal/registry/ha_scan.go`). `Waiting` and the walk-wide `NotBefore` are recounted from the visits that cover the current inventory (`hadepartures_scan.go:346-369`). They reset at the same points as `Unresolved` (`:128-139` and `:326-333`). - ✅ **Item 2. A wait-only page ends as `scan`.** `blocked := s.Unresolved &gt; 0` (`:316`) feeds `retryScanAt(..., "scan", blocked, next)`. With `page=false` the code stays `scan`, which resets `RetryCount` (`ha_journal.go:488-489`). - ✅ **Item 3. A wait-only walk end reschedules correctly.** At `:322-324`, next = max(now+30s, earliest NotBefore+1s), applied only when `!blocked`. - ✅ **Item 4. Existing safety rules are unchanged.** Adopt-before-delete still holds: the visit is saved as unresolved before `Adopt` (`:284-285`). A validated successor still counts as superseded. Real blockers still return "blocked", back off and page. - ✅ **Item 5. The production-wired acceptance test exists.** It runs through `armHADepartures` and `Controller.step` (the worker entry point, `hadepartures.go:301`), with the real journal, `ValidateSuccessor`, `Adopt`, conditional delete and the SQS adapter. It covers 100 records, dead holder on page 1, a 15-minute lease, a clock that only ticks when `next_attempt` is due, and variants peer / adopt / unbound. Assertions cover no early adopt, delete or ack, no page while waiting, and the 2×pages×30s+1m bound. - ✅ **Item 6. The invariant comment and the seeded simulation are in.** The comment is at the decision point (`:308-309`). The simulation runs 64 seeds, or 12 under `-short`. - ✅ **Items 7-10. The churn fix is in.** The digest measurement is real (ship, promote and wake publication leave the digest alone; record rewrites change it). The fix uses a per-record visit map instead of restarting the walk. A digest change no longer produces "blocked". Unrelated churn is in the simulation, with a stated liveness bound. The flagship reproduction (`churn_each_pass`, `churn_two_minutes`) is in the production test. - ✅ **Addendum `EdgesETag` question.** Enrollment binds the ETag in `ha_departures.body`. A late publication is now rebound after verification (`:523-531`). - ⚠️ **"Fails on cf762224" (cannot verify without re-running).** The report shows verbatim failures from the overlay run. I confirmed that `hadepartures_scan.go`, `hadepartures.go`, `ha_scan.go` and `ha_journal.go` are identical between cf762224 and a9a3e4e9, so the overlay base is valid. ### Strengths **Named risk 1 (safety).** A visit is keyed by host, and its digest covers the whole `DepartureHost`: revision, lifetime, placement and pool. - Reordering cannot skip a record. A changed or added record behind the cursor becomes outstanding work again. - The end-of-pass coverage check uses a freshly read inventory (`:313-314`). `complete()` checks coverage again before deleting (`:496`). - Coverage can only shrink between `authority_complete` and the delete, so the counts cannot become unsafe. - An incomplete inventory is a superset that keeps old records (`departure_inventory.go:76-82`), and `FreshAfter` gates completion. A stale or incomplete inventory can therefore only cost progress, never authorize a delete. - The rescan starts with an empty visit map (`:333`) and turns off the wait skip (`:185`). - A restart mid-walk always re-enqueues: `c.evidence` is empty, so the phase becomes `pending` and the walk resets fully (`:100-139`). **Named risk 4 (journal compatibility).** This holds in both directions, for the same reason: every process start goes through the evidence gate (`:97-120`), which forces `pending`. - An old binary therefore resets the cursor and `Rescan` before it can act on the new `Cursor` (now a visit count rather than a prefix index) or on `Generation`. It ignores the new `Waiting` field. - An old checkpoint has a nil `Visited`, which also forces a fresh walk. - I also checked that gob, used by the remote registry child, keeps an empty non-nil `Visited` map. A lost map would have dropped `Rescan`; it does not. **Named risk 2 (liveness).** The 32-record page budget still applies: the `count == 32` check comes after the already-visited skip. Every retry is at least now+30s, so the loop cannot spin. Blockers still go through the backoff ladder (`ha_journal.go:491-495`). **Named risk 3 (edges ETag rebind).** I judge this sound. - It only runs for a derived group ref, which names one account and instance ID forever, so a replacement box cannot share the key. - It requires a freshly resolved identity whose `o.Box` equals the enrolled `d.Box` exactly, including `RecordSHA256`. - It checks `v`, box, box_id, region, placement, data bucket and secrets-key fingerprint. - An explicit `null` placement is refused. An omitted placement decodes to `""`, so it only matches an empty enrolled placement. - The new tag is saved, with `DeleteUncertain`, before `DeleteRevision`, so a race still fails the conditional delete. - The fixed-ref branch is unchanged. `s.EdgesETag` is never set for fixed refs, so it falls back to `d.EdgesETag`. **Named risk 5 (tests).** - The simulation's invariant check means something. The `Adopt` wrapper fails on any early adoption. On completion, every modelled dead duty must be adopted or superseded. Seeds with an unbound successor must keep the edges file and page. - A mutation that counted waits as clean would let a held lease reach the rescan and complete, and the simulation would catch that. - `TestDepartureG3CatchUp` covers changed, added, removed and in-flight records that carry a dead release marker. ### Issues **P3. A removed record drops its unresolved or waiting visit at the next pass end** (`hadepartures_scan.go:346-369`). This follows the brief's own direction ("removed records drop out"). But the window shrinks: - **Old code:** a dead-owned host whose record is missing from the inventory was skipped only if it stayed absent across a full restarted adoption walk plus the rescan. - **New code:** it is skipped if it is absent from the published snapshot at two pass-end instants, one ending the adoption walk and one ending the rescan. That matters for a transient delete-then-create, such as a move. Cheap hardening: before `authority_complete`, read the lock (`Prefix(host)`) of every `s.Hosts` entry still marked `pending` that is missing from the inventory, and block if it still matches the dead box. **P3. A late edges publication pages once.** The first `complete()` uses the enrolled tag, gets a CAS conflict, and returns code `delete` with `page=true` (`:558-569`, deferred retry at `:440`). That gives one page and a backoff before the re-read and rebind. The flagship case (edges written at 13:00:28Z, after the terminate call) would page operators for a condition that fixes itself. Two options: always read before deleting for group refs, or treat a CAS conflict there as non-paging. The production test hides this by skipping the no-page assertion for `late_edges` (`hadepartures_g3_test.go`, production loop). **P3. Part of `TestDepartureG3InventoryWrites` proves nothing** (`hadepartures_g3_test.go:524-537`). Its "legacy cursor" loop is a toy model that calls no production code. The real starvation evidence is the `churn_*` variants failing under the overlay. Drop the loop or label it as illustration. **P3. The simulation's churn never mutates or removes records that carry duties** (the `candidates` filter at `hadepartures_g3_test.go:404`). Catch-up for records with duties is only covered by the deterministic `TestDepartureG3CatchUp`. A follow-up could allow churn on duty records too. **P3 (existing behaviour, not introduced here). A transient `ReadLock` error counts as a real blocker** (`:194`). That host stays unresolved until the walk ends, so every later page in that walk backs off up to 5 minutes and pages. On a 9-page walk, one S3 hiccup costs up to about 45 minutes. A follow-up could reclassify it as a retry within the walk. **P3. Journal write size grows with the deployment.** `Visited` holds one entry per record, and the scan is saved once per pass plus once before each adoption. At about 300 records that is roughly 40 KB per save, fine today. Worth noting for deployments in the thousands. ### Assessment **Task quality: Approved.** All named risks check out. The safety half of the invariant holds under reordering, catch-up, stale or incomplete inventories, restarts and rollback. The new edges-rebind authority is limited to the dead box's own key and verified identity. The P3s are follow-ups. The removed-record window and the one-off page on a late publication are worth deciding before the roll.</result> <usage><subagent_tokens>135147</subagent_tokens><tool_uses>25</tool_uses><duration_ms>432953</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>byhpxww3r</task-id> <tool-use-id>toolu_01VAMHi8nK1yzCvXGSE4gwVQ</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/f72ef775-81b3-4d2e-a18d-c8edb14aa192/tasks/byhpxww3r.output</output-file> <status>completed</status> <summary>Background command "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 -40" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a64a9377916bc7cce</task-id> <tool-use-id>toolu_01Ck5kNec2TsBdKr8kucrE6m</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/f72ef775-81b3-4d2e-a18d-c8edb14aa192/tasks/a64a9377916bc7cce.output</output-file> <status>completed</status> <summary>Agent "Whole-branch 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>The review is done. Full findings: `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-g3-fixes/.superpowers/sdd/2026-11-07-region-ha-g3-fixes/final-review-r1.md`. **Verdict: READY** (no P1, no P2). Checks run: gofmt clean; `go build` darwin/amd64, windows/amd64, linux/arm64 ok for host/steering/console/provision/registry; `go vet` ok; `internal/steering` whole package green; focused G3 tests in provision, console and host green (13 s). Base-failure evidence for the witnesses comes from the T2 and T4 reports' Go-overlay runs; the 21 host failures are the known lifecycle-provider baseline plus the FD probe. I confirmed the Route 53 fake's atomic per-region refusal, the journal retry ladder (code "scan" takes the caller's `next` verbatim with RetryCount reset), scan rows as plain JSON (unknown fields ignored on rollback), `Observed()` returning a copy, and the strict `poolInHAPools` predicate keyed the same way as the leftover check. Findings, one line each (all P3, none blocks): - P3-1 (T1, 6fe676da): `oneTargetPerRegion` logs one ERROR per dropped (name, box) each pass; two fixed boxes in one region yield ~135 ERROR lines every 5 min forever. Aggregate per (region, kept, dropped) with a count. - P3-2 (T2): `Cursor` is persisted as a visit count (hadepartures_scan.go:356) while the cf762224 binary reads it as a prefix position; on rollback, a millisecond-window "hole" in `Visited` could let the old code skip a changed record. Keep `Cursor` at 0 in the journal. - P3-3 (T2): comment at hadepartures_scan.go:126 ("a process restart requires a new full scan") is now false; the walk safely resumes from `Visited`. - P3-4 (T1): one extra `ListResourceRecordSets` per successful pass (route53.go:318), the price of GC'ing from the real zone. Acceptable; note for the API-cost ledger. - P3-5 (T4): the budget raises the possible `reconcileMu` hold per startup attempt from 5 s to 20 s under hanging reads; reconcile would hang on the same backend, so admission is not materially worse, but put the number in the roll notes. - P3-6 (T3): a pooled HA app whose manifest allow-list excludes its stored region now gets `not-allowed` at the door instead of silently landing on home; CLI and door agree. Release-note it. - P3-7 (T4): `TestG3StartupAttemptBudget` asserts a 100 ms timing window; fine today, widen the window rather than the budget if it ever flakes. The queued T2 P3s (removed-record window, one page on a late edges publication, toy loop) stand as queued; nothing I found raises them. The census overlay is safe to propose as a pure re-digest: no new root-data class or record-write site is added.</result> <usage><subagent_tokens>207907</subagent_tokens><tool_uses>32</tool_uses><duration_ms>782231</duration_ms></usage> </task-notification>

diff --git a/internal/host/hadepartures_g3_test.go b/internal/host/hadepartures_g3_test.go
index a319caab7..6207774cf 100644
--- a/internal/host/hadepartures_g3_test.go
+++ b/internal/host/hadepartures_g3_test.go
@@ -6,8 +6,10 @@ import (
"errors"
"fmt"
"math/rand"
+ "net/http"
"os"
"path/filepath"
+ "strings"
"testing"
"time"
@@ -246,15 +248,11 @@ func TestDepartureG3Production(t *testing.T) {
x.writeEdges(t)
}
if e := x.c.step(t.Context()); e != nil {
- // A changed ETag is refused by the conditional delete, then rebound
- // from a fresh read on the next completion attempt.
- if mode != "late_edges" || !errors.Is(e, release.ErrCASConflict) {
- t.Fatal(e)
- }
+ t.Fatal(e)
}
passes++
d = x.row(t)
- if mode != "late_edges" && (mode != "unbound" || !takeover) {
+ if mode != "unbound" || !takeover {
if d.LastError == "blocked" || d.RetryCount != 0 || x.pages != 0 {
t.Fatalf("wait/churn treated as failure: %+v pages=%d", d, x.pages)
}
@@ -519,23 +517,6 @@ func TestDepartureG3InventoryWrites(t *testing.T) {
t.Fatal(e)
}
check("instance channel update", true)
- // Reproduce the old digest/cursor rule independently of lease failures:
- // nine pages cannot finish if a raw-record write resets it every four.
- oldGeneration := digest
- cursor, resets := 0, 0
- for pass := 0; pass < 80; pass++ {
- current := fmt.Sprint(pass / 4)
- if current != oldGeneration {
- cursor = 0
- resets++
- oldGeneration = current
- }
- cursor += 32
- if cursor >= 260 {
- t.Fatal("legacy cursor unexpectedly completed")
- }
- }
- t.Logf("legacy 260-record walk, write every 2m: %d resets in 40m, cursor=%d", resets, cursor)
}
func TestDepartureG3CatchUp(t *testing.T) {
@@ -630,13 +611,10 @@ func TestDepartureG3EdgesRebindRefusals(t *testing.T) {
t.Fatal(e)
}
x.now = x.now.Add(30 * time.Second)
- if e = x.c.step(t.Context()); !errors.Is(e, release.ErrCASConflict) {
- t.Fatalf("stale ETag accepted: %v", e)
- }
if mode == "unbound" {
x.c.cfg.Identities = nil
}
- if e = x.c.Complete(t.Context(), x.id); !errors.Is(e, errDepartureIdentity) {
+ if _, e = x.c.ScanPass(t.Context()); !errors.Is(e, errDepartureIdentity) {
t.Fatalf("unsafe rebind: %v", e)
}
if _, current, e := x.store.Get(t.Context(), x.edgesKey); e != nil || current != tag {
@@ -668,13 +646,12 @@ func TestDepartureG3LateEdges(t *testing.T) {
}
x.now = x.now.Add(30 * time.Second)
x.writeEdges(t)
- if e = x.c.step(t.Context()); !errors.Is(e, release.ErrCASConflict) {
- t.Fatalf("stale ETag was not refused: %v", e)
- }
- x.now = x.now.Add(30 * time.Second)
if e = x.c.step(t.Context()); e != nil {
t.Fatal("late publication stuck", e)
}
+ if x.pages != 0 {
+ t.Fatalf("late publication paged %d times", x.pages)
+ }
if d = x.row(t); d.Phase != "complete" {
t.Fatalf("late publication never finalized: %+v", d)
}
@@ -687,3 +664,133 @@ func TestDepartureG3LateEdges(t *testing.T) {
t.Fatal("missing ack", acks)
}
}
+
+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)
+ }
+ })
+ }
+ }
+}
+
+func TestDepartureG3RollbackCheckpoint(t *testing.T) {
+ x := newG3Departure(t, 100)
+ if err := x.c.step(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ // Change an already visited record to exercise catch-up before the next
+ // checkpoint. Rollback must restart rather than interpret visits as a prefix.
+ rec := x.records[1]
+ key := provision.RecordKey(rec.Account, rec.App, rec.Host)
+ raw, tag, err := x.store.Get(t.Context(), key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = x.store.Put(t.Context(), key, append(raw, '\n'), tag); err != nil {
+ t.Fatal(err)
+ }
+ x.reconcile(t)
+ x.now = x.row(t).NextAttempt
+ 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 || len(scan.Visited) != 63 {
+ t.Fatalf("checkpoint: visits=%d %v", len(scan.Visited), err)
+ }
+ raw, err = json.Marshal(scan)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var legacy struct {
+ Generation string
+ Cursor int
+ Rescan bool
+ Unresolved int
+ }
+ if err = json.Unmarshal(raw, &legacy); err != nil {
+ t.Fatal(err)
+ }
+ inv := x.a.Inventory.Snapshot()
+ if legacy.Generation != departureInventoryDigest(inv) {
+ t.Fatal("test must exercise a checkpoint the old binary would resume")
+ }
+ // cf762224 starts at Cursor when Generation matches, ignoring Visited.
+ if legacy.Cursor != 0 || len(inv.Records[legacy.Cursor:]) != len(inv.Records) {
+ t.Fatalf("rollback skips records: cursor=%d", legacy.Cursor)
+ }
+}
diff --git a/internal/host/hadepartures_retained_test.go b/internal/host/hadepartures_retained_test.go
index 7400bb20f..8e3f6b672 100644
--- a/internal/host/hadepartures_retained_test.go
+++ b/internal/host/hadepartures_retained_test.go
@@ -273,7 +273,11 @@ func TestDepartureGroupRetainsExactDeletion(t *testing.T) {
} else if _, _, err = x.store.Get(t.Context(), x.d.EdgesKey); !errors.Is(err, os.ErrNotExist) {
t.Fatal("exact group revision not removed", err)
}
- if store.deletes != 1 {
+ wantDeletes := 1
+ if changed {
+ wantDeletes = 0 // Refuse the unverified replacement before deleting.
+ }
+ if store.deletes != wantDeletes {
t.Fatal("group delete attempts", store.deletes)
}
})
diff --git a/internal/host/hadepartures_scan.go b/internal/host/hadepartures_scan.go
index 3e9b1a96d..c20653649 100644
--- a/internal/host/hadepartures_scan.go
+++ b/internal/host/hadepartures_scan.go
@@ -123,9 +123,12 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
if err != nil {
return false, errors.Join(err, c.retryScan(ctx, d, nil, "journal", true))
}
- // A process restart requires a new qualifying inventory and a new full scan.
+ // Reobserved departures start a fresh walk; inventory publications retain
+ // visits for unchanged records within the current walk.
generation := departureInventoryDigest(inv)
s.InventoryGeneration = inv.Generation
+ // Older binaries interpret Cursor as a prefix position, never a visit count.
+ s.Cursor = 0
if d.Phase == "pending" || s.Visited == nil {
s.Generation = generation
s.Cursor = 0
@@ -313,6 +316,9 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
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)
@@ -353,7 +359,6 @@ func departureScanCoverage(s *registry.HADepartureScan, inv provision.InventoryS
continue
}
current[h.Host] = v
- s.Cursor++
if v.Unresolved {
s.Unresolved++
}
@@ -365,7 +370,48 @@ func departureScanCoverage(s *registry.HADepartureScan, inv provision.InventoryS
}
}
s.Visited = current
- return s.Cursor == len(inv.Records)
+ 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
@@ -505,7 +551,9 @@ func (c *Controller) complete(ctx context.Context, id string) (result error) {
tag = d.EdgesETag
}
fixed := d.Box.Ref != groupReferenceOf(d.Box.Account, d.Box.InstanceID)
- if fixed || s.DeleteUncertain || tag == "" {
+ // Re-read group revisions too: a late publication needs a verified
+ // binding before delete, without first causing a paging CAS failure.
+ {
call, cancel := context.WithTimeout(ctx, 5*time.Second)
raw, newTag, e := store.Get(call, d.EdgesKey)
cancel()
diff --git a/internal/host/hadepartures_scan_test.go b/internal/host/hadepartures_scan_test.go
index 388ff3b17..d85696040 100644
--- a/internal/host/hadepartures_scan_test.go
+++ b/internal/host/hadepartures_scan_test.go
@@ -382,8 +382,8 @@ func TestDepartureFairScheduling(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if a.Cursor != 64 || b.Cursor != 64 {
- t.Fatal(a.Cursor, b.Cursor)
+ if a.Cursor != 0 || b.Cursor != 0 || len(a.Visited) != 64 || len(b.Visited) != 64 {
+ t.Fatal(a.Cursor, b.Cursor, len(a.Visited), len(b.Visited))
}
}