ha: retain departure revision and classify unrelated locks
Apply P15 to completion, expiry and acknowledgement. Keep changed edges pending unless an independent verified binding names a new incarnation; preserve strict successor checks for previously matched duties.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/host/hadepartures.go+6 −2internal/host/hadepartures_fix_test.go+357 −0internal/host/hadepartures_scan.go+82 −56
Intent
<task-notification> <task-id>bptcm2wgp</task-id> <tool-use-id>toolu_017jbnce4bkcgmbvz9CaAFJk</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22c9817b-87ae-432b-b6d2-3ebbc209af38/tasks/bptcm2wgp.output</output-file> <status>completed</status> <summary>Background command "Wait for CI on B4 tip" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>ac232706c4174e2eb</task-id> <tool-use-id>toolu_01FKhNH5F79rjXwNthZ8iGzg</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22c9817b-87ae-432b-b6d2-3ebbc209af38/tasks/ac232706c4174e2eb.output</output-file> <status>completed</status> <summary>Agent "Opus review Task B4" 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>**Task quality: Needs fixes.** I found 2 Critical, 3 Important and 6 Minor issues. I reviewed all the production code and the test files. I did not review the census notes or the plan14 TSVs, and I ran no tests. **Critical** 1. **A live replacement box's edges file can be deleted** (`hadepartures_scan.go:350-381`). After a 412 or an uncertain delete, the code checks that the file still belongs to the dead box. Its instance-id check only works if the file has an `instance_id` field, and real edges files don't have one (`edgesfile/snapshot.go`). So when a fixed box is recreated (same ref, new instance id, same scope) and republishes `control/edges/<ref>.json`, the code accepts the new file, rescans, and deletes it. The test's replacement fixture includes a made-up `instance_id` field, which is why it passes. 2. **Any awake non-HA instance in the region blocks every departure from completing** (`hadepartures_scan.go:41`, `:145`). A legacy lock owner parses with `HA=false`, so it is counted as unresolved and listed as a blocker. HA is birth-only, so dev has such instances. Departures would never complete: edges stay, the queue message is never acknowledged, and the hourly page names unrelated hosts as `unsupported_wake` or a pool gap. Owners without an iid, old-lifetime markers and tombstones are blocked the same way. **Important** 1. **Every lock that never named the dead box still has to pass successor validation** (`hadepartures_scan.go:175-189`). The validator needs a stored identity with the same scope as this box. A lock held by a box not yet observed, or by a box in another placement, therefore blocks all departures. The plan only requires this check for hosts that previously matched the dead box. 2. **Several completion and evidence error paths skip the retry/backoff path** (`ScanPass:67`, `complete():324`, `:350`, `:357`, `:368`, `:371-374`). They retry every 30 seconds forever, with no 30/60/120/300 s backoff and no page, so a departure can stay stuck without anyone being told. 3. **Some witnesses are weaker than the brief and hid the defects above:** - `TestDepartureRequestBudget` doesn't cover the index-conflict maximum, the duplicate completed event (the record → acknowledge path is untested anywhere) or the idle baseline. - The pool-coverage test gives both receivers the same identity and stubs successor validation. - The production completion witness also stubs successor validation. - No test has a lock held by an unrelated live owner. The report is at `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b3b-duties/.superpowers/sdd/2026-11-03-region-ha-p1b3b-duties/task-B4-review-r1.md`.</result> <usage><subagent_tokens>195497</subagent_tokens><tool_uses>44</tool_uses><duration_ms>579381</duration_ms></usage> </task-notification>
Attributed to this commit: 5.88 g CO₂e (759,057 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-p1b3b-duties, 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/host/hadepartures.go b/internal/host/hadepartures.go| index f265702dc..d3473d7e0 100644 |
| --- a/internal/host/hadepartures.go |
| +++ b/internal/host/hadepartures.go |
| @@ -480,8 +480,8 @@ func (c *Controller) step(ctx context.Context) error { |
| func (c *Controller) ackIID(ctx context.Context, iid string) error { |
| c.receiptMu.Lock() |
| - defer c.receiptMu.Unlock() |
| receipt := c.receipts[iid] |
| + c.receiptMu.Unlock() |
| if receipt == "" { |
| return nil |
| } |
| @@ -491,7 +491,11 @@ func (c *Controller) ackIID(ctx context.Context, iid string) error { |
| if err := c.consumer.DeleteReceipt(ctx, receipt); err != nil { |
| return err |
| } |
| - delete(c.receipts, iid) |
| + c.receiptMu.Lock() |
| + if c.receipts[iid] == receipt { |
| + delete(c.receipts, iid) |
| + } |
| + c.receiptMu.Unlock() |
| return nil |
| } |
| func (c *Controller) ackDeparture(ctx context.Context, d registry.HADeparture) error { |
diff --git a/internal/host/hadepartures_fix_test.go b/internal/host/hadepartures_fix_test.go| new file mode 100644 |
| index 000000000..e3f81e9f0 |
| --- /dev/null |
| +++ b/internal/host/hadepartures_fix_test.go |
| @@ -0,0 +1,357 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/boxid" |
| + "github.com/carlosframework/platform/internal/boxid/boxidtest" |
| + "github.com/carlosframework/platform/internal/edgesfile" |
| + "github.com/carlosframework/platform/internal/hadeparture" |
| + "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 bindScanIdentity(t *testing.T, x *scanRig, ref, iid string) *departureIdentities { |
| + t.Helper() |
| + signer := boxidtest.NewSigner(t) |
| + repo := &departureIdentities{Registry: x.r, Store: x.store, Verifier: boxid.Verifier{Account: x.d.Box.Account, Certs: signer.Certs()}, Fixed: map[string]string{ref: iid}, Region: x.d.Box.Scope.CloudRegion} |
| + _, raw := signer.Record(t, ref, x.d.Box.Account, x.d.Box.Scope.CloudRegion, iid) |
| + if _, err := x.store.Put(t.Context(), boxid.Key(ref), raw, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if obs, err := repo.Observe(t.Context(), hadeparture.BoxObservation{Known: true, Box: hadeparture.Box{Ref: ref, Scope: x.d.Box.Scope}, EdgesKey: "control/edges/" + ref + ".json", EdgesETag: "identity-observation"}); err != nil { |
| + t.Fatal(err) |
| + } else if iid == x.d.Box.InstanceID { |
| + x.d.Box = obs.Box |
| + db, e := sql.Open("sqlite", x.r.Path()) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer db.Close() |
| + raw, _ := json.Marshal(x.d) |
| + if _, e = db.Exec(`UPDATE ha_departures SET body=? WHERE id=?`, raw, x.d.ID); e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + x.c.cfg.Identities = repo |
| + return repo |
| +} |
| + |
| +func TestDepartureReplacementRevision(t *testing.T) { |
| + for _, mode := range []string{"unchanged-binding", "verified-new-binding", "unverifiable-binding", "same-etag"} { |
| + t.Run(mode, func(t *testing.T) { |
| + x := newScanRig(t, 1) |
| + iid := x.d.Box.InstanceID |
| + if mode == "verified-new-binding" { |
| + iid = "i-2123456789abcdef0" |
| + } |
| + repo := bindScanIdentity(t, x, x.d.Box.Ref, iid) |
| + if mode == "unverifiable-binding" { |
| + repo.Verifier = boxid.Verifier{} |
| + } |
| + x.pass(t) |
| + s, err := x.r.DepartureScan(t.Context(), x.d.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s.Generation = departureInventoryDigest(x.inv) |
| + s.DeleteUncertain = true |
| + if err = x.r.SaveDepartureScan(t.Context(), x.d.ID, "authority_complete", s); err != nil { |
| + t.Fatal(err) |
| + } |
| + tag := x.d.EdgesETag |
| + if mode != "same-etag" { |
| + raw, _ := json.Marshal(edgesfile.PlacementView{V: 1, Box: x.d.Box.Ref, BoxID: x.d.Box.Ref, Region: x.d.Box.Scope.CloudRegion, Placement: x.d.Box.Scope.Placement, DataBucket: x.d.Box.Scope.DataBucket, SecretsKeyFP: x.d.Box.Scope.SecretsKeyFP}) |
| + tag, err = x.store.Put(t.Context(), x.d.EdgesKey, raw, tag) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + before := x.locks.reads |
| + err = x.c.Complete(t.Context(), x.d.ID) |
| + d, e := x.r.Departure(t.Context(), x.d.ID) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if mode == "same-etag" || mode == "verified-new-binding" { |
| + if err != nil || d.Phase != "complete" { |
| + t.Fatalf("phase=%s err=%v", d.Phase, err) |
| + } |
| + } else if err == nil || d.Phase != "authority_complete" || d.LastPage.IsZero() || d.LastError == "" { |
| + t.Fatalf("unverified replacement not held and paged: %+v %v", d, err) |
| + } |
| + if mode != "same-etag" { |
| + if _, got, e := x.store.Get(t.Context(), x.d.EdgesKey); e != nil || got != tag { |
| + t.Fatalf("replacement altered: %s %v", got, e) |
| + } |
| + } |
| + if x.locks.reads != before { |
| + t.Fatal("delete retry rescanned locks") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDepartureUnrelatedLockCensus(t *testing.T) { |
| + for _, mode := range []string{"legacy-peer", "legacy-dead", "no-iid", "ha-peer", "other-placement", "old-marker-peer", "old-marker-dead", "tombstone", "malformed-ha", "dead-ha"} { |
| + t.Run(mode, func(t *testing.T) { |
| + x := newScanRig(t, 1) |
| + h := x.inv.Records[0] |
| + v := x.locks.views[h.Host] |
| + v.Lock.Release = nil |
| + v.Lock.ExpiresAt = x.now.Add(-time.Hour) |
| + ref, iid := "live", "i-2123456789abcdef0" |
| + if mode == "legacy-dead" || mode == "old-marker-dead" || mode == "dead-ha" { |
| + ref, iid = x.d.Box.Ref, x.d.Box.InstanceID |
| + } |
| + if mode == "no-iid" { |
| + iid = "" |
| + } |
| + v.Lock.Owner = hafresh.OwnerFor(hafresh.Self{Ref: ref, IID: iid, Boot: "boot"}, 1, mode == "ha-peer" || mode == "dead-ha" || mode == "other-placement") |
| + switch mode { |
| + case "legacy-peer", "legacy-dead": |
| + x.inv.Records[0].HA = false |
| + case "other-placement": |
| + x.inv.Records[0].Placement = "other" |
| + case "old-marker-peer", "old-marker-dead": |
| + v.Lock.Release = &hafresh.Marker{V: 1, Box: ref, IID: iid, Lifetime: "old"} |
| + v.Lock.Owner = hafresh.MarkerOwner(*v.Lock.Release) |
| + v.Lock.ExpiresAt = time.Unix(0, 0) |
| + case "tombstone": |
| + v.Lock.Owner = "moved:operation" |
| + v.Lock.ExpiresAt = time.Unix(0, 0) |
| + case "malformed-ha": |
| + v.Lock.Owner = "box/v1;ref=dead;iid=bad;ha=1" |
| + } |
| + x.locks.views[h.Host] = v |
| + validations := 0 |
| + x.c.cfg.ValidateSuccessor = func(context.Context, string, string) (bool, error) { validations++; return false, nil } |
| + for range 3 { |
| + x.pass(t) |
| + } |
| + d, err := x.r.Departure(t.Context(), x.d.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + blocked := mode == "malformed-ha" || mode == "old-marker-dead" || mode == "dead-ha" |
| + if (d.Phase != "complete") != blocked { |
| + t.Fatalf("phase=%s imports=%d", d.Phase, x.imports) |
| + } |
| + if !blocked && (validations != 0 || x.imports != 0) { |
| + t.Fatalf("unrelated lock validated/imported: %d/%d", validations, x.imports) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +type timedScanReader struct { |
| + x *scanRig |
| + expiry time.Time |
| +} |
| + |
| +func (r timedScanReader) ReadLock(ctx context.Context, b, p string) (hafresh.View, error) { |
| + v, e := r.x.locks.ReadLock(ctx, b, p) |
| + r.x.now = r.expiry.Add(time.Nanosecond) |
| + return v, e |
| +} |
| +func TestDepartureReadMustStartPastExpiry(t *testing.T) { |
| + x := newScanRig(t, 1) |
| + h := x.inv.Records[0] |
| + v := x.locks.views[h.Host] |
| + v.Lock.Release = nil |
| + v.Lock.Owner = hafresh.OwnerFor(hafresh.Self{Ref: x.d.Box.Ref, IID: x.d.Box.InstanceID}, 1, true) |
| + v.Lock.ExpiresAt = x.now.Add(time.Second) |
| + x.locks.views[h.Host] = v |
| + x.c.cfg.NewReader = func(context.Context, string) (DepartureLockReader, error) { |
| + return timedScanReader{x, v.Lock.ExpiresAt}, nil |
| + } |
| + x.pass(t) |
| + if x.imports != 0 { |
| + t.Fatal("import used a read started before expiry") |
| + } |
| + x.c.cfg.NewReader = func(context.Context, string) (DepartureLockReader, error) { return x.locks, nil } |
| + x.pass(t) |
| + if x.imports != 1 || x.locks.reads != 2 { |
| + t.Fatal(x.imports, x.locks.reads) |
| + } |
| +} |
| + |
| +type failedCompletionGet struct { |
| + *completionStore |
| + err error |
| +} |
| + |
| +func (s *failedCompletionGet) Get(ctx context.Context, k string) ([]byte, string, error) { |
| + return nil, "", s.err |
| +} |
| +func TestDepartureFailureBackoff(t *testing.T) { |
| + for _, mode := range []string{"identity", "get", "open", "unsupported", "index"} { |
| + t.Run(mode, func(t *testing.T) { |
| + x := newScanRig(t, 0) |
| + if mode != "identity" { |
| + x.pass(t) |
| + s, _ := x.r.DepartureScan(t.Context(), x.d.ID) |
| + s.DeleteUncertain = true |
| + if e := x.r.SaveDepartureScan(t.Context(), x.d.ID, "authority_complete", s); e != nil { |
| + t.Fatal(e) |
| + } |
| + } else { |
| + x.c.evidence = nil |
| + } |
| + store := &completionStore{Store: x.store, raw: x.store, indexFail: mode == "index"} |
| + switch mode { |
| + case "get": |
| + x.c.cfg.OpenStore = func(context.Context) (release.Store, error) { |
| + return &failedCompletionGet{store, errors.New("get_denied")}, nil |
| + } |
| + case "open": |
| + x.c.cfg.OpenStore = func(context.Context) (release.Store, error) { return nil, errors.New("open_failed") } |
| + case "unsupported": |
| + x.c.cfg.OpenStore = func(context.Context) (release.Store, error) { return struct{ release.Store }{x.store}, nil } |
| + case "index": |
| + x.c.cfg.OpenStore = func(context.Context) (release.Store, error) { return store, nil } |
| + } |
| + pages := 0 |
| + x.c.cfg.Page = func(context.Context, registry.HADeparture, []provision.DepartureHost) error { pages++; return nil } |
| + for _, wait := range []time.Duration{30 * time.Second, time.Minute, 2 * time.Minute, 5 * time.Minute} { |
| + var err error |
| + if mode == "identity" { |
| + _, err = x.c.ScanPass(t.Context()) |
| + } else { |
| + err = x.c.Complete(t.Context(), x.d.ID) |
| + } |
| + if err == nil { |
| + t.Fatal("error swallowed") |
| + } |
| + d, e := x.r.Departure(t.Context(), x.d.ID) |
| + if e != nil || d.NextAttempt.Sub(x.now) != wait || d.LastPage.IsZero() { |
| + t.Fatalf("wait=%s departure=%+v err=%v", wait, d, e) |
| + } |
| + x.now = d.NextAttempt |
| + } |
| + if pages != 1 { |
| + t.Fatal("page count", pages) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDeparturePermissionFaultNotice(t *testing.T) { |
| + x := newScanRig(t, 0) |
| + store := &completionStore{Store: x.store, raw: x.store, deny: true} |
| + x.c.cfg.OpenStore = func(context.Context) (release.Store, error) { return store, nil } |
| + var logs []string |
| + x.c.cfg.Logf = func(f string, a ...any) { logs = append(logs, fmt.Sprintf(f, a...)) } |
| + pages := 0 |
| + x.c.cfg.Page = func(context.Context, registry.HADeparture, []provision.DepartureHost) error { pages++; return nil } |
| + x.pass(t) |
| + _, _ = x.c.ScanPass(t.Context()) |
| + for range 2 { |
| + _ = x.c.Complete(t.Context(), x.d.ID) |
| + } |
| + count := 0 |
| + for _, l := range logs { |
| + if strings.Contains(l, "ha_departure_permission_fault") && strings.Contains(l, x.d.EdgesKey) { |
| + count++ |
| + } |
| + if strings.Contains(l, "Check the box's wake state") { |
| + t.Fatal("permission fault used C3") |
| + } |
| + } |
| + if count != 1 || pages != 0 { |
| + t.Fatal(logs, pages) |
| + } |
| + store.deny = false |
| + store.indexFail = true |
| + _ = x.c.Complete(t.Context(), x.d.ID) |
| + s, e := x.r.DepartureScan(t.Context(), x.d.ID) |
| + if e != nil || s.PermissionAlerted { |
| + t.Fatal("permission fault not cleared", s, e) |
| + } |
| +} |
| + |
| +type heldDeleteQueue struct{ entered, release chan struct{} } |
| + |
| +func (q *heldDeleteQueue) Receive(ctx context.Context, _ time.Duration) ([]hadeparture.Message, error) { |
| + <-ctx.Done() |
| + return nil, ctx.Err() |
| +} |
| +func (q *heldDeleteQueue) Delete(ctx context.Context, _ string) error { |
| + close(q.entered) |
| + select { |
| + case <-q.release: |
| + return nil |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + } |
| +} |
| +func TestDepartureAckDoesNotBlockRecord(t *testing.T) { |
| + x := newScanRig(t, 0) |
| + x.c.cfg.Self.Account = x.d.Box.Account |
| + x.c.cfg.Self.InstanceID = "i-0123456789abcdef0" |
| + q := &heldDeleteQueue{make(chan struct{}), make(chan struct{})} |
| + ready := make(chan struct{}) |
| + // Initialize the real consumer's queue without sending an event. |
| + x.c.consumer = hadeparture.NewConsumer(func(context.Context) error { return nil }, x.c.record, nil) |
| + life, e := x.c.Start(t.Context(), func(context.Context) (hadeparture.Queue, error) { close(ready); return q, nil }) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer life.Stop(context.Background()) |
| + <-ready |
| + x.c.receipts = map[string]string{x.d.Box.InstanceID: "old"} |
| + ack := make(chan error, 1) |
| + go func() { |
| + // Queue installation follows MakeQueue; retry only that startup refusal. |
| + for { |
| + e := x.c.ackIID(t.Context(), x.d.Box.InstanceID) |
| + if e == nil || e.Error() != "ha_receipt_unavailable" { |
| + ack <- e |
| + return |
| + } |
| + time.Sleep(time.Millisecond) |
| + } |
| + }() |
| + select { |
| + case <-q.entered: |
| + case <-time.After(time.Second): |
| + t.Fatal("delete never started") |
| + } |
| + recorded := make(chan error, 1) |
| + go func() { |
| + recorded <- x.c.record(t.Context(), hadeparture.Message{Receipt: "new", Body: terminationHint(x.d.Box.InstanceID)}) |
| + }() |
| + blocked := false |
| + select { |
| + case e = <-recorded: |
| + if e != nil { |
| + t.Error(e) |
| + } |
| + case <-time.After(time.Second): |
| + blocked = true |
| + } |
| + close(q.release) |
| + if e = <-ack; e != nil { |
| + t.Error(e) |
| + } |
| + if blocked { |
| + if e = <-recorded; e != nil { |
| + t.Error(e) |
| + } |
| + t.Error("record blocked on network Delete") |
| + } |
| + x.c.receiptMu.Lock() |
| + defer x.c.receiptMu.Unlock() |
| + if x.c.receipts[x.d.Box.InstanceID] != "new" { |
| + t.Error("old acknowledgement removed current receipt") |
| + } |
| +} |
diff --git a/internal/host/hadepartures_scan.go b/internal/host/hadepartures_scan.go| index 4eebbeaaf..8963fe2e4 100644 |
| --- a/internal/host/hadepartures_scan.go |
| +++ b/internal/host/hadepartures_scan.go |
| @@ -7,6 +7,7 @@ import ( |
| "errors" |
| "fmt" |
| "os" |
| + "strings" |
| "time" |
| "github.com/aws/smithy-go" |
| @@ -40,6 +41,22 @@ func departureLockIdentity(v hafresh.View, life string) (string, string, bool) { |
| o, ok := hafresh.ParseOwner(v.Lock.Owner) |
| return o.Ref, o.IID, ok && o.HA && o.IID != "" |
| } |
| + |
| +// An unseen lock with a classified non-departed identity carries no duty for D. |
| +// Previously matched hosts still require the strict successor checks below. |
| +func unrelatedDepartureLock(v hafresh.View, ref, iid string) bool { |
| + if v.Absent || v.ETag == "" || v.Lock.Generation < 0 || v.Lock.ExpiresAt.IsZero() { |
| + return false |
| + } |
| + if m := v.Lock.Release; m != nil { |
| + r, i, ok := departureLockIdentity(v, m.Lifetime) |
| + return ok && (r != ref || i != iid) |
| + } |
| + if o, ok := hafresh.ParseOwner(v.Lock.Owner); ok { |
| + return !o.HA || o.IID == "" || o.Ref != ref || o.IID != iid |
| + } |
| + return strings.HasPrefix(v.Lock.Owner, lease.TombstonePrefix) && len(v.Lock.Owner) > len(lease.TombstonePrefix) |
| +} |
| func scanDigest(v any) string { b, _ := json.Marshal(v); return fmt.Sprintf("%x", sha256.Sum256(b)) } |
| func (c *Controller) ScanPass(ctx context.Context) (bool, error) { |
| c.scanMu.Lock() |
| @@ -55,23 +72,23 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) { |
| if _, err = c.cfg.Registry.RetryDeparture(ctx, d.ID, c.now(), c.now().Add(30*time.Second), "reserve", false); err != nil { |
| return false, err |
| } |
| - if d.Phase == "edges_deleted_or_absent" || d.Phase == "indexed" { |
| + if d.Phase == "authority_complete" && c.evidence[d.ID] || d.Phase == "edges_deleted_or_absent" || d.Phase == "indexed" { |
| return true, c.complete(ctx, d.ID) |
| } |
| if !c.evidence[d.ID] { |
| if c.cfg.Identities == nil { |
| - return false, errDeparturePending |
| + return false, errors.Join(errDeparturePending, c.retryScan(ctx, d, nil, "identity", true)) |
| } |
| o, ok, e := c.cfg.Identities.Resolve(ctx, d.Box.Ref, d.Box.InstanceID) |
| if e != nil || !ok { |
| - return false, errors.Join(e, errDeparturePending) |
| + return false, errors.Join(e, errDeparturePending, c.retryScan(ctx, d, nil, "identity", true)) |
| } |
| if e = c.Enqueue(ctx, o); e != nil { |
| - return false, e |
| + return false, errors.Join(e, c.retryScan(ctx, d, nil, "evidence", true)) |
| } |
| d.ObservedAt = c.now() |
| if e = c.cfg.Registry.ReobserveDeparture(ctx, d.ID, d.ObservedAt); e != nil { |
| - return false, e |
| + return false, errors.Join(e, c.retryScan(ctx, d, nil, "evidence", true)) |
| } |
| d.Phase = "pending" |
| if c.evidence == nil { |
| @@ -129,6 +146,7 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) { |
| continue |
| } |
| call, done := context.WithTimeout(ctx, 5*time.Second) |
| + readStarted := c.now() |
| v, e := reader.ReadLock(call, d.Box.Scope.DataBucket, c.cfg.Prefix(h.Host)) |
| done() |
| if e != nil { |
| @@ -141,6 +159,9 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) { |
| } |
| continue |
| } |
| + if !seen && unrelatedDepartureLock(v, d.Box.Ref, d.Box.InstanceID) { |
| + continue |
| + } |
| ref, iid, valid := departureLockIdentity(v, h.Lifetime) |
| if !valid { |
| s.Unresolved++ |
| @@ -149,6 +170,9 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) { |
| } |
| match := MatchesDeparture(v, d.Box.Ref, d.Box.InstanceID, h.Lifetime) |
| if !match { |
| + if !seen { |
| + continue |
| + } |
| if seen && ref == c.cfg.Self.Ref && iid == c.cfg.Self.InstanceID { |
| receipt, present, e := c.cfg.Registry.HAAdoption(ctx, h.Host, h.Lifetime, d.ID) |
| if e != nil { |
| @@ -209,7 +233,7 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) { |
| blockers = append(blockers, h) |
| continue |
| } |
| - if v.Lock.Release == nil && !c.now().After(v.Lock.ExpiresAt) { |
| + if v.Lock.Release == nil && !readStarted.After(v.Lock.ExpiresAt) { |
| old.NotBefore = v.Lock.ExpiresAt |
| s.Hosts[h.Host] = old |
| s.Unresolved++ |
| @@ -274,6 +298,10 @@ func (c *Controller) retryScan(ctx context.Context, d registry.HADeparture, host |
| return err |
| } |
| if claimed { |
| + if code == "permission" { |
| + c.logf("ha_departure_permission_fault key=%s", d.EdgesKey) |
| + return nil |
| + } |
| c.logf("Duties from box %s have not been recovered. The scan will retry automatically. Check the box's wake state before removing its records.", d.Box.Ref) |
| if c.cfg.Page != nil { |
| return c.cfg.Page(ctx, d, hosts) |
| @@ -286,7 +314,7 @@ func (c *Controller) Complete(ctx context.Context, id string) error { |
| defer c.scanMu.Unlock() |
| return c.complete(ctx, id) |
| } |
| -func (c *Controller) complete(ctx context.Context, id string) error { |
| +func (c *Controller) complete(ctx context.Context, id string) (result error) { |
| d, err := c.cfg.Registry.Departure(ctx, id) |
| if err != nil { |
| return err |
| @@ -294,6 +322,16 @@ func (c *Controller) complete(ctx context.Context, id string) error { |
| if d.Phase == "complete" { |
| return c.ackDeparture(ctx, d) |
| } |
| + code := "completion" |
| + defer func() { |
| + if result == nil { |
| + return |
| + } |
| + retryCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) |
| + defer cancel() |
| + result = errors.Join(result, c.retryScan(retryCtx, d, nil, code, true)) |
| + }() |
| + |
| s, err := c.cfg.Registry.DepartureScan(ctx, id) |
| if err != nil { |
| return err |
| @@ -336,52 +374,39 @@ func (c *Controller) complete(ctx context.Context, id string) error { |
| } |
| s.InventoryGeneration = inv.Generation |
| tag := d.EdgesETag |
| - if s.EdgesETag != "" { |
| - tag = s.EdgesETag |
| - } |
| if s.DeleteUncertain || tag == "" { |
| call, cancel := context.WithTimeout(ctx, 5*time.Second) |
| - raw, newTag, e := store.Get(call, d.EdgesKey) |
| + _, newTag, e := store.Get(call, d.EdgesKey) |
| cancel() |
| if errors.Is(e, os.ErrNotExist) { |
| if err = save("edges_deleted_or_absent"); err != nil { |
| return err |
| } |
| + |
| } else if e != nil { |
| - return e |
| - } else { |
| - // Replacements need their own full scan, and must retain the exact binding. |
| - var f struct{ Box, BoxID, Region, Placement, DataBucket, SecretsKeyFP, IID string } |
| - var wire map[string]json.RawMessage |
| - if json.Unmarshal(raw, &wire) != nil { |
| - return errDepartureScope |
| - } |
| - get := func(k string) string { var v string; _ = json.Unmarshal(wire[k], &v); return v } |
| - f.Box = get("box") |
| - f.BoxID = get("box_id") |
| - f.Region = get("region") |
| - f.Placement = get("placement") |
| - f.DataBucket = get("data_bucket") |
| - f.SecretsKeyFP = get("secrets_key_fp") |
| - f.IID = get("instance_id") |
| - if f.Box != d.Box.Ref || (f.BoxID != "" && f.BoxID != d.Box.Ref) || f.Region != d.Box.Scope.CloudRegion || f.Placement != d.Box.Scope.Placement || f.DataBucket != d.Box.Scope.DataBucket || f.SecretsKeyFP != d.Box.Scope.SecretsKeyFP || (f.IID != "" && f.IID != d.Box.InstanceID) || string(wire["placement"]) == "null" { |
| - return errDepartureScope |
| + code = "edges_read" |
| + if departurePermissionFault(e) { |
| + code = "permission" |
| } |
| + return e |
| + } else if tag == "" || newTag != tag { |
| + code = "replacement_binding" |
| if c.cfg.Identities == nil { |
| return errDepartureIdentity |
| } |
| - o, known, e := c.cfg.Identities.Resolve(ctx, d.Box.Ref, d.Box.InstanceID) |
| - if e != nil || !known || o.Box != d.Box { |
| - return errDepartureIdentity |
| + // Edges have no iid. Only an independently verified changed binding |
| + // can establish that the retained incarnation's publication is gone. |
| + o, known, e := c.cfg.Identities.Resolve(ctx, d.Box.Ref, "") |
| + if e != nil || !known || !o.Known || o.PlacementNull || o.Box.Ref != d.Box.Ref || o.Box.InstanceID == "" || o.Box.InstanceID == d.Box.InstanceID || o.Box.Account != d.Box.Account || o.Box.Scope != d.Box.Scope { |
| + return errors.Join(e, errDepartureIdentity) |
| + } |
| + s.PermissionAlerted = false |
| + if err = save("edges_deleted_or_absent"); err != nil { |
| + return err |
| } |
| - s.EdgesETag = newTag |
| - s.DeleteUncertain = false |
| - s.Generation = "" |
| - s.Rescan = false |
| - s.Cursor = 0 |
| - return save("scanning") |
| } |
| } |
| + |
| if d.Phase == "authority_complete" { |
| // Persist uncertainty before the call, including death after the remote effect. |
| s.DeleteUncertain = true |
| @@ -391,28 +416,21 @@ func (c *Controller) complete(ctx context.Context, id string) error { |
| call, cancel := context.WithTimeout(ctx, 5*time.Second) |
| err = indexed.DeleteRevision(call, d.EdgesKey, tag) |
| cancel() |
| + |
| if err != nil { |
| - var ae smithy.APIError |
| - if errors.As(err, &ae) && ae.ErrorCode() == "AccessDenied" { |
| + code = "delete" |
| + s.PermissionAlerted = departurePermissionFault(err) |
| + if s.PermissionAlerted { |
| + code = "permission" |
| s.DeleteUncertain = false |
| - if !s.PermissionAlerted { |
| - s.PermissionAlerted = true |
| - if e := save("authority_complete"); e != nil { |
| - return e |
| - } |
| - c.logf("ha_departure_permission id=%s code=AccessDenied", id) |
| - if c.cfg.Page != nil { |
| - _ = c.cfg.Page(ctx, d, nil) |
| - } |
| - } else { |
| - if e := save("authority_complete"); e != nil { |
| - return e |
| - } |
| - } |
| } |
| - _ = c.retryScan(ctx, d, nil, "delete", false) |
| + if e := save("authority_complete"); e != nil { |
| + return errors.Join(err, e) |
| + } |
| return err |
| } |
| + s.PermissionAlerted = false |
| + |
| if err = save("edges_deleted_or_absent"); err != nil { |
| return err |
| } |
| @@ -423,7 +441,10 @@ func (c *Controller) complete(ctx context.Context, id string) error { |
| err = indexed.IndexDeletion(call, d.EdgesKey) |
| cancel() |
| if err != nil { |
| - _ = c.retryScan(ctx, d, nil, "index", false) |
| + code = "index" |
| + if departurePermissionFault(err) { |
| + code = "permission" |
| + } |
| return err |
| } |
| if err = save("indexed"); err != nil { |
| @@ -448,3 +469,8 @@ func departureInventoryDigest(inv provision.InventorySnapshot) string { |
| Records []provision.DepartureHost |
| }{inv.Complete, inv.Records}) |
| } |
| + |
| +func departurePermissionFault(err error) bool { |
| + var ae smithy.APIError |
| + return errors.As(err, &ae) && ae.ErrorCode() == "AccessDenied" |
| +} |