region HA DR-5: finish departures when nobody serves the pool
A departure now finishes when no surviving box in the region serves a departed member's pool (spec §7.5): such hosts are recorded unserved with no import and no lock write, rechecked at one finalization gate right before the edges delete. Departures finish within 3 min of proof (scan every due departure per step, defer inventory requests inside the 60 s spacing, rescan at once). N6 reproduction test included. Astra R3 P1 accepted by Paul as the §7.5 publication race. Census census-ruling-region-ha-dr5 approved (Astra) on #280. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from fix/region-ha-dr5 into main.
15 files changed,
+1,257
−24
docs/superpowers/notes/census-proposal-region-ha-dr5.md+26 −0docs/superpowers/plans/2026-11-08-region-ha-dr5-unserved-departures.md+57 −0docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md+30 −1internal/edge/hadepartures.go+2 −0internal/hadeparture/pools_test.go+25 −0internal/hadeparture/types.go+25 −0internal/host/changeindex.go+49 −7internal/host/changeindex_nudger_dr5_test.go+68 −0internal/host/hadepartures.go+25 −2internal/host/hadepartures_dr5_test.go+777 −0internal/host/hadepartures_g3_test.go+18 −9internal/host/hadepartures_production_test.go+9 −1internal/host/hadepartures_scan.go+129 −4internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-region-ha-dr5.tsv+16 −0
CI passed — run details
diff --git a/docs/superpowers/notes/census-proposal-region-ha-dr5.md b/docs/superpowers/notes/census-proposal-region-ha-dr5.md| new file mode 100644 |
| index 000000000..5d3cd6038 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-region-ha-dr5.md |
| @@ -0,0 +1,26 @@ |
| +# Census approval: region-ha-dr5 |
| + |
| +Ruling `census-ruling-region-ha-dr5`. The independent reviewer approves or rejects every change below, 4 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/host/hadepartures_scan.go` `Controller.ScanPass` | sites | +registry:Hosts, +registry:Rescan, +registry:Result, +whole:HADeparture, +whole:HADepartureHostScan ×2 | BASIS AMENDED by spec 7.5 (DR-5, approved by agent manager 8a3d302 for the region HA standing approval): the B4 completion gate "adoption or validated successor" becomes "adoption, validated successor, or unserved discharge". A host may be discharged unserved only when (1) its lock is a valid release marker naming the departed box or a held lock whose expiry this box read as passed, (2) this box would adopt it but for the pool (placement, HA, lifetime, kind and sidecar rules, not denied), and (3) the complete in-memory departure view shows no in-scope box that serves or may serve the pool, other than group members with a departure enrolled in this box journal (fixed refs never count as gone; unknown served_pools blocks). Every unserved discharge is rechecked at one finalization gate immediately before the conditional edges delete. An unserved host is never imported and its lock is never written, so no lease authority moves; the full zero-match rescan still runs, with unserved hosts the only allowed matches. Inputs: served_pools comes from edges files that only box roles write (already trusted by this scan for identity and by placement); a box agent that lies can at most let a departure finish without import, which it can already cause by deleting edges files with its own role. No new remote read; reads Hosts/Rescan/Result from the local journal. The rescan is due at once. | |
| + |
| +Envelopes re-pinned: `internal/edge`, `internal/hadeparture`, `internal/host`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `internal/host/hadepartures_scan.go` `Controller.ScanPass`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=B4: Read authoritative pre-filter inventory, exact canonical lock revisions through one page reader, local scan checkpoints and adoption receipts. Persist source identity before the sole AdoptHost importer; validate later successor identity/lifetime/generation and require a fresh full zero-match rescan. Unknown state, unsupported hosts and missing previously matched locks refuse completion. No process launch or tenancy expansion. Preserve checkpoints across walks of identical record bytes; persist the current inventory generation separately and recheck source freshness/completeness before every page and deletion. Placement changes cannot filter the lock census. Fix r1/P15: classify legacy and unrelated locks as zero only before any D match; keep strict successor checks for previously matched hosts and hold malformed HA identities. Compare read start to expiry. Resume authority-complete deletion without rescanning unchanged inventory; persist evidence and scan errors with bounded retry. B4 fix r2: Inventory-only waits request the existing hourly page only after observed evidence is older than ChangeIndexBackstop plus 10 percent. Freshness and completion gates are unchanged; no new read. B5: Route the unchanged AdoptHost callback through measured telemetry; no new authority or lock read.;rev3=census-ruling-region-ha-p3b;basis=Gate and register the existing departure scan with admission before any work. Existing registry/object reads remain, closed members do not import, and shutdown cancels/joins registered work; no new root input.;rev3=census-ruling-region-ha-g2r-fixes;basis=W3: when a departure is blocked only on inventory freshness, signals the bounded early backstop round (global 60 s spacing, three per evidence) instead of waiting for the 30 min backstop. FreshAfter/I3 gates unchanged; no walk inside the step; no new read.;rev3=census-ruling-region-ha-g3-fixes;basis=Track current record revisions across inventory publications; separate lease waits from blockers and persist Cursor as zero for rollback. Drop removed records from coverage while retaining adoption or validated-successor gates for current hosts. Use the bounded lock-prefix listing only after validating every current host prefix; preserve per-host reads for known duties and fall back to the existing 32-host scan when listing evidence is unavailable. Cache listing evidence only in this process under scanMu, invalidate it on blocked work or inventory changes, and permit 128 reads with proven listing coverage. Added reads include departure LastError, host scan state and registry Hosts; the new remote read is a bounded LIST of the configured lock prefix in the existing data bucket. |
| + |
| +New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff: |
| + |
| +- new `internal/host/hadepartures_scan.go:Controller.unserved`: reads +whole:HADeparture; written legacy, accepted-legacy, frozen |
| +- new `internal/host/hadepartures_scan.go:Controller.unservedRevoked`: reads +registry:Hosts, +registry:Lifetime, +registry:Result, +whole:HADeparture, +whole:HADepartureHostScan; written legacy, accepted-legacy, frozen |
| +- reads `internal/host/hadepartures.go:Controller.step`: +registry:NextAttempt ×2, +whole:HADeparture ×5; keeps legacy, task accepted-legacy |
| +- reads `internal/host/hadepartures_scan.go:Controller.complete`: +registry:DeleteUncertain, +registry:Rescan, +registry:Result, +registry:Visited, +whole:HADeparture, +whole:HADepartureScan, +whole:HADepartureVisit; keeps legacy, task accepted-legacy |
| + |
| +Seal: `feba66806ddfcbdfaf369d72413bb18e75162263b6f82f117fccf1b75497986a` → `f19eb78c1da1475cbf8e11a3d6c394d828aa1c8f88ae24469fe8d473581b934b`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-region-ha-dr5.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/plans/2026-11-08-region-ha-dr5-unserved-departures.md b/docs/superpowers/plans/2026-11-08-region-ha-dr5-unserved-departures.md| new file mode 100644 |
| index 000000000..1607ebf23 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-08-region-ha-dr5-unserved-departures.md |
| @@ -0,0 +1,57 @@ |
| +# Plan: DR-5, departures that finish when nobody serves the pool |
| + |
| +Spec: `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` §7.5 (rev 6.5). |
| +Branch `fix/region-ha-dr5`, worktree `.claude/worktrees/region-ha-dr5`. Ledger and scratch: `~/.cache/region-ha-dr5/`. |
| +No release, no live boxes, no infra. |
| + |
| +## Task 1: the N6 reproduction (red first) |
| + |
| +`internal/host/hadepartures_dr5_test.go`, on the `g3Departure` harness (real `armHADepartures`, real lock fixture, real record store, real journal; only time and the queue are faked). |
| +- Two group members, both terminated and enrolled at T (proof time). Self is a fixed box with no named pools (`CARLOS_POOLS` unset). |
| +- Records in pool `ha`, HA, born on the members. Member A is the releaser of two of them (clean markers, generations as in N6). Member B holds nothing. Some shared-pool records exist too. |
| +- The departure view (`Controller.Tick`) holds self (`served_pools ["shared"]` form as published), A and B (`served_pools ["ha"]`). |
| +- Inventory rounds run only when requested, through the real `inventoryNudger` with the fake clock, and each takes 20 s of walk. Steps run every 30 s as `work` does. Churn: one record write per 30 s, as in N6. |
| +- Assert: both departures `complete`, both edges files and both status snapshots 404, both queue messages acked, all within 3 min of T; no adoption of a pool `ha` host; their locks unchanged byte for byte; no page. |
| +- Assert steering unchanged: `steering.ConvergeDeployment` on a fake Route 53 with the edges files before and after makes the same record set (no change batch after retirement). |
| +- Today: A's departure never completes (fails on the rule), and B's takes more than 3 min under this model (fails on timing). Record both numbers in the ledger. |
| + |
| +Negative cases in the same file: |
| +- a surviving peer in scope publishes `served_pools` with `ha`: A's departure stays blocked (today's behaviour); |
| +- a peer with missing or malformed `served_pools`: blocked; |
| +- an incomplete departure view: blocked; |
| +- a held, unexpired lock naming A: waits until expiry, then unserved; never before; |
| +- a host whose placement differs from self's: still blocked (rule 2); |
| +- the rescan finds an unserved host's lock changed to a new owner: successor path as today. |
| + |
| +## Task 2: the unserved rule (spec §7.5 rules 1-3) |
| + |
| +- `hadeparture.BoxObservation` gains `ServedPools []string` and `PoolsKnown bool`; `edge.homeMap.departureView` fills them from the fold's `served_pools` (`PoolEvidence.Pools()`). |
| +- `ScanPass`: when `CanAdopt` is false, test `CanAdopt` again with the policy's pools set to the host's pool. If that passes and `c.unserved(ctx, d, h)` holds, fall through to the existing expiry wait instead of blocking. After the wait, record `Result = "unserved"`, keep the visit resolved, log `ha_departure_unserved departure=… host=… pool=…`, and skip the import. |
| +- `c.unserved`: the view is complete; every peer in scope either publishes known pools without the host's pool, or resolves (`Identities.Resolve`) to a box with an enrolled departure in the journal. Self is excluded (rule 2 covers it). |
| +- Rescan: a matching host already recorded `unserved` with the same lock generation stays resolved if `c.unserved` still holds; otherwise it blocks as today. |
| +- The completion line counts only imported hosts. |
| + |
| +## Task 3: timing (spec §7.5 Timing) |
| + |
| +- `step`: call `ScanPass` until it reports no due departure, at most 8 times, within the step's context. |
| +- `inventoryNudger.request`: a request inside the 60 s spacing records `pending` and arms one timer for the end of the spacing; `begin` is unchanged, so the spacing and the three-round limit hold. Unit tests on the nudger with a fake clock. |
| +- `ScanPass`: when a clean adoption pass sets `Rescan`, the next attempt is now, not +30 s. |
| + |
| +### S3 requests (8a3d302 condition 2) |
| + |
| +No new periodic S3 request. The unserved rule reads only the in-memory departure view and the local journal. The step loop scans only departures already due. Per departure, as before: one lock LIST per walk (one page per 1,000 locks) plus one GET per in-scope lock, for the adoption walk and the rescan (two walks); then at finalize one edges GET, one conditional DELETE, one index write, one status GET and one DELETE. The rescan now starts at once rather than 30 s later; its requests are the same. The deferred inventory round replaces a dropped one: rounds stay at most one per 60 s and three per piece of evidence, so a departure costs at most three early rounds, as before. |
| + |
| +## Task 4: gates |
| + |
| +- Targeted tests: `go test ./internal/host/ -run 'Departure|HADeparture|Nudger' -count=1`, `./internal/edge/ -run Departure`, `./internal/hadeparture/`. |
| +- Cross-compile check for darwin and windows (`internal/host` builds there). |
| +- Astra review of the branch (`codex -m gpt-6-astra -c model_reasoning_effort="high"`), at most three rounds, stop at the first round with no P1. |
| +- Census card (`make census-card`, `make census-propose`), verdict on #280. |
| +- CI green on the tip; origin/main an ancestor. |
| +- Merge under the region HA standing approval: squash with `-expect`, subject under 80 characters. |
| + |
| +## Out of scope |
| + |
| +- A new pool server scanning for unserved hosts: G5 item on #421 (8a3d302 condition 3). |
| +- Retiring leftovers in a region with no HA box left (dev g-428c05c1): hand step and switch-off card rule, runbook on a separate docs branch after this merges (8a3d302). |
| +- Any page or operator text: the new line is a diagnostic. |
diff --git a/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md b/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md| index f2f648c3e..753c290da 100644 |
| --- a/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md |
| +++ b/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md |
| @@ -1,6 +1,6 @@ |
| # Region HA without claims: N-box regions behind a load balancer |
| -Design, 2026-10-26, **rev 6.4** (§9.9 T1/DR-4, 2026-11-08): rev 6 APPROVED by Paul on 2026-10-26, plus his ruling N-HA7 the same day (a scope ruling, not a redesign: §2.1, §8.4, §13, §19). Astra rounds 1 to 3 are complete, and the review budget is spent (AGENTS.md, stopping rules). Branch `design-region-ha-no-claims`, cut from `origin/main` at ddf3b929. Nothing here is built. |
| +Design, 2026-10-26, **rev 6.5** (§7.5 DR-5, 2026-11-08): rev 6 APPROVED by Paul on 2026-10-26, plus his ruling N-HA7 the same day (a scope ruling, not a redesign: §2.1, §8.4, §13, §19). Astra rounds 1 to 3 are complete, and the review budget is spent (AGENTS.md, stopping rules). Branch `design-region-ha-no-claims`, cut from `origin/main` at ddf3b929. Nothing here is built. |
| This spec supersedes every claim-dependent part of "Region HA, spec 2: two-box regions" (`2026-10-15-region-ha-two-box-regions-design.md`, rev 21, cited **S2 §n**) and of spec 1 (`2026-10-04-region-ha-box-placement-design.md`, cited **S1 §n**). §16 lists what it reuses from S2, plan 2a (6834659c) and plan 2b (b1118925), and the removals this series owns. Line citations are to this worktree unless they name a module path. |
| @@ -12,6 +12,7 @@ This spec supersedes every claim-dependent part of "Region HA, spec 2: two-box r |
| - **Rev 6** is a scope cut Paul approved on 2026-10-26. Duty handoff drew a P1 in all three rounds, so the duty-file transfer protocol is deleted, not fixed again (stopping rule 2). Duties stay in local registries, as today. One scan-and-import moves them when a box leaves (§7.4). |
| - **Rev 6.2** adds the approved N-HA14 serialized operator ASG Standby maintenance exception to §12.1 (Paul, 2026-11-01). |
| - **Rev 6.4** records T1/DR-4 planned termination: shutdown ordering, release budgets and the real-terminate witness (§9.9, 2026-11-08). |
| +- **Rev 6.5** records DR-5: a departure finishes when no surviving box serves a departed box's pool, and departures finish within 3 minutes of proof (§7.5, 2026-11-08). |
| Under stopping rule 2, the families I2, I3 and I4 drew findings two rounds running. I2 and I4 are now stated as invariants, enforced in one place and checked by the simulation (§3.1). I3 drew a P1 in all three rounds, so rev 6 cuts its transfer protocol and restates I3 over the scan alone. |
| @@ -336,6 +337,34 @@ No duty files exist, and nothing is published for transfer. The wake state (time |
| **What can be lost.** A timer registered in the last second before a crash, before its wake state synced. The edges files' existing due entries for cross-box wake routing stay as they are, but failover does not depend on them. |
| +### 7.5 A pool nobody serves any more (DR-5) |
| + |
| +**The fault.** Dev rehearsal N6 (2026-11-08) destroyed the whole UK group. The fixed box dennis serves no named pool. Both members' departures were proven, but g-428c05c1 was the last releaser of both pool `ha` locks. §7.4 finishes a departure only when every host whose lock names the dead box is adopted or superseded. dennis may not adopt a pool `ha` host, and no other box could, so the departure never finished. Its edges file and status snapshot stayed, and the scan paged every retry. Flagship has the same shape: a US group plus the fixed box adi with no HA pool. Any switch-off or aborted bring-up would leave the same residue. |
| + |
| +**The rule.** A host whose lock names the departed box is **unserved** when all of these hold, and the scanning box then records it as discharged without importing it: |
| +1. The lock is a release marker naming the departed box, clean or not, or a held lock whose expiry the scanning box has seen pass. The scan already waits for expiry before any adoption (§9.4); it waits the same way here. |
| +2. The scanning box could adopt the host if it served the host's pool: same placement, an HA record with a lifetime, an instance or a sidecar whose placement rule this box meets, and this box is not denied. Every other refusal keeps blocking, as today. |
| +3. No box that could adopt it remains. The scanning box's departure view is complete, and every box in it with the same region, placement, data bucket and secrets key fingerprint either publishes known `served_pools` without the host's pool, or is a group member with a departure enrolled in this box's journal (its termination is proven). Only a group reference can be proven gone: it names one instance forever. A fixed reference is reused by its replacement, which an earlier incarnation's proof says nothing about, so a fixed box that serves or may serve the pool always keeps the departure blocked, including when the departing box is itself fixed (Astra DR-5 R1 P1). A box whose `served_pools` is missing or malformed counts as a possible server, so it keeps the departure blocked. |
| + |
| +An unserved discharge holds only while the rule does. One finalization gate, immediately before the conditional edges delete and after every other step of the finalize, rechecks every unserved host against the box's current view and policy; one that no longer qualifies sends the departure back to a fresh walk before anything is deleted (Astra DR-5 R2 and R3 P1, ruling option A by agent manager 8a3d302). The residual window, a server whose edges file the view has not folded yet, is the publication race below: the view lags publication by up to a fold period, so no local check can close it, and its outcome is the accepted one. An unserved host gets no import, and its lock is not touched. The departure then finishes as §9.3 says: edges file, index, status snapshot (DR-2) and queue message. The scan logs one diagnostic per host (`ha_departure_unserved`). It sends no page, because the operator removed the pool's last server. |
| + |
| +**Who finalizes.** Every HA box that enrolled the departure, as today; no new role. The departure controller already runs on every HA box, holds the termination proof and does the scan. Finalizing is idempotent: the deletes are conditional, and a box that finds the edges file gone moves on. The deployment housekeeper was considered and rejected. It is one elected fixed box and would add a dependency to every departure for a case the scan rule covers. A fixed-box-only rule was rejected too: a surviving member that does not serve the pool is in the same position as dennis. |
| + |
| +**Prerequisite: a fixed box that finishes departures.** The rule runs only on a box whose termination recovery is running. A fixed box needs, in `host.env`: `CARLOS_REGION_HA=1`; `CARLOS_TERMINATION_QUEUE_URL` (the region's terminations queue, same account and region as the box); `CARLOS_DEPLOYMENT_BUCKET`; `CARLOS_HIBERNATE_BUCKET` and `CARLOS_HIBERNATE_REGION` (the region's data bucket, in the box's own AWS region); a parseable `CARLOS_SECRETS_KEY` (its fingerprint is the scope); `CARLOS_REGION` as the members have it (empty in the home region); and `CARLOS_HA_FIXED_BOX_IDENTITIES` naming every other fixed box of the region. Its role needs the region-host grants: receive and delete on the queue, `ec2:DescribeInstances`, read and list under the hibernate prefix, put and get on `control/terminations/`, and delete on `control/edges/*` and `status/boxes/*`. The journal line "Termination recovery is running." confirms it. A fixed box without these (dennis after U1) finishes nothing, and DR-5 cannot help it. |
| + |
| +**What this does not change.** |
| +- **Takeover.** No box acquires, renews or rewrites the lease of an unserved host. A later server of the pool acquires it as §9.4 says: a release marker is open to any box, and an expired lock needs the persisted termination proof (N-HA16). "Takeover only after proof and expiry" stands. |
| +- **Serving.** Nothing here makes a box serve a pool it does not serve. Requests for the host keep failing until a box serving its pool exists, as they did the moment the pool's last server left. |
| +- **Duties.** The host's scheduled duties (due wakes, timers, ticks) stay in its wake state in S3 (§7.2). They run again when a box serving the pool wakes the host, which imports the wake state at restore (§5.3). Until then they do not run; nothing could run them. A box that later starts serving the pool does not scan for unserved hosts. That is a follow-up, not part of DR-5. |
| +- **The race.** A new server of the pool that has not yet published its edges file is invisible to rule 3. The departure can then finish without it; the new server still wakes the host on its first request, and the duties wait for that wake. |
| + |
| +**Timing.** N6 also took 5 min 44 s to retire g-2d46d1d5, which had nothing to adopt; the target was 5 minutes. Three delays added up: |
| +- each 30-second step scanned one departure, so two departures took turns; |
| +- an inventory round asked for inside the 60-second spacing was dropped rather than deferred, so a departure whose evidence came 30 seconds after another's waited for a later round; |
| +- the full lock rescan after a clean adoption pass waited a further 30 seconds. |
| + |
| +DR-5 changes all three. A step scans every due departure (up to 8, within the step's budget); a departure that waits, for inventory or a lease, does not stop the next one. An inventory request inside the spacing is kept and starts when the spacing ends; the spacing and the limit of three rounds per piece of evidence stay. The rescan is due as soon as the adoption pass is saved. The bound is **3 minutes from termination proof to edges file and status snapshot gone, under record churn**, with a production-wired test of the N6 shape (whole group gone, a fixed box with no named pools, churn writes) asserting it and asserting Route 53 steering unchanged. |
| + |
| ## 8. Per-instance files (H6) |
| ### 8.1 What is there |
diff --git a/internal/edge/hadepartures.go b/internal/edge/hadepartures.go| index df0420809..a95dc8206 100644 |
| --- a/internal/edge/hadepartures.go |
| +++ b/internal/edge/hadepartures.go |
| @@ -28,6 +28,8 @@ func (m *homeMap) departureView() DepartureView { |
| _ = json.Unmarshal(f.Generation, &gen) |
| at, _ := time.Parse(time.RFC3339Nano, gen) |
| o := hadeparture.BoxObservation{Box: hadeparture.Box{Ref: f.Box, Scope: hadeparture.Scope{CloudRegion: f.Region, Placement: f.Placement, DataBucket: f.DataBucket, SecretsKeyFP: f.SecretsKeyFP}}, Known: true, PlacementNull: f.placementNull, EdgesKey: key, EdgesETag: f.etag, Generation: gen, PublishedAt: at} |
| + pools, known := f.ServedPools.Pools() |
| + o.ServedPools, o.PoolsKnown = hadeparture.EncodePools(pools), known |
| if f.Box == m.self { |
| v.Self = o |
| } else { |
diff --git a/internal/hadeparture/pools_test.go b/internal/hadeparture/pools_test.go| new file mode 100644 |
| index 000000000..30c7d2df8 |
| --- /dev/null |
| +++ b/internal/hadeparture/pools_test.go |
| @@ -0,0 +1,25 @@ |
| +package hadeparture |
| + |
| +import "testing" |
| + |
| +func TestServesEncodedPools(t *testing.T) { |
| + for _, tc := range []struct { |
| + pools []string |
| + known bool |
| + pool string |
| + want bool |
| + }{ |
| + {[]string{""}, true, "", true}, |
| + {[]string{""}, true, "ha", false}, |
| + {[]string{}, true, "", false}, |
| + {[]string{"ha"}, true, "", false}, |
| + {[]string{"", "ha"}, true, "ha", true}, |
| + {[]string{"hapair"}, true, "ha", false}, |
| + {[]string{"ha"}, false, "ha", false}, |
| + } { |
| + o := BoxObservation{ServedPools: EncodePools(tc.pools), PoolsKnown: tc.known} |
| + if got := o.Serves(tc.pool); got != tc.want { |
| + t.Errorf("%q known=%v serves %q = %v", tc.pools, tc.known, tc.pool, got) |
| + } |
| + } |
| +} |
diff --git a/internal/hadeparture/types.go b/internal/hadeparture/types.go| index bcc23e4a5..184936472 100644 |
| --- a/internal/hadeparture/types.go |
| +++ b/internal/hadeparture/types.go |
| @@ -2,6 +2,7 @@ package hadeparture |
| import ( |
| "context" |
| + "strings" |
| "time" |
| ) |
| @@ -24,7 +25,31 @@ type BoxObservation struct { |
| PlacementNull bool |
| EdgesKey, EdgesETag, Generation string |
| PublishedAt time.Time |
| + // ServedPools is the box's published served_pools, encoded by |
| + // EncodePools so the observation stays comparable. PoolsKnown is false |
| + // when the field is missing or malformed (DR-5: a possible server). |
| + ServedPools string |
| + PoolsKnown bool |
| } |
| + |
| +// EncodePools writes each pool as "|"+name, so the shared pool "" and an |
| +// empty list stay distinct. Pool names never contain "|". |
| +func EncodePools(pools []string) string { |
| + var b strings.Builder |
| + for _, p := range pools { |
| + b.WriteString("|") |
| + b.WriteString(p) |
| + } |
| + return b.String() |
| +} |
| + |
| +// Serves reports whether the observed box publishes pool among known |
| +// served pools. Unknown evidence serves nothing here; callers treat |
| +// !PoolsKnown as a possible server themselves. |
| +func (o BoxObservation) Serves(pool string) bool { |
| + return o.PoolsKnown && strings.Contains(o.ServedPools+"|", "|"+pool+"|") |
| +} |
| + |
| type Departure struct { |
| ID string |
| Box Box |
diff --git a/internal/host/changeindex.go b/internal/host/changeindex.go| index 954994fd3..120d66033 100644 |
| --- a/internal/host/changeindex.go |
| +++ b/internal/host/changeindex.go |
| @@ -193,16 +193,21 @@ func recordViewBackstop(ctx context.Context, v *provision.RecordView, due *atomi |
| // Three start times cover every departure observed before those rounds began. |
| // Keeping only those times bounds memory even when another path abandons or |
| // acknowledges a departure. A new controller does not reset the process budget. |
| +// A request inside the 60 s spacing is kept and started when the spacing ends |
| +// (DR-5), so departure evidence arriving just after a round still gets one; |
| +// the spacing and the three-round limit are unchanged. |
| type inventoryNudger struct { |
| mu sync.Mutex |
| wake chan struct{} |
| now func() time.Time |
| + after func(time.Duration, func()) |
| starts [3]time.Time |
| pending time.Time |
| + armed bool |
| } |
| func newInventoryNudger(now func() time.Time) *inventoryNudger { |
| - return &inventoryNudger{wake: make(chan struct{}, 1), now: now} |
| + return &inventoryNudger{wake: make(chan struct{}, 1), now: now, after: func(d time.Duration, f func()) { time.AfterFunc(d, f) }} |
| } |
| var departureInventoryNudges = newInventoryNudger(time.Now) |
| @@ -211,19 +216,48 @@ func (n *inventoryNudger) eligible(observed, now time.Time) bool { |
| return now.After(observed) && !n.starts[0].After(observed) && (n.starts[2].IsZero() || now.Sub(n.starts[2]) >= time.Minute) |
| } |
| +// spaced reports a request refused only by the 60 s spacing. |
| +func (n *inventoryNudger) spaced(observed, now time.Time) bool { |
| + return now.After(observed) && !n.starts[0].After(observed) && !n.starts[2].IsZero() && now.Sub(n.starts[2]) < time.Minute |
| +} |
| + |
| +func (n *inventoryNudger) signal() { |
| + select { |
| + case n.wake <- struct{}{}: |
| + default: |
| + } |
| +} |
| + |
| +// deferLocked arms one timer for the end of the spacing. Callers hold mu. |
| +func (n *inventoryNudger) deferLocked(now time.Time) { |
| + if n.armed { |
| + return |
| + } |
| + n.armed = true |
| + n.after(n.starts[2].Add(time.Minute).Sub(now), func() { |
| + n.mu.Lock() |
| + n.armed = false |
| + n.mu.Unlock() |
| + n.signal() |
| + }) |
| +} |
| + |
| func (n *inventoryNudger) request(observed time.Time) { |
| n.mu.Lock() |
| defer n.mu.Unlock() |
| - if !n.eligible(observed, n.now()) { |
| + now := n.now() |
| + eligible := n.eligible(observed, now) |
| + if !eligible && !n.spaced(observed, now) { |
| return |
| } |
| if observed.After(n.pending) { |
| n.pending = observed |
| } |
| - select { |
| - case n.wake <- struct{}{}: |
| - default: |
| + if eligible { |
| + n.signal() |
| + return |
| } |
| + n.deferLocked(now) |
| } |
| func (n *inventoryNudger) begin() bool { |
| @@ -231,10 +265,18 @@ func (n *inventoryNudger) begin() bool { |
| defer n.mu.Unlock() |
| now := n.now() |
| observed := n.pending |
| - n.pending = time.Time{} |
| - if observed.IsZero() || !n.eligible(observed, now) { |
| + if observed.IsZero() { |
| return false |
| } |
| + if !n.eligible(observed, now) { |
| + if n.spaced(observed, now) { |
| + n.deferLocked(now) |
| + return false |
| + } |
| + n.pending = time.Time{} |
| + return false |
| + } |
| + n.pending = time.Time{} |
| n.starts[0], n.starts[1], n.starts[2] = n.starts[1], n.starts[2], now |
| return true |
| } |
diff --git a/internal/host/changeindex_nudger_dr5_test.go b/internal/host/changeindex_nudger_dr5_test.go| new file mode 100644 |
| index 000000000..8a18c4423 |
| --- /dev/null |
| +++ b/internal/host/changeindex_nudger_dr5_test.go |
| @@ -0,0 +1,68 @@ |
| +package host |
| + |
| +import ( |
| + "testing" |
| + "time" |
| +) |
| + |
| +// DR-5: a request inside the 60 s spacing is deferred, not dropped; the |
| +// spacing and the three-round limit still hold. |
| +func TestInventoryNudgerDefersSpacedRequest(t *testing.T) { |
| + now := time.Unix(1_000_000, 0) |
| + n := newInventoryNudger(func() time.Time { return now }) |
| + var due time.Time |
| + var fire func() |
| + n.after = func(d time.Duration, f func()) { due, fire = now.Add(d), f } |
| + drain := func() bool { |
| + select { |
| + case <-n.wake: |
| + return true |
| + default: |
| + return false |
| + } |
| + } |
| + obs1 := now.Add(-time.Second) |
| + n.request(obs1) |
| + if !drain() || !n.begin() { |
| + t.Fatal("first request did not start a round") |
| + } |
| + round1 := now |
| + now = now.Add(30 * time.Second) |
| + obs2 := now.Add(-time.Millisecond) |
| + n.request(obs2) |
| + if drain() { |
| + t.Fatal("spacing ignored") |
| + } |
| + if fire == nil || !due.Equal(round1.Add(time.Minute)) { |
| + t.Fatalf("not deferred to the end of the spacing: due=%v", due) |
| + } |
| + now = now.Add(10 * time.Second) |
| + n.signal() // an early wake inside the spacing keeps the request |
| + if !drain() || n.begin() { |
| + t.Fatal("round started inside the spacing") |
| + } |
| + now = due |
| + f := fire |
| + fire = nil |
| + f() |
| + if !drain() || !n.begin() { |
| + t.Fatal("deferred request did not start a round at the end of the spacing") |
| + } |
| + if !n.starts[2].Equal(due) { |
| + t.Fatalf("round start %v, want %v", n.starts[2], due) |
| + } |
| + // Three rounds have started after obs2: a later request for it is dropped. |
| + for range 2 { |
| + now = now.Add(time.Minute) |
| + n.request(now.Add(-time.Millisecond)) |
| + if !drain() || !n.begin() { |
| + t.Fatal("eligible request refused") |
| + } |
| + } |
| + now = now.Add(10 * time.Second) |
| + fire = nil |
| + n.request(obs2) |
| + if drain() || fire != nil { |
| + t.Fatal("evidence past three rounds requested again") |
| + } |
| +} |
diff --git a/internal/host/hadepartures.go b/internal/host/hadepartures.go| index 61f539664..9bcce556f 100644 |
| --- a/internal/host/hadepartures.go |
| +++ b/internal/host/hadepartures.go |
| @@ -24,6 +24,9 @@ import ( |
| var errDepartureScope = errors.New("ha_departure_scope_invalid") |
| +// departuresPerStep bounds the scan passes one step runs (DR-5). |
| +const departuresPerStep = 8 |
| + |
| type LocalPolicy struct { |
| Scope hadeparture.Scope |
| Pools []string |
| @@ -474,8 +477,28 @@ func (c *Controller) step(ctx context.Context) error { |
| } |
| } |
| if c.cfg.NewReader != nil { |
| - _, err := c.ScanPass(ctx) |
| - return err |
| + // DR-5: scan every due departure in this step (at most |
| + // departuresPerStep), so departures never take turns across steps. |
| + // Each pass reserves its departure first, so the loop advances. |
| + // One departure's error does not hold the others. A pass that |
| + // reserved its departure (even one that then waits, say for |
| + // inventory) moves its next attempt; a pass that did not reserve |
| + // (not admitted) leaves the same row due, and the loop stops. |
| + var errs error |
| + var last registry.HADeparture |
| + for i := range departuresPerStep { |
| + due, err := c.cfg.Registry.PendingDepartures(ctx, c.now(), 1) |
| + if err != nil || len(due) == 0 || ctx.Err() != nil { |
| + return errors.Join(errs, err) |
| + } |
| + if i > 0 && due[0].ID == last.ID && due[0].NextAttempt.Equal(last.NextAttempt) { |
| + break |
| + } |
| + last = due[0] |
| + _, err = c.ScanPass(ctx) |
| + errs = errors.Join(errs, err) |
| + } |
| + return errs |
| } |
| pending, err := c.cfg.Registry.PendingDepartures(ctx, c.now(), 1) |
| if err != nil { |
diff --git a/internal/host/hadepartures_dr5_test.go b/internal/host/hadepartures_dr5_test.go| new file mode 100644 |
| index 000000000..332589dc8 |
| --- /dev/null |
| +++ b/internal/host/hadepartures_dr5_test.go |
| @@ -0,0 +1,777 @@ |
| +package host |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/service/route53" |
| + r53types "github.com/aws/aws-sdk-go-v2/service/route53/types" |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/boxid" |
| + "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" |
| + "github.com/carlosframework/platform/internal/steering" |
| +) |
| + |
| +// dr5Rig is dev rehearsal N6 (2026-11-08) on the production wiring of |
| +// newG3Departure: the whole group (members A and B) is terminated and both |
| +// departures are enrolled at T. Self is a fixed box with no named pools. |
| +// A was the last releaser of the pool "ha" hosts; B released the one |
| +// shared-pool host. Inventory rounds run only when the scan requests them, |
| +// through the real inventoryNudger on the fake clock, and each walk takes |
| +// 20 s. Steps run every 30 s, and a record is rewritten every 30 s. |
| +type dr5Rig struct { |
| + *g3Departure |
| + b hadeparture.Box |
| + bID string |
| + bEdgesKey string |
| + haHosts []string |
| + locks map[string][]byte |
| + nudger *inventoryNudger |
| + deferredAt time.Time |
| + deferredFn func() |
| + walkFrom time.Time |
| + walkDone time.Time |
| + unserved int |
| + logs []string |
| + // fixedDeparture: the fixed box's own departure keeps its edges file |
| + // (never deleted automatically) and reports that on every step. |
| + fixedDeparture bool |
| + view hadeparture.DepartureView |
| +} |
| + |
| +const ( |
| + dr5Walk = 20 * time.Second |
| + dr5Bound = 3 * time.Minute |
| +) |
| + |
| +type dr5Options struct { |
| + heldUntil time.Duration // >0: the first "ha" lock is held by A until T+heldUntil |
| + livePeer string // "": none; "serves": served_pools ["ha"]; "unknown": served_pools missing |
| + incompleteView bool |
| + otherPlacement bool // A also released a pool "ha" host placed in another region |
| + fixedPeer bool // a fixed box serving "ha" whose earlier incarnation departed |
| + fillers int // shared-pool hosts with unrelated locks: forces multi-page walks |
| + haLast bool // "ha" hosts sort after the fillers (read on a walk's last page) |
| +} |
| + |
| +func newDR5Rig(t *testing.T, o dr5Options) *dr5Rig { |
| + t.Helper() |
| + x := &dr5Rig{g3Departure: newG3Departure(t, 1), locks: map[string][]byte{}} |
| + a := &x.a |
| + ctx := t.Context() |
| + x.c.cfg.Logf = func(f string, args ...any) { |
| + line := fmt.Sprintf(f, args...) |
| + x.logs = append(x.logs, line) |
| + if strings.HasPrefix(line, "ha_departure_unserved ") { |
| + x.unserved++ |
| + } |
| + } |
| + // Member B: identity, member-shaped edges file, status snapshot. |
| + x.b = hadeparture.Box{Account: a.Self.Account, InstanceID: "i-4123456789abcdef0", Scope: a.Self.Scope} |
| + x.b.Ref = groupReferenceOf(x.b.Account, x.b.InstanceID) |
| + _, raw := x.signer.Record(t, x.b.Ref, x.b.Account, x.b.Scope.CloudRegion, x.b.InstanceID) |
| + if _, err := x.store.Put(ctx, boxid.Key(x.b.Ref), raw, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + x.bEdgesKey = "control/edges/" + x.b.Ref + ".json" |
| + bTag, err := x.store.Put(ctx, x.bEdgesKey, dr5MemberEdges(x.b), "") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, ref := range []string{x.dead.Ref, x.b.Ref} { |
| + if _, err = x.store.Put(ctx, "status/boxes/"+ref+".json", []byte(`{"v":1}`), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + // Republish A's edges file in member shape (pool "ha" only, not the |
| + // shared pool), as members publish it. The scan rebinds the new ETag. |
| + if x.edgesTag, err = x.store.Put(ctx, x.edgesKey, dr5MemberEdges(x.dead), x.edgesTag); err != nil { |
| + t.Fatal(err) |
| + } |
| + obs, err := x.c.cfg.Identities.Observe(ctx, hadeparture.BoxObservation{Known: true, Box: x.b, EdgesKey: x.bEdgesKey, EdgesETag: bTag}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + x.b = obs.Box |
| + if err = x.c.Enqueue(ctx, obs); err != nil { |
| + t.Fatal(err) |
| + } |
| + x.bID = departureID(x.c.cfg.DeploymentBucket, obs.Box) |
| + // B's own termination message, with its own receipt, through the |
| + // production receive handler (A's came through the queue at start). |
| + x.queue.mu.Lock() |
| + x.queue.extra = map[string]bool{"receipt-b": true} |
| + x.queue.mu.Unlock() |
| + if err = x.c.record(ctx, hadeparture.Message{ID: "event-b", Receipt: "receipt-b", Body: terminationHint(x.b.InstanceID)}); err != nil { |
| + t.Fatal(err) |
| + } |
| + // The shared-pool host (record 0) was released by B: self adopts it. |
| + x.putMarker(t, x.records[0].Host, x.b, 3) |
| + // Pool "ha" hosts released by A, as N6 found them. |
| + n := 2 |
| + if o.otherPlacement { |
| + n = 3 |
| + } |
| + for i := range n { |
| + name := fmt.Sprintf("dr5-ha-%d.example.com", i) |
| + if o.haLast { |
| + name = fmt.Sprintf("zzz-ha-%d.example.com", i) |
| + } |
| + rec := provision.Record{Schema: 1, Account: "bab", App: "shop", Host: name, Channel: "stable", Pool: "ha", HA: true, CreatedAt: x.start.Add(-time.Hour)} |
| + if i == 2 { |
| + rec.Region = "elsewhere" |
| + } |
| + if err = provision.CreateRecord(ctx, x.store, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + x.records = append(x.records, rec) |
| + x.haHosts = append(x.haHosts, rec.Host) |
| + if i == 0 && o.heldUntil > 0 { |
| + x.putHeld(t, rec.Host, x.dead, 6, x.start.Add(o.heldUntil)) |
| + continue |
| + } |
| + x.putMarker(t, rec.Host, x.dead, int64(4+i)) |
| + } |
| + // Fillers sort after the "ha" hosts; each lock read counts toward a |
| + // pass's page, so the walks take several passes. |
| + for i := range o.fillers { |
| + rec := provision.Record{Schema: 1, Account: "bab", App: "shop", Host: fmt.Sprintf("zz-fill-%03d.example.com", i), Channel: "stable", HA: true, CreatedAt: x.start.Add(-time.Hour)} |
| + if err = provision.CreateRecord(ctx, x.store, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + x.records = append(x.records, rec) |
| + raw, _ := json.Marshal(hafresh.Lock{Generation: 1, Owner: "pid-4242", ExpiresAt: x.start.Add(time.Hour)}) |
| + x.fx.PutLock(activator.HibernatePrefix(x.a.Backend.Cfg.Prefix, rec.Host), raw) |
| + } |
| + // A churn target outside this placement, written every 30 s. |
| + churn := provision.Record{Schema: 1, Account: "bab", App: "shop", Host: "dr5-churn.example.com", Channel: "stable", Region: "elsewhere", CreatedAt: x.start.Add(-time.Hour)} |
| + if err = provision.CreateRecord(ctx, x.store, churn); err != nil { |
| + t.Fatal(err) |
| + } |
| + x.records = append(x.records, churn) |
| + x.reconcile(t) |
| + // The departure view the edge folds from the edges files. |
| + view := hadeparture.DepartureView{Complete: !o.incompleteView, Self: hadeparture.BoxObservation{Known: true, Box: a.Self, EdgesKey: "control/edges/" + a.Self.Ref + ".json", ServedPools: hadeparture.EncodePools([]string{""}), PoolsKnown: true}} |
| + for _, m := range []hadeparture.Box{x.dead, x.b} { |
| + view.Peers = append(view.Peers, hadeparture.BoxObservation{Known: true, Box: hadeparture.Box{Ref: m.Ref, Scope: m.Scope}, ServedPools: hadeparture.EncodePools([]string{"ha"}), PoolsKnown: true}) |
| + } |
| + switch o.livePeer { |
| + case "serves": |
| + view.Peers = append(view.Peers, hadeparture.BoxObservation{Known: true, Box: hadeparture.Box{Ref: x.peer.Ref, Scope: x.peer.Scope}, ServedPools: hadeparture.EncodePools([]string{"ha"}), PoolsKnown: true}) |
| + case "unknown": |
| + view.Peers = append(view.Peers, hadeparture.BoxObservation{Known: true, Box: hadeparture.Box{Ref: x.peer.Ref, Scope: x.peer.Scope}}) |
| + } |
| + if o.fixedPeer { |
| + x.fixedDeparture = true |
| + // A fixed box bound in CARLOS_HA_FIXED_BOX_IDENTITIES has a proven, |
| + // enrolled departure; its reference now publishes a replacement that |
| + // serves "ha". The old proof says nothing about the replacement. |
| + fixed := hadeparture.Box{Ref: "fixedha", InstanceID: "i-5123456789abcdef0", Account: a.Self.Account, Scope: a.Self.Scope} |
| + x.c.cfg.Identities.Fixed[fixed.Ref] = fixed.InstanceID |
| + _, rec := x.signer.Record(t, fixed.Ref, fixed.Account, fixed.Scope.CloudRegion, fixed.InstanceID) |
| + if _, e := x.store.Put(ctx, boxid.Key(fixed.Ref), rec, ""); e != nil { |
| + t.Fatal(e) |
| + } |
| + fTag, e := x.store.Put(ctx, "control/edges/"+fixed.Ref+".json", dr5MemberEdges(fixed), "") |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + fobs, e := x.c.cfg.Identities.Observe(ctx, hadeparture.BoxObservation{Known: true, Box: fixed, EdgesKey: "control/edges/" + fixed.Ref + ".json", EdgesETag: fTag}) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = x.c.Enqueue(ctx, fobs); e != nil { |
| + t.Fatal(e) |
| + } |
| + view.Peers = append(view.Peers, hadeparture.BoxObservation{Known: true, Box: hadeparture.Box{Ref: fixed.Ref, Scope: fixed.Scope}, ServedPools: hadeparture.EncodePools([]string{"ha"}), PoolsKnown: true}) |
| + } |
| + x.view = view |
| + if err = x.c.Tick(ctx, view); err != nil { |
| + t.Fatal(err) |
| + } |
| + // Inventory rounds only on request, through the production nudger. The |
| + // nudger's clock runs 1 ms ahead: in production the request follows the |
| + // observation it carries by the pass's own I/O. |
| + x.nudger = newInventoryNudger(func() time.Time { return x.now.Add(time.Millisecond) }) |
| + x.nudger.after = func(d time.Duration, f func()) { x.deferredAt, x.deferredFn = x.now.Add(d), f } |
| + x.c.cfg.RequestInventory = func(_ context.Context, observed time.Time) { x.nudger.request(observed) } |
| + for _, h := range x.haHosts { |
| + x.locks[h] = x.lockBody(t, h) |
| + } |
| + return x |
| +} |
| + |
| +func dr5MemberEdges(b hadeparture.Box) []byte { |
| + raw, _ := json.Marshal(edgesFile{V: 1, Box: b.Ref, BoxID: b.Ref, Region: b.Scope.CloudRegion, Placement: b.Scope.Placement, DataBucket: b.Scope.DataBucket, SecretsKeyFP: b.Scope.SecretsKeyFP, EIP: "192.0.2.9", ServesSharedPool: false, NamedPools: []string{"ha"}, ServedPools: edgesfile.PoolEvidence(`["ha"]`)}) |
| + return raw |
| +} |
| + |
| +func (x *dr5Rig) putMarker(t *testing.T, host string, b hadeparture.Box, gen int64) { |
| + t.Helper() |
| + rec := x.record(t, host) |
| + entry, _ := provision.LifetimeEntryOf(rec) |
| + raw, _ := hafresh.MarkerBody(gen, hafresh.Marker{V: 1, Box: b.Ref, IID: b.InstanceID, Lifetime: entry.ID}) |
| + x.fx.PutLock(activator.HibernatePrefix(x.a.Backend.Cfg.Prefix, host), raw) |
| +} |
| + |
| +func (x *dr5Rig) putHeld(t *testing.T, host string, b hadeparture.Box, gen int64, expiry time.Time) { |
| + t.Helper() |
| + raw, _ := json.Marshal(hafresh.Lock{Generation: gen, Owner: hafresh.OwnerFor(hafresh.Self{Ref: b.Ref, IID: b.InstanceID}, 1, true), ExpiresAt: expiry}) |
| + x.fx.PutLock(activator.HibernatePrefix(x.a.Backend.Cfg.Prefix, host), raw) |
| +} |
| + |
| +func (x *dr5Rig) record(t *testing.T, host string) provision.Record { |
| + t.Helper() |
| + for _, r := range x.records { |
| + if r.Host == host { |
| + return r |
| + } |
| + } |
| + rec, _, err := provision.FindRecordByHost(t.Context(), x.store, host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return *rec |
| +} |
| + |
| +func (x *dr5Rig) lockBody(t *testing.T, host string) []byte { |
| + t.Helper() |
| + r, err := defaultDepartureReaderFor(t, x) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + v, err := r.ReadLock(t.Context(), x.a.Self.Scope.DataBucket, activator.HibernatePrefix(x.a.Backend.Cfg.Prefix, host)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + raw, _ := json.Marshal(v.Lock) |
| + return append(raw, []byte(v.ETag)...) |
| +} |
| + |
| +func defaultDepartureReaderFor(t *testing.T, x *dr5Rig) (DepartureLockReader, error) { |
| + return x.c.cfg.NewReader(t.Context(), x.a.Self.Scope.CloudRegion) |
| +} |
| + |
| +// round is one inventory round whose walk began at from. |
| +func (x *dr5Rig) round(t *testing.T, from time.Time) { |
| + t.Helper() |
| + cfg := provision.ReconcileConfig{DataDir: x.a.Backend.DataDir, Departures: x.a.Inventory.Begin(from.String(), from, from, true), Layout: func(context.Context, release.Store) (string, error) { return release.LayoutModeNested, nil }} |
| + if err := provision.Reconcile(t.Context(), x.store, x.a.Registry, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := provision.ReconcileSidecars(t.Context(), x.store, x.a.Registry, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func (x *dr5Rig) churn(t *testing.T, n int) { |
| + t.Helper() |
| + rec := &x.records[len(x.records)-1] |
| + rec.Channel = fmt.Sprintf("churn-%d", n) |
| + key := provision.RecordKey(rec.Account, rec.App, rec.Host) |
| + _, tag, err := x.store.Get(t.Context(), key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + raw, _ := json.Marshal(rec) |
| + if _, err = x.store.Put(t.Context(), key, raw, tag); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func (x *dr5Rig) phase(t *testing.T, id string) string { |
| + t.Helper() |
| + d, err := x.a.Registry.Departure(t.Context(), id) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return d.Phase |
| +} |
| + |
| +// run drives the box for limit after T and returns each departure's |
| +// completion offset (0 = not complete). |
| +func (x *dr5Rig) run(t *testing.T, limit time.Duration, each func(at time.Duration)) (time.Duration, time.Duration) { |
| + t.Helper() |
| + var doneA, doneB time.Duration |
| + churns := 0 |
| + for x.now = x.start; !x.now.After(x.start.Add(limit)); x.now = x.now.Add(time.Second) { |
| + at := x.now.Sub(x.start) |
| + if x.deferredFn != nil && !x.now.Before(x.deferredAt) { |
| + f := x.deferredFn |
| + x.deferredFn = nil |
| + f() |
| + } |
| + select { |
| + case <-x.nudger.wake: |
| + if x.walkDone.IsZero() && x.nudger.begin() { |
| + x.walkFrom, x.walkDone = x.now, x.now.Add(dr5Walk) |
| + } |
| + default: |
| + } |
| + // Index-driven publication with churn: a regular round every 60 s, |
| + // besides the rounds the scan requests. |
| + if x.walkDone.IsZero() && at%(60*time.Second) == 40*time.Second { |
| + x.walkFrom, x.walkDone = x.now, x.now.Add(dr5Walk) |
| + } |
| + if !x.walkDone.IsZero() && !x.now.Before(x.walkDone) { |
| + x.round(t, x.walkFrom) |
| + x.walkDone = time.Time{} |
| + } |
| + if at%(30*time.Second) == 15*time.Second { |
| + churns++ |
| + x.churn(t, churns) |
| + } |
| + // Steps start just after T, the first one after enrollment. |
| + if at%(30*time.Second) == 2*time.Second { |
| + if err := x.c.step(t.Context()); err != nil && !errors.Is(err, errDeparturePending) && !(x.fixedDeparture && errors.Is(err, errDepartureIdentity)) { |
| + t.Fatalf("step at T+%s: %v", at, err) |
| + } |
| + if doneA == 0 && x.phase(t, x.id) == "complete" { |
| + doneA = at |
| + } |
| + if doneB == 0 && x.phase(t, x.bID) == "complete" { |
| + doneB = at |
| + } |
| + complete := 0 |
| + for _, d := range []time.Duration{doneA, doneB} { |
| + if d != 0 { |
| + complete++ |
| + } |
| + } |
| + x.queue.mu.Lock() |
| + ackA, ackB := x.queue.deleted[x.queue.queue], x.queue.deleted["receipt-b"] |
| + x.queue.mu.Unlock() |
| + if (ackA > 0) != (doneA != 0) || (ackB > 0) != (doneB != 0) || ackA > 1 || ackB > 1 { |
| + t.Fatalf("T+%s: acks A=%d B=%d for completions A=%s B=%s", at, ackA, ackB, doneA, doneB) |
| + } |
| + } |
| + if each != nil { |
| + each(at) |
| + } |
| + } |
| + return doneA, doneB |
| +} |
| + |
| +func (x *dr5Rig) gone(t *testing.T, key string) bool { |
| + t.Helper() |
| + _, _, err := x.store.Get(t.Context(), key) |
| + if err != nil && !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal(err) |
| + } |
| + return errors.Is(err, os.ErrNotExist) |
| +} |
| + |
| +func (x *dr5Rig) assertUntouched(t *testing.T) { |
| + t.Helper() |
| + for _, h := range x.haHosts[:min(2, len(x.haHosts))] { |
| + if got := x.lockBody(t, h); !bytes.Equal(got, x.locks[h]) { |
| + t.Fatalf("lock of %s changed:\n%s\n%s", h, x.locks[h], got) |
| + } |
| + rec := x.record(t, h) |
| + entry, _ := provision.LifetimeEntryOf(rec) |
| + for _, id := range []string{x.id, x.bID} { |
| + if _, adopted, err := x.a.Registry.HAAdoption(t.Context(), h, entry.ID, id); err != nil || adopted { |
| + t.Fatalf("pool ha host %s imported (departure %s): %v", h, id, err) |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestDepartureDR5WholeGroupGone(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + o dr5Options |
| + }{ |
| + {"n6", dr5Options{}}, |
| + {"held_lock_expiry", dr5Options{heldUntil: 100 * time.Second}}, |
| + {"multipage", dr5Options{fillers: 140}}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + x := newDR5Rig(t, tc.o) |
| + // Steering as the housekeeper sees it before the departures. |
| + before := x.edgesBodies(t) |
| + r53 := &dr5Route53{} |
| + routes := []registry.Route{{Host: "shop.apps.example.com", Steering: "latency"}} |
| + if err := steering.ConvergeDeployment(t.Context(), r53, "Z1", routes, before, "apps.example.com"); err != nil { |
| + t.Fatal(err) |
| + } |
| + zone := r53.snapshot() |
| + doneA, doneB := x.run(t, 5*time.Minute, func(at time.Duration) { |
| + // The first step reobserves both departures: one waiting for |
| + // inventory does not hold the other (Astra DR-5 R1 P2). |
| + if at == 2*time.Second { |
| + for _, id := range []string{x.id, x.bID} { |
| + if d, e := x.a.Registry.Departure(t.Context(), id); e != nil || d.LastError != "inventory" { |
| + t.Fatalf("departure %s not scanned in the first step: %+v %v", id, d, e) |
| + } |
| + } |
| + } |
| + if tc.o.heldUntil > 0 && at < tc.o.heldUntil && x.phase(t, x.id) == "complete" { |
| + t.Fatalf("A finished at T+%s before its held lock expired at T+%s", at, tc.o.heldUntil) |
| + } |
| + }) |
| + t.Logf("A complete at T+%s, B complete at T+%s, unserved lines %d", doneA, doneB, x.unserved) |
| + if doneA == 0 || doneA > dr5Bound || doneB == 0 || doneB > dr5Bound { |
| + t.Fatalf("departures not finished within %s of proof: A=%s B=%s logs=%q", dr5Bound, doneA, doneB, x.logs) |
| + } |
| + for _, key := range []string{x.edgesKey, x.bEdgesKey, "status/boxes/" + x.dead.Ref + ".json", "status/boxes/" + x.b.Ref + ".json"} { |
| + if !x.gone(t, key) { |
| + t.Fatalf("%s left behind", key) |
| + } |
| + } |
| + if x.pages != 0 { |
| + t.Fatalf("paged %d times", x.pages) |
| + } |
| + if x.unserved < 2 { |
| + t.Fatalf("unserved hosts not logged: %d", x.unserved) |
| + } |
| + x.assertUntouched(t) |
| + // The shared-pool host B released was imported here. |
| + entry, _ := provision.LifetimeEntryOf(x.records[0]) |
| + if _, adopted, err := x.a.Registry.HAAdoption(t.Context(), x.records[0].Host, entry.ID, x.bID); err != nil || !adopted { |
| + t.Fatalf("shared-pool host not adopted: %v", err) |
| + } |
| + // Route 53 steering is unchanged once both members are gone. |
| + r53.changes = 0 |
| + if err := steering.ConvergeDeployment(t.Context(), r53, "Z1", routes, x.edgesBodies(t), "apps.example.com"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if r53.changes != 0 || r53.snapshot() != zone { |
| + t.Fatalf("steering changed: %d change batches\nbefore %s\nafter %s", r53.changes, zone, r53.snapshot()) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDepartureDR5StaysBlocked(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + o dr5Options |
| + }{ |
| + {"live_peer_serves_pool", dr5Options{livePeer: "serves"}}, |
| + {"peer_served_pools_missing", dr5Options{livePeer: "unknown"}}, |
| + {"incomplete_view", dr5Options{incompleteView: true}}, |
| + {"other_placement", dr5Options{otherPlacement: true}}, |
| + {"fixed_ref_replacement_serves_pool", dr5Options{fixedPeer: true}}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + x := newDR5Rig(t, tc.o) |
| + doneA, doneB := x.run(t, 5*time.Minute, nil) |
| + if doneA != 0 { |
| + t.Fatalf("A finished at T+%s with a possible adopter", doneA) |
| + } |
| + if doneB == 0 { |
| + t.Fatal("B (nothing unserved) did not finish") |
| + } |
| + if x.gone(t, x.edgesKey) || x.gone(t, "status/boxes/"+x.dead.Ref+".json") { |
| + t.Fatal("A's files retired while blocked") |
| + } |
| + if x.pages == 0 { |
| + t.Fatal("blocked departure did not page") |
| + } |
| + x.assertUntouched(t) |
| + }) |
| + } |
| +} |
| + |
| +// edgesBodies lists the edges files as the housekeeper loads them, plus |
| +// self's own (armed: shared pool, an EIP, an AWS region). |
| +func (x *dr5Rig) edgesBodies(t *testing.T) [][]byte { |
| + t.Helper() |
| + self, _ := json.Marshal(map[string]any{"v": 1, "box": x.a.Self.Ref, "eip": "192.0.2.1", "region": x.a.Self.Scope.CloudRegion, "serves_shared_pool": true}) |
| + out := [][]byte{self} |
| + for _, key := range []string{x.edgesKey, x.bEdgesKey} { |
| + raw, _, err := x.store.Get(t.Context(), key) |
| + if errors.Is(err, os.ErrNotExist) { |
| + continue |
| + } |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + out = append(out, raw) |
| + } |
| + return out |
| +} |
| + |
| +// dr5Route53 is a minimal zone: record sets keyed by name and set id, and |
| +// health checks with tags. |
| +type dr5Route53 struct { |
| + records map[string]r53types.ResourceRecordSet |
| + checks []r53types.HealthCheck |
| + tags map[string][]r53types.Tag |
| + changes int |
| +} |
| + |
| +func (f *dr5Route53) snapshot() string { |
| + keys := make([]string, 0, len(f.records)) |
| + for k, rr := range f.records { |
| + raw, _ := json.Marshal(rr) |
| + keys = append(keys, k+"="+string(raw)) |
| + } |
| + slices.Sort(keys) |
| + return strings.Join(keys, "\n") |
| +} |
| + |
| +func (f *dr5Route53) ListResourceRecordSets(context.Context, *route53.ListResourceRecordSetsInput, ...func(*route53.Options)) (*route53.ListResourceRecordSetsOutput, error) { |
| + out := &route53.ListResourceRecordSetsOutput{} |
| + keys := make([]string, 0, len(f.records)) |
| + for k := range f.records { |
| + keys = append(keys, k) |
| + } |
| + slices.Sort(keys) |
| + for _, k := range keys { |
| + out.ResourceRecordSets = append(out.ResourceRecordSets, f.records[k]) |
| + } |
| + return out, nil |
| +} |
| + |
| +func (f *dr5Route53) ChangeResourceRecordSets(_ context.Context, in *route53.ChangeResourceRecordSetsInput, _ ...func(*route53.Options)) (*route53.ChangeResourceRecordSetsOutput, error) { |
| + f.changes++ |
| + if f.records == nil { |
| + f.records = map[string]r53types.ResourceRecordSet{} |
| + } |
| + for _, c := range in.ChangeBatch.Changes { |
| + rr := *c.ResourceRecordSet |
| + key := aws.ToString(rr.Name) + "|" + string(rr.Type) + "|" + aws.ToString(rr.SetIdentifier) |
| + switch c.Action { |
| + case r53types.ChangeActionDelete: |
| + delete(f.records, key) |
| + default: |
| + f.records[key] = rr |
| + } |
| + } |
| + return &route53.ChangeResourceRecordSetsOutput{}, nil |
| +} |
| + |
| +func (f *dr5Route53) ListHealthChecks(context.Context, *route53.ListHealthChecksInput, ...func(*route53.Options)) (*route53.ListHealthChecksOutput, error) { |
| + return &route53.ListHealthChecksOutput{HealthChecks: f.checks}, nil |
| +} |
| + |
| +func (f *dr5Route53) ListTagsForResources(_ context.Context, in *route53.ListTagsForResourcesInput, _ ...func(*route53.Options)) (*route53.ListTagsForResourcesOutput, error) { |
| + out := &route53.ListTagsForResourcesOutput{} |
| + for _, id := range in.ResourceIds { |
| + out.ResourceTagSets = append(out.ResourceTagSets, r53types.ResourceTagSet{ResourceId: aws.String(id), ResourceType: in.ResourceType, Tags: f.tags[id]}) |
| + } |
| + return out, nil |
| +} |
| + |
| +func (f *dr5Route53) CreateHealthCheck(_ context.Context, in *route53.CreateHealthCheckInput, _ ...func(*route53.Options)) (*route53.CreateHealthCheckOutput, error) { |
| + f.changes++ |
| + hc := r53types.HealthCheck{Id: aws.String(fmt.Sprintf("hc-%d", len(f.checks)+1)), CallerReference: in.CallerReference, HealthCheckConfig: in.HealthCheckConfig} |
| + f.checks = append(f.checks, hc) |
| + return &route53.CreateHealthCheckOutput{HealthCheck: &hc}, nil |
| +} |
| + |
| +func (f *dr5Route53) DeleteHealthCheck(_ context.Context, in *route53.DeleteHealthCheckInput, _ ...func(*route53.Options)) (*route53.DeleteHealthCheckOutput, error) { |
| + f.changes++ |
| + for i, hc := range f.checks { |
| + if aws.ToString(hc.Id) == aws.ToString(in.HealthCheckId) { |
| + f.checks = append(f.checks[:i], f.checks[i+1:]...) |
| + break |
| + } |
| + } |
| + return &route53.DeleteHealthCheckOutput{}, nil |
| +} |
| + |
| +func (f *dr5Route53) ChangeTagsForResource(_ context.Context, in *route53.ChangeTagsForResourceInput, _ ...func(*route53.Options)) (*route53.ChangeTagsForResourceOutput, error) { |
| + f.changes++ |
| + if f.tags == nil { |
| + f.tags = map[string][]r53types.Tag{} |
| + } |
| + f.tags[aws.ToString(in.ResourceId)] = append(f.tags[aws.ToString(in.ResourceId)], in.AddTags...) |
| + return &route53.ChangeTagsForResourceOutput{}, nil |
| +} |
| + |
| +// A lock that changes during A's rescan, after its host was recorded |
| +// unserved and before the rescan reads it again: an advancing successor |
| +// supersedes it as today; a non-advancing rewrite keeps the departure |
| +// blocked (Astra DR-5 R2/R3 P2). |
| +func TestDepartureDR5SuccessorDuringRescan(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + gen int64 |
| + advance bool |
| + }{ |
| + {"advancing_successor", 9, true}, |
| + {"same_generation", 5, false}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + // Fillers fill the first page; the "ha" hosts are read on the |
| + // last page of each walk. |
| + x := newDR5Rig(t, dr5Options{fillers: 140, haLast: true}) |
| + host := x.haHosts[1] |
| + changed := false |
| + doneA, doneB := x.run(t, 5*time.Minute, func(at time.Duration) { |
| + if changed { |
| + return |
| + } |
| + scan, e := x.a.Registry.DepartureScan(t.Context(), x.id) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + _, visited := scan.Visited[host] |
| + if !scan.Rescan || len(scan.Visited) == 0 || visited || x.phase(t, x.id) != "scanning" { |
| + return |
| + } |
| + if scan.Hosts[host].Result != departureUnserved { |
| + t.Fatalf("rescan began without the host recorded unserved: %+v", scan.Hosts[host]) |
| + } |
| + x.putHeld(t, host, x.peer, tc.gen, x.now.Add(time.Hour)) |
| + changed = true |
| + }) |
| + if !changed { |
| + t.Fatal("never observed the rescan between pages before the host's read") |
| + } |
| + if doneB == 0 { |
| + t.Fatal("B did not finish") |
| + } |
| + if tc.advance { |
| + if doneA == 0 || doneA > dr5Bound { |
| + t.Fatalf("A not finished within %s after a valid successor: %s", dr5Bound, doneA) |
| + } |
| + scan, e := x.a.Registry.DepartureScan(t.Context(), x.id) |
| + if e != nil || scan.Hosts[host].Result != "superseded" { |
| + t.Fatalf("successor not recorded: %+v %v", scan.Hosts[host], e) |
| + } |
| + return |
| + } |
| + if doneA != 0 { |
| + t.Fatalf("A finished at T+%s after a non-advancing rewrite", doneA) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// dr5HookedStore runs hook once on the first Get of key: here, the |
| +// finalize's edges read, the last remote step before the gate. |
| +type dr5HookedStore struct { |
| + release.Store |
| + key string |
| + hook func() |
| +} |
| + |
| +func (s *dr5HookedStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if key == s.key && s.hook != nil { |
| + h := s.hook |
| + s.hook = nil |
| + h() |
| + } |
| + return s.Store.Get(ctx, key) |
| +} |
| +func (s *dr5HookedStore) DeleteRevision(ctx context.Context, key, etag string) error { |
| + return s.Store.(release.IndexedDeleter).DeleteRevision(ctx, key, etag) |
| +} |
| +func (s *dr5HookedStore) IndexDeletion(ctx context.Context, key string) error { |
| + return s.Store.(release.IndexedDeleter).IndexDeletion(ctx, key) |
| +} |
| + |
| +// The finalization gate sits after the finalize's edges read: a pool |
| +// server the view gains while that read is in flight keeps A blocked |
| +// (8a3d302 option A). Moving the gate earlier fails this test. |
| +func TestDepartureDR5GateAfterEdgesRead(t *testing.T) { |
| + x := newDR5Rig(t, dr5Options{}) |
| + fired := false |
| + hooked := &dr5HookedStore{Store: x.store, key: x.edgesKey, hook: func() { |
| + v := x.view |
| + v.Peers = append(slices.Clone(v.Peers), hadeparture.BoxObservation{Known: true, Box: hadeparture.Box{Ref: x.peer.Ref, Scope: x.peer.Scope}, ServedPools: hadeparture.EncodePools([]string{"ha"}), PoolsKnown: true}) |
| + if e := x.c.Tick(t.Context(), v); e != nil { |
| + t.Fatal(e) |
| + } |
| + fired = true |
| + }} |
| + x.c.cfg.OpenStore = func(context.Context) (release.Store, error) { return hooked, nil } |
| + doneA, doneB := x.run(t, 5*time.Minute, nil) |
| + if !fired { |
| + t.Fatal("the finalize never read A's edges file") |
| + } |
| + if doneA != 0 || x.gone(t, x.edgesKey) { |
| + t.Fatalf("A finished at T+%s although a pool server appeared before the delete", doneA) |
| + } |
| + if doneB == 0 { |
| + t.Fatal("B did not finish") |
| + } |
| + if !slices.ContainsFunc(x.logs, func(l string) bool { return strings.HasPrefix(l, "ha_departure_unserved_revoked ") }) { |
| + t.Fatal("gate did not log the revocation") |
| + } |
| + x.assertUntouched(t) |
| +} |
| + |
| +// A fixed departing reference is never proof that its pool lost a server: |
| +// a replacement may publish under it (Astra DR-5 R1 P1). |
| +func TestDepartureDR5FixedRefsNeverProven(t *testing.T) { |
| + x := newDR5Rig(t, dr5Options{}) |
| + memo := map[string]bool{} |
| + fixed := registry.HADeparture{Departure: hadeparture.Departure{Box: hadeparture.Box{Ref: "fixedha", InstanceID: "i-5123456789abcdef0", Account: x.a.Self.Account, Scope: x.a.Self.Scope}}} |
| + if x.c.provenDeparted(t.Context(), fixed, "fixedha", memo) { |
| + t.Fatal("fixed departing reference counted as proven") |
| + } |
| + group := x.row(t) |
| + if !x.c.provenDeparted(t.Context(), group, x.dead.Ref, map[string]bool{}) { |
| + t.Fatal("departing group reference not proven") |
| + } |
| + if !x.c.provenDeparted(t.Context(), group, x.b.Ref, map[string]bool{}) { |
| + t.Fatal("enrolled group peer not proven") |
| + } |
| + if x.c.provenDeparted(t.Context(), group, x.peer.Ref, map[string]bool{}) { |
| + t.Fatal("live group peer counted as proven") |
| + } |
| +} |
| + |
| +// A server of the pool appears after a host was recorded unserved but |
| +// before the rescan's last page: completion must not use the stale |
| +// discharge (Astra DR-5 R2 P1). |
| +func TestDepartureDR5ServerAppearsBetweenRescanPages(t *testing.T) { |
| + x := newDR5Rig(t, dr5Options{fillers: 140}) |
| + added := false |
| + addedAt := time.Duration(0) |
| + doneA, doneB := x.run(t, 5*time.Minute, func(at time.Duration) { |
| + if added { |
| + return |
| + } |
| + scan, e := x.a.Registry.DepartureScan(t.Context(), x.id) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + _, visited := scan.Visited[x.haHosts[1]] |
| + if !scan.Rescan || !visited || scan.Hosts[x.haHosts[1]].Result != departureUnserved || x.phase(t, x.id) != "scanning" { |
| + return |
| + } |
| + if len(scan.Visited) >= len(x.records) { |
| + t.Fatalf("rescan fit in one page (%d visits); the fixture needs more fillers", len(scan.Visited)) |
| + } |
| + v := x.view |
| + v.Peers = append(slices.Clone(v.Peers), hadeparture.BoxObservation{Known: true, Box: hadeparture.Box{Ref: x.peer.Ref, Scope: x.peer.Scope}, ServedPools: hadeparture.EncodePools([]string{"ha"}), PoolsKnown: true}) |
| + if e = x.c.Tick(t.Context(), v); e != nil { |
| + t.Fatal(e) |
| + } |
| + added, addedAt = true, at |
| + }) |
| + if !added { |
| + t.Fatal("never observed a rescan between pages with the host unserved") |
| + } |
| + t.Logf("peer added at T+%s; A done %s; B done %s", addedAt, doneA, doneB) |
| + if doneA != 0 { |
| + t.Fatalf("A finished at T+%s on a stale unserved discharge", doneA) |
| + } |
| + if x.gone(t, x.edgesKey) { |
| + t.Fatal("A's edges file deleted") |
| + } |
| + if doneB == 0 { |
| + t.Fatal("B did not finish") |
| + } |
| + x.assertUntouched(t) |
| +} |
diff --git a/internal/host/hadepartures_g3_test.go b/internal/host/hadepartures_g3_test.go| index 25f9ec272..e77d11a71 100644 |
| --- a/internal/host/hadepartures_g3_test.go |
| +++ b/internal/host/hadepartures_g3_test.go |
| @@ -621,14 +621,24 @@ func TestDepartureG3EdgesRebindRefusals(t *testing.T) { |
| t.Fatal(e) |
| } |
| x.now = x.expiry.Add(30 * time.Second) |
| - if e = x.c.step(t.Context()); e != nil { |
| - t.Fatal(e) |
| - } |
| - x.now = x.now.Add(30 * time.Second) |
| + // DR-5: the adoption pass, the rescan and the finalize run in one |
| + // step. step itself needs identities, so the unbound case drives |
| + // the same passes through ScanPass. |
| if mode == "unbound" { |
| + // step needs identities; drive the same passes through |
| + // ScanPass, with the confirmer's hook (which resolves |
| + // identities) detached. |
| x.c.cfg.Identities = nil |
| + x.a.Confirmer.OnConfirmed = nil |
| + for range 3 { |
| + if _, e = x.c.ScanPass(t.Context()); e != nil { |
| + break |
| + } |
| + } |
| + } else { |
| + e = x.c.step(t.Context()) |
| } |
| - if _, e = x.c.ScanPass(t.Context()); !errors.Is(e, errDepartureIdentity) { |
| + if !errors.Is(e, errDepartureIdentity) { |
| t.Fatalf("unsafe rebind: %v", e) |
| } |
| if _, current, e := x.store.Get(t.Context(), x.edgesKey); e != nil || current != tag { |
| @@ -655,10 +665,9 @@ func TestDepartureG3LateEdges(t *testing.T) { |
| entry, _ := provision.LifetimeEntryOf(x.records[0]) |
| raw, _ := hafresh.MarkerBody(5, hafresh.Marker{V: 1, Box: x.dead.Ref, IID: x.dead.InstanceID, Lifetime: entry.ID}) |
| x.fx.PutLock("instances/"+x.records[0].Host, raw) |
| - if e = x.c.step(t.Context()); e != nil { |
| - t.Fatal(e) |
| - } |
| - x.now = x.now.Add(30 * time.Second) |
| + // DR-5: a released host finishes in the first step, so the late |
| + // publication lands after enrollment and before that step. |
| + x.now = x.now.Add(time.Millisecond) |
| x.writeEdges(t) |
| if e = x.c.step(t.Context()); e != nil { |
| t.Fatal("late publication stuck", e) |
diff --git a/internal/host/hadepartures_production_test.go b/internal/host/hadepartures_production_test.go| index 27bac03ae..ea269f308 100644 |
| --- a/internal/host/hadepartures_production_test.go |
| +++ b/internal/host/hadepartures_production_test.go |
| @@ -35,6 +35,9 @@ type departureSQSTransport struct { |
| attrs, receives, deletes int |
| ready chan struct{} |
| redeliver bool |
| + // extra receipts accepted by DeleteMessage, and deletes per receipt. |
| + extra map[string]bool |
| + deleted map[string]int |
| } |
| func (q *departureSQSTransport) Do(r *http.Request) (*http.Response, error) { |
| @@ -67,10 +70,15 @@ func (q *departureSQSTransport) Do(r *http.Request) (*http.Response, error) { |
| return nil, r.Context().Err() |
| } |
| case "AmazonSQS.DeleteMessage": |
| - if in["ReceiptHandle"] != q.queue { |
| + handle, _ := in["ReceiptHandle"].(string) |
| + if handle != q.queue && !q.extra[handle] { |
| return nil, fmt.Errorf("wrong_queue_receipt") |
| } |
| q.deletes++ |
| + if q.deleted == nil { |
| + q.deleted = map[string]int{} |
| + } |
| + q.deleted[handle]++ |
| default: |
| return nil, fmt.Errorf("unexpected_queue_request") |
| } |
diff --git a/internal/host/hadepartures_scan.go b/internal/host/hadepartures_scan.go| index b9302e3ab..47b3141a2 100644 |
| --- a/internal/host/hadepartures_scan.go |
| +++ b/internal/host/hadepartures_scan.go |
| @@ -168,6 +168,7 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) { |
| limit = 128 |
| } |
| blockers := []provision.DepartureHost{} |
| + departed := map[string]bool{} |
| count := 0 |
| for _, h := range inv.Records { |
| digest := scanDigest(h) |
| @@ -291,10 +292,15 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) { |
| old.Result = "pending" |
| old.NotBefore = time.Time{} |
| s.Hosts[h.Host] = old |
| + unserved := false |
| if !CanAdopt(h, c.cfg.Policy()) || !h.HA { |
| - block() |
| - blockers = append(blockers, h) |
| - continue |
| + // DR-5 (spec §7.5): a host no surviving box could adopt does not |
| + // hold the departure. It is neither imported nor touched. |
| + if unserved = c.unserved(ctx, d, h, departed); !unserved { |
| + block() |
| + blockers = append(blockers, h) |
| + continue |
| + } |
| } |
| if v.Lock.Release == nil && !readStarted.After(v.Lock.ExpiresAt) { |
| old.NotBefore = v.Lock.ExpiresAt |
| @@ -302,6 +308,12 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) { |
| wait(old.NotBefore) |
| continue |
| } |
| + if unserved { |
| + old.Result = departureUnserved |
| + s.Hosts[h.Host] = old |
| + c.logf("ha_departure_unserved departure=%s box=%s host=%s pool=%q generation=%d", d.ID, d.Box.Ref, h.Host, h.Pool, v.Lock.Generation) |
| + continue |
| + } |
| if s.Rescan { |
| block() |
| continue |
| @@ -351,6 +363,10 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) { |
| } |
| // A clean adoption pass is followed by an independent full lock walk. |
| s.Rescan = s.Unresolved == 0 && s.Waiting == 0 |
| + if s.Rescan { |
| + // DR-5: the independent rescan is due at once, not a step later. |
| + next = c.now() |
| + } |
| s.Cursor = 0 |
| s.Unresolved = 0 |
| s.Waiting = 0 |
| @@ -369,6 +385,94 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) { |
| return true, c.retryScanAt(ctx, d, blockers, "scan", blocked, next) |
| } |
| +// departureUnserved marks a host discharged under spec §7.5: no box that |
| +// could adopt it remains, so the departure finishes without an import. |
| +const departureUnserved = "unserved" |
| + |
| +// unserved applies spec §7.5 rules 2 and 3 (rule 1, the release marker or |
| +// the passed expiry, is the scan's own wait). It reads only this box's |
| +// departure view and local journal: no S3 request. departed memoizes the |
| +// proven-departure answer per reference for one pass. |
| +func (c *Controller) unserved(ctx context.Context, d registry.HADeparture, h provision.DepartureHost, departed map[string]bool) bool { |
| + p := c.cfg.Policy() |
| + if !h.HA || p.Denied { |
| + return false |
| + } |
| + // Rule 2: this box would adopt the host if it served the host's pool. |
| + p.Pools = []string{h.Pool} |
| + if !CanAdopt(h, p) { |
| + return false |
| + } |
| + c.mu.Lock() |
| + v := c.view |
| + c.mu.Unlock() |
| + if !v.Complete || !v.Self.Known || v.Self.Box.Ref != c.cfg.Self.Ref { |
| + return false |
| + } |
| + // Rule 3: every other box in scope is a known non-server or proven gone. |
| + for _, o := range v.Peers { |
| + if o.Box.Ref == c.cfg.Self.Ref { |
| + continue |
| + } |
| + if !o.Known || o.PlacementNull { |
| + return false |
| + } |
| + if o.Box.Scope != c.cfg.Self.Scope { |
| + continue |
| + } |
| + if o.PoolsKnown && !o.Serves(h.Pool) { |
| + continue |
| + } |
| + if !c.provenDeparted(ctx, d, o.Box.Ref, departed) { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// unservedRevoked reports the first current host recorded unserved that no |
| +// longer meets spec §7.5: this box could now adopt it, or a possible server |
| +// is in view. It reads only the view, the policy and the local journal. |
| +func (c *Controller) unservedRevoked(ctx context.Context, d registry.HADeparture, s registry.HADepartureScan, inv provision.InventorySnapshot) (string, bool) { |
| + departed := map[string]bool{} |
| + for _, h := range inv.Records { |
| + if hs, ok := s.Hosts[h.Host]; !ok || hs.Result != departureUnserved || hs.Lifetime != h.Lifetime { |
| + continue |
| + } |
| + if (CanAdopt(h, c.cfg.Policy()) && h.HA) || !c.unserved(ctx, d, h, departed) { |
| + return h.Host, true |
| + } |
| + } |
| + return "", false |
| +} |
| + |
| +// provenDeparted reports a departure enrolled in this box's journal for the |
| +// box named ref. Enrollment requires termination proof. Only a group |
| +// reference qualifies: it names one account and instance forever, so its |
| +// proof covers every edges file published under it. A fixed reference is |
| +// reused by its replacement, which a proof about an earlier incarnation |
| +// says nothing about (Astra DR-5 R1 P1), so a fixed box that may serve the |
| +// pool always keeps the departure blocked. |
| +func (c *Controller) provenDeparted(ctx context.Context, d registry.HADeparture, ref string, memo map[string]bool) bool { |
| + if known, ok := memo[ref]; ok { |
| + return known |
| + } |
| + memo[ref] = false |
| + if ref == d.Box.Ref { |
| + memo[ref] = ref == groupReferenceOf(d.Box.Account, d.Box.InstanceID) |
| + return memo[ref] |
| + } |
| + o, ok, err := c.cfg.Identities.Resolve(ctx, ref, "") |
| + if err != nil || !ok || !o.Known || o.PlacementNull || o.Box.Ref != ref || ref != groupReferenceOf(o.Box.Account, o.Box.InstanceID) { |
| + return false |
| + } |
| + if _, err = c.cfg.Registry.Departure(ctx, departureID(c.cfg.DeploymentBucket, o.Box)); err != nil { |
| + return false |
| + } |
| + memo[ref] = true |
| + return true |
| +} |
| + |
| type departureLockListing struct { |
| root string |
| prefixes map[string]bool |
| @@ -629,6 +733,21 @@ func (c *Controller) complete(ctx context.Context, id string) (result error) { |
| if err = save("authority_complete"); err != nil { |
| return err |
| } |
| + // DR-5 finalization gate (spec §7.5, Astra R2/R3 P1, 8a3d302 |
| + // option A): an unserved discharge is evidence only while it |
| + // still holds. This is the one recheck, against the current view |
| + // and policy, with nothing between it and the delete but the |
| + // call itself. One that no longer holds sends the departure back |
| + // to a fresh walk before anything is deleted. A server the view |
| + // has not folded yet is the publication race §7.5 accepts. |
| + if host, revoked := c.unservedRevoked(ctx, d, s, inv); revoked { |
| + c.logf("ha_departure_unserved_revoked departure=%s box=%s host=%s", d.ID, d.Box.Ref, host) |
| + s.DeleteUncertain = false |
| + s.Rescan = false |
| + s.Visited = map[string]registry.HADepartureVisit{} |
| + delete(c.lockListings, id) |
| + return save("scanning") |
| + } |
| call, cancel := context.WithTimeout(ctx, 5*time.Second) |
| err = indexed.DeleteRevision(call, d.EdgesKey, tag) |
| cancel() |
| @@ -676,7 +795,13 @@ func (c *Controller) complete(ctx context.Context, id string) (result error) { |
| c.telemetry.mu.Lock() |
| c.telemetry.sample.Completions++ |
| c.telemetry.mu.Unlock() |
| - c.logf("Recovered duties for %d instances from box %s.", len(s.Hosts), d.Box.Ref) |
| + recovered := 0 |
| + for _, h := range s.Hosts { |
| + if h.Result != departureUnserved { |
| + recovered++ |
| + } |
| + } |
| + c.logf("Recovered duties for %d instances from box %s.", recovered, d.Box.Ref) |
| return c.ackDeparture(ctx, d) |
| } |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 4e9d2dbde..a2c022f12 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -125,3 +125,4 @@ plan14-root-reads-region-ha-graceful-terminate-t2.tsv 687cf7744aecdf8a238dcdb805 |
| plan14-root-reads-static-sweep-periodic.tsv 3dc3f6657527133a251c028772315bdd333b04c318fbbc6d90ef5047f15408ed |
| plan14-root-reads-agent-login-link.tsv e820ef22ac677cd49aa9ca3f70d6bca9dea061bce3184ca86f0a3fc98f8de0eb |
| plan14-root-reads-fix-activator-backoff-flake.tsv feba66806ddfcbdfaf369d72413bb18e75162263b6f82f117fccf1b75497986a |
| +plan14-root-reads-region-ha-dr5.tsv f19eb78c1da1475cbf8e11a3d6c394d828aa1c8f88ae24469fe8d473581b934b |
diff --git a/internal/provision/testdata/plan14-root-reads-region-ha-dr5.tsv b/internal/provision/testdata/plan14-root-reads-region-ha-dr5.tsv| new file mode 100644 |
| index 000000000..6c8e14c51 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-region-ha-dr5.tsv |
| @@ -0,0 +1,16 @@ |
| +# Census overlay region-ha-dr5, written by census-propose (#369). census-ruling-region-ha-dr5, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-region-ha-dr5.md. |
| +# 0 body, 1 sites, 3 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 4 new dispositions: 2 reads re-frozen at their disposition with the claim, 2 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| +@legacy 7f842c66968b4bde381264f9314a984c738d693f5462e631485914f2847d97d5 internal/host/hadepartures_scan.go Controller.unserved legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-dr5;basis=DR-5 spec 7.5 rules 2-3: reads the policy, the in-memory departure view, local identity bindings (Resolve) and local journal departure rows; group references only count as proven gone. No remote read, no root input from tenants. whole:HADeparture@818 e7d3be108620a819fac614b85980739d6dc6053afc7d21864f4d8c84091f0159 |
| +@legacy 5a4e715660f744d181e2d6a717bb2e47e95654d13a37a3742c4b0ab89f61975b internal/host/hadepartures_scan.go Controller.unservedRevoked legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-dr5;basis=DR-5 R2: rechecks unserved discharges before the edges delete; reads inventory records, scan Hosts, the in-memory view, policy and local journal rows via unserved(). No remote read. registry:Hosts@239,registry:Lifetime@297,registry:Result@263,whole:HADeparture@404,whole:HADepartureHostScan@241 90d33b186039e32bae766867aaedaf5c8595f631de537cf4fa93ea0c87a70c51 |
| +@legacy 64696ef227105be80a2318eafb57825f9e8f0b9763ee910f77363737f3cbe39a internal/host/hadepartures.go Controller.step legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=B3b: resolve bound same-scope identities, persist validated termination proof before enrollment, and replay bounded pending work outside consumer/fold locks. Existing regional data client and shared cache; inventory only restricts completion, never lifecycle. B3 fix r1: Describe before proof access on suspicion paths. Normalize validated legacy inbox entries in atomic transactions, process bounded per-iid pending pages, and persist hourly escalation. Delete unrelated rows only after complete applicable walks and guarded received timestamps. Acquire/completion authority unchanged. B4: Count unresolved durable hints for the globally throttled summary and call the bounded scanner outside the fold. Acknowledge unrelated hints only after complete applicable discovery; complete departure acknowledgment reads durable state. B4 fix r3: Include refused fixed-box replacements in the existing structured receiver summary, sharing its persisted hourly page claim with pending hints. Read only local refusal state and registry page state; no additional cloud request or completion authority.;rev3=census-ruling-region-ha-p3b;basis=Register admitted departure work and cancel/join it during closure before existing confirmation/import processing. Existing 23 read sites and lease/termination proofs remain; no new root input or takeover permission.;rev3=census-ruling-region-ha-g2-fixes;basis=Include identity and underlying paging errors in existing failure logs; new IID field read only, no new external read or termination authority.;rev3=census-ruling-region-ha-dr5;basis=DR-5: scans every due departure per step (at most 8), reading departure rows from the local journal (PendingDepartures) to detect progress; same ScanPass per departure, no new remote read. file:Walk@2717,registry:Body@1979,registry:IID@2554,registry:IID@2971,registry:IID@3324,registry:IID@3357,registry:IID@4038,registry:IID@4196,registry:Key@2081,registry:Key@2317,registry:LastBlocked@2872,registry:NextAttempt@5620,registry:NextAttempt@5645,registry:ReceivedAt@2300,registry:ReceivedAt@3255,whole:HADeparture@5510,whole:HADeparture@5596,whole:HADeparture@5620,whole:HADeparture@5683,whole:HADeparture@5690,whole:HADeparture@5898,whole:HADeparture@6866,whole:HADeparture@7189,whole:HAPendingTermination@2495,whole:HAPendingTermination@2912,whole:HAPendingTermination@3166,whole:HAPendingTermination@3449,whole:HAPendingTermination@3555,whole:HAPendingTermination@4114,whole:HAPendingTermination@4730,whole:HATerminationInbox@1939 277d5872fe89124b960a7957f0c2595d983f2dbdb8379c812d7df3f5be5081dd |
| +@legacy b999756cd33f81ac8295b7e438270220d42d14e8f22ed7af128d56146adba05a internal/host/hadepartures_scan.go Controller.complete legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=B4: Read the durable departure/scan and current inventory, then conditionally delete only the retained exact edges key/revision. Reread uncertain results and refuse replacement identities. Persist deletion and acknowledged index phases before complete; queue receipts stay in memory and only complete rows acknowledge. Fresh process evidence is required before authority checkpoint reuse. Fix r1/P15: ignore the old scan-level ETag override and delete only the original departure ETag. Exact-key readback retries the same tag; a changed tag is never deleted and advances only with a different verified iid under the same ref/account/scope, otherwise holds and pages. Persist permission fault episodes; route completion faults through bounded retry. No new filesystem or executable input. B4 fix r4/P18 supersedes fixed-ref deletion: only the deterministic account/iid group reference may delete its retained exact ETag. Every other ref performs an exact-key GET and stays pending unless absent or the existing verified newer-incarnation check succeeds; the live replacement file is left intact. Group revision changes stay pending. No new key or authority read. B5: Increment completion counter only after the durable complete phase; C4 ordering stays after that commit.;rev3=census-ruling-region-ha-p3b;basis=Require registered admitted work before completing a departure or acknowledging it. Existing coverage, inventory, lease and successor reads remain; closed members defer rather than clear obligations.;rev3=census-ruling-region-ha-g2r-fixes;basis=W3: drops the per-departure nudge bookkeeping (moved to a fixed-size global limiter). Completion gates, exact-ETag deletion and reads unchanged.;rev3=census-ruling-region-ha-g3-fixes;basis=Require current inventory visit coverage and re-read group edges before conditional deletion. Verify identity and scope before rebinding a changed ETag; preserve fixed-ref retention and exact-ETag deletion. Reads scan EdgesETag and coverage state; no new object key or read source.;rev3=census-ruling-region-ha-dr2;basis=DR-2: after the edges phases, calls retireStatusSnapshot, which for a deterministic account/iid group reference only does one GET of status/boxes/<ref>.json in the deployment store and a conditional delete of that exact revision (ETag). Best-effort and time-bounded (at most 5 s, always leaving 2 s of the step for the completion save; Astra R1 P2): any failure or timeout is logged and never holds completion, paging or acknowledgement. Fixed refs untouched. No filesystem, executable or new authority read; no change to the edges deletion, completion gates or ordering.;rev3=census-ruling-region-ha-dr5;basis=DR-5: one finalization gate immediately before the conditional edges delete revalidates unserved discharges (unservedRevoked: local view, policy, journal only); on failure clears DeleteUncertain and resets to a fresh walk before any delete. The completion log counts imported hosts only. No new remote read. registry:DeleteUncertain@3813,registry:DeleteUncertain@4544,registry:DeleteUncertain@4997,registry:EdgesETag@1894,registry:EdgesETag@2906,registry:Hosts@5848,registry:InventoryGeneration@1846,registry:PermissionAlerted@2426,registry:PermissionAlerted@3559,registry:PermissionAlerted@5141,registry:PermissionAlerted@5545,registry:PermissionAlerted@841,registry:PermissionAlerted@883,registry:Phase@1002,registry:Phase@1042,registry:Phase@1538,registry:Phase@262,registry:Phase@3692,registry:Phase@5259,registry:Phase@680,registry:Phase@950,registry:Phase@967,registry:Rescan@4574,registry:Result@5863,registry:Version@665,registry:Visited@4595,whole:HADeparture@2846,whole:HADeparture@315,whole:HADeparture@442,whole:HADeparture@4423,whole:HADeparture@5671,whole:HADeparture@6025,whole:HADepartureHostScan@5850,whole:HADepartureScan@1718,whole:HADepartureScan@4426,whole:HADepartureScan@643,whole:HADepartureVisit@4597 6b87823a40a3a54378a9e560498344dd4dca51121bdce723a015e586f511529e |
| +@legacy dd1911346527d92267e5256bbb43128ce7a3a001d00168ecc0d1ebe1031b7efa internal/host/hadepartures_scan.go Controller.ScanPass legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=B4: Read authoritative pre-filter inventory, exact canonical lock revisions through one page reader, local scan checkpoints and adoption receipts. Persist source identity before the sole AdoptHost importer; validate later successor identity/lifetime/generation and require a fresh full zero-match rescan. Unknown state, unsupported hosts and missing previously matched locks refuse completion. No process launch or tenancy expansion. Preserve checkpoints across walks of identical record bytes; persist the current inventory generation separately and recheck source freshness/completeness before every page and deletion. Placement changes cannot filter the lock census. Fix r1/P15: classify legacy and unrelated locks as zero only before any D match; keep strict successor checks for previously matched hosts and hold malformed HA identities. Compare read start to expiry. Resume authority-complete deletion without rescanning unchanged inventory; persist evidence and scan errors with bounded retry. B4 fix r2: Inventory-only waits request the existing hourly page only after observed evidence is older than ChangeIndexBackstop plus 10 percent. Freshness and completion gates are unchanged; no new read. B5: Route the unchanged AdoptHost callback through measured telemetry; no new authority or lock read.;rev3=census-ruling-region-ha-p3b;basis=Gate and register the existing departure scan with admission before any work. Existing registry/object reads remain, closed members do not import, and shutdown cancels/joins registered work; no new root input.;rev3=census-ruling-region-ha-g2r-fixes;basis=W3: when a departure is blocked only on inventory freshness, signals the bounded early backstop round (global 60 s spacing, three per evidence) instead of waiting for the 30 min backstop. FreshAfter/I3 gates unchanged; no walk inside the step; no new read.;rev3=census-ruling-region-ha-g3-fixes;basis=Track current record revisions across inventory publications; separate lease waits from blockers and persist Cursor as zero for rollback. Drop removed records from coverage while retaining adoption or validated-successor gates for current hosts. Use the bounded lock-prefix listing only after validating every current host prefix; preserve per-host reads for known duties and fall back to the existing 32-host scan when listing evidence is unavailable. Cache listing evidence only in this process under scanMu, invalidate it on blocked work or inventory changes, and permit 128 reads with proven listing coverage. Added reads include departure LastError, host scan state and registry Hosts; the new remote read is a bounded LIST of the configured lock prefix in the existing data bucket.;rev3=census-ruling-region-ha-dr5;basis=BASIS AMENDED by spec 7.5 (DR-5, approved by agent manager 8a3d302 for the region HA standing approval): the B4 completion gate "adoption or validated successor" becomes "adoption, validated successor, or unserved discharge". A host may be discharged unserved only when (1) its lock is a valid release marker naming the departed box or a held lock whose expiry this box read as passed, (2) this box would adopt it but for the pool (placement, HA, lifetime, kind and sidecar rules, not denied), and (3) the complete in-memory departure view shows no in-scope box that serves or may serve the pool, other than group members with a departure enrolled in this box journal (fixed refs never count as gone; unknown served_pools blocks). Every unserved discharge is rechecked at one finalization gate immediately before the conditional edges delete. An unserved host is never imported and its lock is never written, so no lease authority moves; the full zero-match rescan still runs, with unserved hosts the only allowed matches. Inputs: served_pools comes from edges files that only box roles write (already trusted by this scan for identity and by placement); a box agent that lies can at most let a departure finish without import, which it can already cause by deleting edges files with its own role. No new remote read; reads Hosts/Rescan/Result from the local journal. The rescan is due at once. registry:Cursor@2032,registry:Cursor@2122,registry:Cursor@9032,registry:Generation@2094,registry:Generation@8297,registry:Hosts@2306,registry:Hosts@2326,registry:Hosts@3329,registry:Hosts@3949,registry:Hosts@4017,registry:Hosts@6025,registry:Hosts@6412,registry:Hosts@6870,registry:Hosts@6984,registry:Hosts@7742,registry:InventoryGeneration@1913,registry:LastError@2902,registry:Lifetime@3978,registry:NotBefore@2191,registry:NotBefore@3877,registry:NotBefore@4350,registry:NotBefore@4391,registry:NotBefore@4416,registry:NotBefore@5993,registry:NotBefore@6382,registry:NotBefore@6834,registry:NotBefore@6900,registry:NotBefore@8706,registry:NotBefore@8760,registry:NotBefore@9085,registry:Observed@5564,registry:Observed@5711,registry:Observed@6265,registry:Observed@6299,registry:Phase@1448,registry:Phase@2049,registry:Phase@2384,registry:Phase@5281,registry:Phase@634,registry:Phase@689,registry:Phase@729,registry:RecordDigest@3259,registry:RecordDigest@4312,registry:RecordDigest@6322,registry:Rescan@2137,registry:Rescan@4292,registry:Rescan@5450,registry:Rescan@7164,registry:Rescan@8483,registry:Rescan@8871,registry:Rescan@8924,registry:Result@5963,registry:Result@6357,registry:Result@6950,registry:Result@7708,registry:Unresolved@2156,registry:Unresolved@3783,registry:Unresolved@7766,registry:Unresolved@8354,registry:Unresolved@8599,registry:Unresolved@8882,registry:Unresolved@9048,registry:Version@7440,registry:Visited@2073,registry:Visited@2219,registry:Visited@3234,registry:Visited@3734,registry:Visited@3810,registry:Visited@3904,registry:Visited@7793,registry:Visited@9114,registry:Waiting@2175,registry:Waiting@8614,registry:Waiting@8689,registry:Waiting@8903,registry:Waiting@9068,whole:HADeparture@1111,whole:HADeparture@1230,whole:HADeparture@1415,whole:HADeparture@1704,whole:HADeparture@2517,whole:HADeparture@2714,whole:HADeparture@2870,whole:HADeparture@3005,whole:HADeparture@350,whole:HADeparture@392,whole:HADeparture@5561,whole:HADeparture@6664,whole:HADeparture@7408,whole:HADeparture@7544,whole:HADeparture@7900,whole:HADeparture@914,whole:HADeparture@9331,whole:HADeparture@9500,whole:HADepartureHostScan@2308,whole:HADepartureHostScan@2328,whole:HADepartureHostScan@3331,whole:HADepartureHostScan@3951,whole:HADepartureHostScan@4019,whole:HADepartureHostScan@4053,whole:HADepartureHostScan@6027,whole:HADepartureHostScan@6043,whole:HADepartureHostScan@6084,whole:HADepartureHostScan@6414,whole:HADepartureHostScan@6430,whole:HADepartureHostScan@6872,whole:HADepartureHostScan@6888,whole:HADepartureHostScan@6986,whole:HADepartureHostScan@7002,whole:HADepartureHostScan@7744,whole:HADepartureHostScan@7760,whole:HADepartureScan@7345,whole:HADepartureScan@8288,whole:HADepartureScan@9265,whole:HADepartureVisit@2075,whole:HADepartureVisit@2221,whole:HADepartureVisit@3236,whole:HADepartureVisit@3736,whole:HADepartureVisit@3754,whole:HADepartureVisit@3812,whole:HADepartureVisit@3830,whole:HADepartureVisit@3906,whole:HADepartureVisit@3924,whole:HADepartureVisit@7795,whole:HADepartureVisit@7813,whole:HADepartureVisit@9116 d5e9f4748365fdb80b58221d5bdc286bd422b5d969f0d436c3107c3dbd92b415 |
| +internal/host/hadepartures_scan.go Controller.unserved legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-dr5;basis=DR-5 spec 7.5 rules 2-3: reads the policy, the in-memory departure view, local identity bindings (Resolve) and local journal departure rows; group references only count as proven gone. No remote read, no root input from tenants. whole:HADeparture@818 e7d3be108620a819fac614b85980739d6dc6053afc7d21864f4d8c84091f0159 |
| +internal/host/hadepartures_scan.go Controller.unservedRevoked legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-dr5;basis=DR-5 R2: rechecks unserved discharges before the edges delete; reads inventory records, scan Hosts, the in-memory view, policy and local journal rows via unserved(). No remote read. registry:Hosts@239,registry:Lifetime@297,registry:Result@263,whole:HADeparture@404,whole:HADepartureHostScan@241 90d33b186039e32bae766867aaedaf5c8595f631de537cf4fa93ea0c87a70c51 |
| +internal/host/hadepartures.go Controller.step legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=B3b: resolve bound same-scope identities, persist validated termination proof before enrollment, and replay bounded pending work outside consumer/fold locks. Existing regional data client and shared cache; inventory only restricts completion, never lifecycle. B3 fix r1: Describe before proof access on suspicion paths. Normalize validated legacy inbox entries in atomic transactions, process bounded per-iid pending pages, and persist hourly escalation. Delete unrelated rows only after complete applicable walks and guarded received timestamps. Acquire/completion authority unchanged. B4: Count unresolved durable hints for the globally throttled summary and call the bounded scanner outside the fold. Acknowledge unrelated hints only after complete applicable discovery; complete departure acknowledgment reads durable state. B4 fix r3: Include refused fixed-box replacements in the existing structured receiver summary, sharing its persisted hourly page claim with pending hints. Read only local refusal state and registry page state; no additional cloud request or completion authority.;rev3=census-ruling-region-ha-p3b;basis=Register admitted departure work and cancel/join it during closure before existing confirmation/import processing. Existing 23 read sites and lease/termination proofs remain; no new root input or takeover permission.;rev3=census-ruling-region-ha-g2-fixes;basis=Include identity and underlying paging errors in existing failure logs; new IID field read only, no new external read or termination authority.;rev3=census-ruling-region-ha-dr5;basis=DR-5: scans every due departure per step (at most 8), reading departure rows from the local journal (PendingDepartures) to detect progress; same ScanPass per departure, no new remote read. file:Walk@2717,registry:Body@1979,registry:IID@2554,registry:IID@2971,registry:IID@3324,registry:IID@3357,registry:IID@4038,registry:IID@4196,registry:Key@2081,registry:Key@2317,registry:LastBlocked@2872,registry:NextAttempt@5620,registry:NextAttempt@5645,registry:ReceivedAt@2300,registry:ReceivedAt@3255,whole:HADeparture@5510,whole:HADeparture@5596,whole:HADeparture@5620,whole:HADeparture@5683,whole:HADeparture@5690,whole:HADeparture@5898,whole:HADeparture@6866,whole:HADeparture@7189,whole:HAPendingTermination@2495,whole:HAPendingTermination@2912,whole:HAPendingTermination@3166,whole:HAPendingTermination@3449,whole:HAPendingTermination@3555,whole:HAPendingTermination@4114,whole:HAPendingTermination@4730,whole:HATerminationInbox@1939 277d5872fe89124b960a7957f0c2595d983f2dbdb8379c812d7df3f5be5081dd |
| +internal/host/hadepartures_scan.go Controller.complete legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=B4: Read the durable departure/scan and current inventory, then conditionally delete only the retained exact edges key/revision. Reread uncertain results and refuse replacement identities. Persist deletion and acknowledged index phases before complete; queue receipts stay in memory and only complete rows acknowledge. Fresh process evidence is required before authority checkpoint reuse. Fix r1/P15: ignore the old scan-level ETag override and delete only the original departure ETag. Exact-key readback retries the same tag; a changed tag is never deleted and advances only with a different verified iid under the same ref/account/scope, otherwise holds and pages. Persist permission fault episodes; route completion faults through bounded retry. No new filesystem or executable input. B4 fix r4/P18 supersedes fixed-ref deletion: only the deterministic account/iid group reference may delete its retained exact ETag. Every other ref performs an exact-key GET and stays pending unless absent or the existing verified newer-incarnation check succeeds; the live replacement file is left intact. Group revision changes stay pending. No new key or authority read. B5: Increment completion counter only after the durable complete phase; C4 ordering stays after that commit.;rev3=census-ruling-region-ha-p3b;basis=Require registered admitted work before completing a departure or acknowledging it. Existing coverage, inventory, lease and successor reads remain; closed members defer rather than clear obligations.;rev3=census-ruling-region-ha-g2r-fixes;basis=W3: drops the per-departure nudge bookkeeping (moved to a fixed-size global limiter). Completion gates, exact-ETag deletion and reads unchanged.;rev3=census-ruling-region-ha-g3-fixes;basis=Require current inventory visit coverage and re-read group edges before conditional deletion. Verify identity and scope before rebinding a changed ETag; preserve fixed-ref retention and exact-ETag deletion. Reads scan EdgesETag and coverage state; no new object key or read source.;rev3=census-ruling-region-ha-dr2;basis=DR-2: after the edges phases, calls retireStatusSnapshot, which for a deterministic account/iid group reference only does one GET of status/boxes/<ref>.json in the deployment store and a conditional delete of that exact revision (ETag). Best-effort and time-bounded (at most 5 s, always leaving 2 s of the step for the completion save; Astra R1 P2): any failure or timeout is logged and never holds completion, paging or acknowledgement. Fixed refs untouched. No filesystem, executable or new authority read; no change to the edges deletion, completion gates or ordering.;rev3=census-ruling-region-ha-dr5;basis=DR-5: one finalization gate immediately before the conditional edges delete revalidates unserved discharges (unservedRevoked: local view, policy, journal only); on failure clears DeleteUncertain and resets to a fresh walk before any delete. The completion log counts imported hosts only. No new remote read. registry:DeleteUncertain@3813,registry:DeleteUncertain@4544,registry:DeleteUncertain@4997,registry:EdgesETag@1894,registry:EdgesETag@2906,registry:Hosts@5848,registry:InventoryGeneration@1846,registry:PermissionAlerted@2426,registry:PermissionAlerted@3559,registry:PermissionAlerted@5141,registry:PermissionAlerted@5545,registry:PermissionAlerted@841,registry:PermissionAlerted@883,registry:Phase@1002,registry:Phase@1042,registry:Phase@1538,registry:Phase@262,registry:Phase@3692,registry:Phase@5259,registry:Phase@680,registry:Phase@950,registry:Phase@967,registry:Rescan@4574,registry:Result@5863,registry:Version@665,registry:Visited@4595,whole:HADeparture@2846,whole:HADeparture@315,whole:HADeparture@442,whole:HADeparture@4423,whole:HADeparture@5671,whole:HADeparture@6025,whole:HADepartureHostScan@5850,whole:HADepartureScan@1718,whole:HADepartureScan@4426,whole:HADepartureScan@643,whole:HADepartureVisit@4597 6b87823a40a3a54378a9e560498344dd4dca51121bdce723a015e586f511529e |
| +internal/host/hadepartures_scan.go Controller.ScanPass legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=B4: Read authoritative pre-filter inventory, exact canonical lock revisions through one page reader, local scan checkpoints and adoption receipts. Persist source identity before the sole AdoptHost importer; validate later successor identity/lifetime/generation and require a fresh full zero-match rescan. Unknown state, unsupported hosts and missing previously matched locks refuse completion. No process launch or tenancy expansion. Preserve checkpoints across walks of identical record bytes; persist the current inventory generation separately and recheck source freshness/completeness before every page and deletion. Placement changes cannot filter the lock census. Fix r1/P15: classify legacy and unrelated locks as zero only before any D match; keep strict successor checks for previously matched hosts and hold malformed HA identities. Compare read start to expiry. Resume authority-complete deletion without rescanning unchanged inventory; persist evidence and scan errors with bounded retry. B4 fix r2: Inventory-only waits request the existing hourly page only after observed evidence is older than ChangeIndexBackstop plus 10 percent. Freshness and completion gates are unchanged; no new read. B5: Route the unchanged AdoptHost callback through measured telemetry; no new authority or lock read.;rev3=census-ruling-region-ha-p3b;basis=Gate and register the existing departure scan with admission before any work. Existing registry/object reads remain, closed members do not import, and shutdown cancels/joins registered work; no new root input.;rev3=census-ruling-region-ha-g2r-fixes;basis=W3: when a departure is blocked only on inventory freshness, signals the bounded early backstop round (global 60 s spacing, three per evidence) instead of waiting for the 30 min backstop. FreshAfter/I3 gates unchanged; no walk inside the step; no new read.;rev3=census-ruling-region-ha-g3-fixes;basis=Track current record revisions across inventory publications; separate lease waits from blockers and persist Cursor as zero for rollback. Drop removed records from coverage while retaining adoption or validated-successor gates for current hosts. Use the bounded lock-prefix listing only after validating every current host prefix; preserve per-host reads for known duties and fall back to the existing 32-host scan when listing evidence is unavailable. Cache listing evidence only in this process under scanMu, invalidate it on blocked work or inventory changes, and permit 128 reads with proven listing coverage. Added reads include departure LastError, host scan state and registry Hosts; the new remote read is a bounded LIST of the configured lock prefix in the existing data bucket.;rev3=census-ruling-region-ha-dr5;basis=BASIS AMENDED by spec 7.5 (DR-5, approved by agent manager 8a3d302 for the region HA standing approval): the B4 completion gate "adoption or validated successor" becomes "adoption, validated successor, or unserved discharge". A host may be discharged unserved only when (1) its lock is a valid release marker naming the departed box or a held lock whose expiry this box read as passed, (2) this box would adopt it but for the pool (placement, HA, lifetime, kind and sidecar rules, not denied), and (3) the complete in-memory departure view shows no in-scope box that serves or may serve the pool, other than group members with a departure enrolled in this box journal (fixed refs never count as gone; unknown served_pools blocks). Every unserved discharge is rechecked at one finalization gate immediately before the conditional edges delete. An unserved host is never imported and its lock is never written, so no lease authority moves; the full zero-match rescan still runs, with unserved hosts the only allowed matches. Inputs: served_pools comes from edges files that only box roles write (already trusted by this scan for identity and by placement); a box agent that lies can at most let a departure finish without import, which it can already cause by deleting edges files with its own role. No new remote read; reads Hosts/Rescan/Result from the local journal. The rescan is due at once. registry:Cursor@2032,registry:Cursor@2122,registry:Cursor@9032,registry:Generation@2094,registry:Generation@8297,registry:Hosts@2306,registry:Hosts@2326,registry:Hosts@3329,registry:Hosts@3949,registry:Hosts@4017,registry:Hosts@6025,registry:Hosts@6412,registry:Hosts@6870,registry:Hosts@6984,registry:Hosts@7742,registry:InventoryGeneration@1913,registry:LastError@2902,registry:Lifetime@3978,registry:NotBefore@2191,registry:NotBefore@3877,registry:NotBefore@4350,registry:NotBefore@4391,registry:NotBefore@4416,registry:NotBefore@5993,registry:NotBefore@6382,registry:NotBefore@6834,registry:NotBefore@6900,registry:NotBefore@8706,registry:NotBefore@8760,registry:NotBefore@9085,registry:Observed@5564,registry:Observed@5711,registry:Observed@6265,registry:Observed@6299,registry:Phase@1448,registry:Phase@2049,registry:Phase@2384,registry:Phase@5281,registry:Phase@634,registry:Phase@689,registry:Phase@729,registry:RecordDigest@3259,registry:RecordDigest@4312,registry:RecordDigest@6322,registry:Rescan@2137,registry:Rescan@4292,registry:Rescan@5450,registry:Rescan@7164,registry:Rescan@8483,registry:Rescan@8871,registry:Rescan@8924,registry:Result@5963,registry:Result@6357,registry:Result@6950,registry:Result@7708,registry:Unresolved@2156,registry:Unresolved@3783,registry:Unresolved@7766,registry:Unresolved@8354,registry:Unresolved@8599,registry:Unresolved@8882,registry:Unresolved@9048,registry:Version@7440,registry:Visited@2073,registry:Visited@2219,registry:Visited@3234,registry:Visited@3734,registry:Visited@3810,registry:Visited@3904,registry:Visited@7793,registry:Visited@9114,registry:Waiting@2175,registry:Waiting@8614,registry:Waiting@8689,registry:Waiting@8903,registry:Waiting@9068,whole:HADeparture@1111,whole:HADeparture@1230,whole:HADeparture@1415,whole:HADeparture@1704,whole:HADeparture@2517,whole:HADeparture@2714,whole:HADeparture@2870,whole:HADeparture@3005,whole:HADeparture@350,whole:HADeparture@392,whole:HADeparture@5561,whole:HADeparture@6664,whole:HADeparture@7408,whole:HADeparture@7544,whole:HADeparture@7900,whole:HADeparture@914,whole:HADeparture@9331,whole:HADeparture@9500,whole:HADepartureHostScan@2308,whole:HADepartureHostScan@2328,whole:HADepartureHostScan@3331,whole:HADepartureHostScan@3951,whole:HADepartureHostScan@4019,whole:HADepartureHostScan@4053,whole:HADepartureHostScan@6027,whole:HADepartureHostScan@6043,whole:HADepartureHostScan@6084,whole:HADepartureHostScan@6414,whole:HADepartureHostScan@6430,whole:HADepartureHostScan@6872,whole:HADepartureHostScan@6888,whole:HADepartureHostScan@6986,whole:HADepartureHostScan@7002,whole:HADepartureHostScan@7744,whole:HADepartureHostScan@7760,whole:HADepartureScan@7345,whole:HADepartureScan@8288,whole:HADepartureScan@9265,whole:HADepartureVisit@2075,whole:HADepartureVisit@2221,whole:HADepartureVisit@3236,whole:HADepartureVisit@3736,whole:HADepartureVisit@3754,whole:HADepartureVisit@3812,whole:HADepartureVisit@3830,whole:HADepartureVisit@3906,whole:HADepartureVisit@3924,whole:HADepartureVisit@7795,whole:HADepartureVisit@7813,whole:HADepartureVisit@9116 d5e9f4748365fdb80b58221d5bdc286bd422b5d969f0d436c3107c3dbd92b415 |
| +@coverage internal/edge 606121c04922bdd826c5ecec3e2c1a34fe0d4c4972da03b21ec4522f701881eb |
| +@coverage internal/hadeparture 2ad007bad5ec3ca5b3df1c4303de384e5fe3732a2fa9c006af0f44589a9a8e17 |
| +@coverage internal/host 0216862068121257153b8dae9865cb78f67b21e7d8007163518b4895d48b50ee |