carlos / platform Public

region-ha-p1b1-takeover

Squashed from region-ha-p1b1-takeover into main.
Co-Authored-By: Paul Campbell <paul@tito.io>
claude agent, operated by paul@keymail.dev 896977ad7aed921cdec093d0e8cead30bf6fd6a3 parent 50c0cb1
40 files changed, +2,676 −91
  • docs/superpowers/notes/census-proposal-region-ha-p1b1.md +34 −0
  • docs/superpowers/plans/2026-10-27-region-ha-p1b1-takeover.md +244 −0
  • docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-BRIEF-1.md +58 −0
  • docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-BRIEF-2.md +71 −0
  • docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-BRIEF-3.md +72 −0
  • docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-R1.md +64 −0
  • docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-R2.md +53 −0
  • docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-R3.md +28 −0
  • docs/superpowers/plans/CODEX-REVIEW-BRIEF-REGION-HA-P1B1-BRANCH-1.md +51 −0
  • docs/superpowers/plans/CODEX-REVIEW-REGION-HA-P1B1-BRANCH-1.md +33 −0
  • docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md +8 −4
  • internal/activator/backend_exec.go +7 −0
  • internal/activator/harelease_test.go +2 −2
  • internal/activator/hasamebox.go +6 −5
  • internal/activator/hasecrets_test.go +4 −4
  • internal/activator/hatakeover.go +70 −0
  • internal/activator/hatakeover_test.go +170 −0
  • internal/activator/hawake.go +1 −1
  • internal/activator/hawake_test.go +2 −2
  • internal/hafresh/acquire.go +35 −5
  • internal/hafresh/acquire_test.go +72 −1
  • internal/hafresh/owner.go +9 −2
  • internal/hafresh/owner_test.go +17 −0
  • internal/host/agent.go +8 −5
  • internal/host/haself.go +32 −18
  • internal/host/haself_test.go +76 −6
  • internal/host/hatakeover.go +50 −0
  • internal/host/hatakeover_wiring_test.go +105 −0
  • internal/lease/ha.go +29 −15
  • internal/lease/ha_test.go +98 −4
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-region-ha-p1b1.tsv +18 −0
  • internal/sim/regionha/actions_test.go +157 −7
  • internal/sim/regionha/invariants_test.go +13 −0
  • internal/sim/regionha/rules_test.go +5 −0
  • internal/sim/regionha/sim_test.go +85 −0
  • internal/sim/regionha/witness_test.go +46 −0
  • internal/sim/regionha/world_test.go +151 −10
  • internal/termfence/confirm.go +228 −0
  • internal/termfence/confirm_test.go +463 −0

CI passed — run details

diff --git a/docs/superpowers/notes/census-proposal-region-ha-p1b1.md b/docs/superpowers/notes/census-proposal-region-ha-p1b1.md
new file mode 100644
index 000000000..9351d53e7
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-region-ha-p1b1.md
@@ -0,0 +1,34 @@
+# Census approval: region-ha-p1b1
+
+Ruling `census-ruling-region-ha-p1b1`. The independent reviewer approves or rejects every change below, 2 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/host/agent.go` `runAgent` | body | unchanged (6) | region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites |
+| `internal/activator/hawake.go` `ExecBackend.acquireClassified` | sites | +whole:Route | region HA P1b-1: the HA acquire's Proofs gain OwnerTerminated (b.ownerTerminated(ctx, rt)) beside SameBoxEmpty; one more whole:Route site passes the route to ownerTerminated; nothing new is read; the proof is consulted only by hafresh.DecideAcquire for another box's expired HA lock |
+
+Envelopes re-pinned: `internal/activator`, `internal/hafresh`, `internal/host`, `internal/lease`, `internal/termfence`.
+
+Removed units: the scan finds neither the declaration nor any of its sites.
+
+| unit | recorded disposition | basis | what changed |
+|---|---|---|---|
+| `internal/host/haself.go` `readInstanceID` | legacy, task accepted-legacy | accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new (region HA P1a), the agent as carlos, at RunAgent's start and its one-minute retry (haSelfNow, haSelfRetry): reads this instance's id from IMDSv2 (PUT /latest/api/token, then the identity document), each body through io.ReadAll capped at 64 KiB (the +file:ReadAll site), within 2 s; the id names the box as owner of the lease locks it writes (lease.SetSelf); IMDS answers only for this instance, no tenant or app input; root never calls it | removed: replaced by readIdentity (same reads, two more decoded fields) |
+
+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. Escalate 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. An escalation goes to the census owner as a decision.
+
+A removed unit's recorded disposition and basis are in its table above. For a removed unit or a retired envelope, confirm from the diff that the code is deleted and not moved: a read that moved shows on this card as a change to the unit that took it, and a unit moved whole shows as a new unit, a decision. Escalate if a check, refusal or validation that root relies on goes with the deleted code and its callers' changes on this card do not account for that.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/host/agent.go` `runAgent`: authority, task B,C,D,F. Basis: rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above
+- `internal/activator/hawake.go` `ExecBackend.acquireClassified`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: the acquire's classification: a legacy route (sidecar, hand-added or not an instance) takes lease.Acquire and refuses on an HA-format lock; otherwise isHA (a record read error fails the wake, never falls back to legacy); not HA takes lease.Acquire, and an HA-format lock there marks the host HA for good and continues; HA requires haContained before any lock request, then lease.AcquireHA with the same-box proof; held and refused leases map to errLeaseHeld and errLeaseRefused (leaseError); +registry:Host, +whole:Route x7
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/activator/hatakeover.go:ExecBackend.ownerTerminated`: reads +registry:Host ×2; written legacy, accepted-legacy, frozen
+- new `internal/host/haself.go:readIdentity`: reads +file:ReadAll; written legacy, accepted-legacy, frozen
+
+Seal: `f5afdacd495705841fcc8441eaefe0efb9db7056de281bb06d1714960a5575b7` → `185170fe393cb565d18a3359dee5ace12676b3e1adecb8b638199d25ceeb779f`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-region-ha-p1b1.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/plans/2026-10-27-region-ha-p1b1-takeover.md b/docs/superpowers/plans/2026-10-27-region-ha-p1b1-takeover.md
new file mode 100644
index 000000000..e27423e51
--- /dev/null
+++ b/docs/superpowers/plans/2026-10-27-region-ha-p1b1-takeover.md
@@ -0,0 +1,244 @@
+# Region HA P1b-1: takeover of a terminated box's hosts Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** A born-HA host whose box is terminated comes back on a surviving box of its pool once its lease has expired (within about 15 minutes of the death), instead of never.
+
+**Architecture:**
+- **The pure decision.** `hafresh.DecideAcquire` gains one proof, `Proofs.OwnerTerminated`, and one row: another box's **expired** lock whose instance EC2 confirms `terminated` is taken. Every other row is P1a's, unchanged.
+- **The oracle.** `termfence` gains a confirmer: one `DescribeInstances` for the owner's instance id, checked against this box's own account and region, with spec §9.2's cache (positive 24 h, negative 10 s).
+- **The wiring.** The box learns its account and region from the identity document it already reads. The activator hands the proof to `lease.AcquireHA`. Every takeover is request-driven: the first request for the host at a survivor after expiry runs the acquire.
+
+**Tech Stack:** Go 1.26, aws-sdk-go-v2 (S3 conditional writes, EC2 `DescribeInstances`), `internal/lease/leasetest`, the seeded simulation in `internal/sim/regionha`.
+
+**Spec:** `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` (rev 6.1) §9.2, §9.4's "owner confirmed terminated" row (narrowed by N-HA9), and Paul's rulings below. P1a's plan, `docs/superpowers/plans/2026-10-26-region-ha-p1a-first-slice.md`, is the base this slice changes.
+
+**Status: rev 3.1. Astra round 3 (final): READY AFTER FIXES; its one P2 (r3.1, the third box's outputs and `tofu init`) is fixed in Task 6 Step 2. Review closed.**
+
+## Rulings
+
+**N-HA8 (Paul, 2026-10-27).** P1b is cut into slices. This slice, P1b-1, is takeover on confirmed termination, request-driven. No SQS consumer, no scan, no duties. Why now: under P1a, a born-HA host on a dead box never comes back, which is worse than a legacy host.
+
+**N-HA9 (Paul, 2026-10-27, after Astra rounds 1 and 2; stopping rule 2).** A survivor takes a terminated box's lock **only once that lock has also expired**. Same-box re-take stays at expiry, exactly as in P1a. Why: an upload the dead process already sent can still land; `CompleteMultipartUpload` can run for minutes after S3 receives it (AWS API reference), and replica and manifest keys carry no ownership generation. A time margin shorter than the lease is not defensible. The 15-minute lease is the margin every legacy host's takeover and P1a's same-box recovery already rely on, so this slice adds no new timing assumption. Making either path faster needs storage fencing, its own design (follow-ups).
+
+Deferred to later slices: storage fencing, same-box re-take before expiry, forwarding (§6), duties and the scan (§7), the termination queue consumer (§9.1), deleting the dead box's edges file (§9.3 step 2), the serving latch and lifecycle hook (§10), hairpin (§12.4), roles.
+
+Task 1 writes both rulings into the spec.
+
+## Round history
+
+| Round | File | Verdict |
+|---|---|---|
+| 1 | `CODEX-PLAN-REGION-HA-P1B1-R1.md` | NOT READY: 3 P1, 2 P2 |
+| 2 | `CODEX-PLAN-REGION-HA-P1B1-R2.md` | NOT READY: 1 P1, 2 P2 |
+| 3 | `CODEX-PLAN-REGION-HA-P1B1-R3.md` | READY AFTER FIXES: 1 P2 (fixed in rev 3.1) |
+
+| Finding | Disposition in rev 3 |
+|---|---|
+| r1.1 / r2.1 P1: a dead process's already-sent upload can land after the take (fault family I1, storage writes crossing ownership generations) | **Cut by N-HA9.** The early rows (unexpired takeover, same-box before expiry) and the 60 s settle are gone. The takeover row requires expiry. |
+| r1.2 P1: a partial identity never retries | Resolved in rev 2 (r2 confirmed); kept: Task 3. |
+| r1.3 P1: an uncatchable sim rule | The rule is gone with the early same-box row. |
+| r1.4 / r2.2 P2: I5 fairness | Task 5's finalization: the visibility bound and expiry, then confirmation attempts, then fault-free wakes, independent of the mutated confirmer; a witness with no requests between termination and finalization. |
+| r1.5 P2: graceful stop | Resolved in rev 2 (r2 confirmed); kept: Task 6. |
+| r2.3 P2: no drill observation points | Task 2 logs every real describe and the first accepted evidence per instance id; Task 6 collects them from the journal. |
+
+## Global Constraints
+
+- **Termination is evidence only when** a `DescribeInstances` reply names the owner's instance id in this box's own account and region, in state exactly `terminated` (§9.2). `shutting-down`, `stopped`, `stopping`, a missing instance and an error are not evidence. Absence is never evidence.
+- **Takeover needs both:** the lock has expired by this box's clock, and the owner is confirmed terminated. An unexpired lock of another box is held, and the confirmer is not asked.
+- **Cache:** a confirmed termination is kept 24 h; a "not terminated" answer, or an error, 10 s, per instance id.
+- **Who may take over:** only a box that already serves the host's route (its pool), because the request has to reach that box's activator. No new placement rule.
+- **No proof without identity.** An HA acquire refuses when this box's reference, instance id, account or region is unknown (`lease.ErrNoSelf`). A lock without `iid=` can never be confirmed terminated or re-taken.
+- **Same-box recovery:** unchanged from P1a (expiry plus `sameBoxProven`).
+- **Restore after a takeover** is P1a's no-marker restore: the local copy is never kept (`hafresh.KeepNoMarker`).
+- **Owner format unchanged:** `box/v1;ref=<ref>;iid=<iid>;pid=<pid>;ha=1`. Account and region are not added to it.
+- **Budget:** a takeover wake is P1a's 1 GET + 1 conditional PUT, plus 1 EC2 `DescribeInstances` (no S3 cost). A wake refused on another box's expired lock adds at most one describe per 10 s per owner instance id. Non-HA hosts and unexpired locks: unchanged.
+- **IAM:** none new. The box role's inventory statement already allows `ec2:DescribeInstances` (`infra/modules/region-host/main.tf:211-235`).
+- **Cross-compile:** darwin and windows build. Nothing here is linux-only.
+- **Copy:** none. Log lines are diagnostics.
+- **Tests:** locally, touched packages only: `nice -n 19 go test <pkg> -run '<names>' -count=1`. Leave `GOCACHE` at its default.
+- **Simulation:** one 3000-seed sweep per revision, serial, `nice -n 19`, `PAR=2`.
+
+## Review Focus
+
+1. **A stopped box, not terminated** (EC2 stop, a hibernating spot instance). Its HA hosts stay down until it starts or is terminated; no survivor takes them. Task 1: `TestDecideAcquireStoppedOwnerIsNotTaken`; Task 2: `TestConfirmStatesOtherThanTerminated`.
+2. **A describe that fails** (throttling, a network error, a missing IAM grant). The host stays refused, the failure is cached 10 s, and the next request tries again. Task 2: `TestConfirmErrorIsCachedBriefly`; Task 4: `TestTakeoverDescribeFailureKeepsHostDown`.
+3. **An owner instance id from another account or region** (a copied bucket, a cross-region lock). Never evidence. Task 2: `TestConfirmRefusesOtherAccountOrRegion`.
+4. **A terminated owner whose lock has not expired yet.** Held, and no describe is made. Task 1: `TestDecideAcquireProofScope`; Task 4: `TestTakeoverWaitsForExpiry`.
+5. **A box that has not learned its full identity yet** (IMDS slow or partial at boot). Its HA wakes refuse until the retry sets it; legacy hosts are unaffected. Task 3: `TestAcquireHARefusesWithoutInstanceID`, `TestAgentRetriesAPartialIdentity`.
+
+---
+
+Tasks 1, 2 and 4 are **[own review]** (stopping rule 3): they decide when a second box may write. Task 5 is the simulation **[own review]**. Task 6 is the dev drill and needs Paul's go before anything touches dev.
+
+### Task 1: The acquire table takes a terminated owner's expired lock [own review]
+
+**Files:**
+- Modify: `internal/hafresh/acquire.go` (`Proofs`, the reason constants, `DecideAcquire`)
+- Modify: `internal/hafresh/owner.go` (`Self`, `Self.Complete`)
+- Test: `internal/hafresh/acquire_test.go`, `internal/hafresh/owner_test.go`
+- Modify: `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` (§2, §9.4, §9.6, §9.8, §19: N-HA8, N-HA9)
+
+**Interfaces:**
+- Produces:
+ - `type Self struct{ Ref, IID, Account, Region string }`. `OwnerFor` still writes only `Ref` and `IID`. Positional literals `Self{"b", "i-b"}` in tests become keyed.
+ - `func (s Self) Complete() bool`: all four fields non-empty.
+ - `type Proofs struct { SameBoxEmpty func() (bool, error); OwnerTerminated func(iid string) (bool, error) }`
+ - `const ReasonTerminated = "holder terminated"`. The existing take reason `"same box, proven empty"` becomes `const ReasonSameBox`.
+
+The table, in this order. Only the bold row is new:
+
+| Lock | Proof | Decision |
+|---|---|---|
+| absent | | create |
+| not HA-format | | refuse, leftover lock |
+| release marker | | take |
+| HA owner, unparseable | | refuse, malformed marker |
+| unexpired, any owner | | held by the owner (no proof is called) |
+| expired, owner IID is self.IID (non-empty) | SameBoxEmpty true | take, `ReasonSameBox` |
+| expired, owner IID is self.IID | missing, false or error | refuse, `ReasonSameBoxUnsure` |
+| **expired, owner IID another non-empty IID** | **OwnerTerminated(o.IID) true** | **take, `ReasonTerminated`** |
+| expired, owner IID another or empty | missing, false or error | refuse, `ReasonOtherExpired` (plus `": " + err` on an error) |
+
+`OwnerTerminated` is called only for an expired lock of another non-empty IID. `SameBoxEmpty` is called only for an expired lock of this box's IID.
+
+- [ ] **Step 1: Write the failing tests:**
+ - `TestDecideAcquireTable`: existing rows unchanged. Add: `{expired, other, terminated}` → `ActTake`; `{unexpired, other, terminated}` → `ActHeld`; `{expired, other, terminatedErr}` → `ActRefuse`; `{expired, iid-less other owner, terminated}` → `ActRefuse`.
+ - `TestDecideAcquireReasons`: the terminated take's reason is `ReasonTerminated`; an error from `OwnerTerminated` gives a reason starting `ReasonOtherExpired + ": "`.
+ - `TestDecideAcquireProofScope`: with proofs that record their calls, `OwnerTerminated` is called once with `"i-b"` for an expired lock of `i-b`, and never for an unexpired one, this box's own, or an `iid`-less owner's; `SameBoxEmpty` is never called for another box's lock.
+ - `TestDecideAcquireStoppedOwnerIsNotTaken`: `OwnerTerminated` answering false on an expired lock of `i-b` → `ActRefuse`, `ReasonOtherExpired`.
+ - `owner_test.go`, `TestSelfComplete`: each field missing in turn is incomplete; all four is complete.
+- [ ] **Step 2: Run** `nice -n 19 go test ./internal/hafresh -run 'TestDecideAcquire|TestSelfComplete' -count=1`. Expected: FAIL (undefined fields and constants).
+- [ ] **Step 3: Implement** the table in `DecideAcquire(v View, self Self, now time.Time, p Proofs) Decision`, `Self` and `Complete`. Update the doc comment's list to the table.
+- [ ] **Step 4: Run** the Step 2 command, then `nice -n 19 go build ./... && GOOS=darwin go build ./... && GOOS=windows go build ./...`. Expected: PASS and clean builds (fix positional `Self{...}` literals the build reports).
+- [ ] **Step 5: Write N-HA8 and N-HA9 into the spec:** both under §2's rulings; §9.4's row "Expired or unexpired, owner confirmed terminated" becomes "Expired, owner confirmed terminated (N-HA9)", with one sentence on why; §9.6's last bullet names storage fencing as the precondition for same-box takeover before expiry; §19's table gains a P1b-1 row above P1b; §9.8's timeline gains one line: until storage fencing, takeover also waits for the lease to expire, so the totals are up to about 15 minutes after the last renewal.
+- [ ] **Step 6: Commit** `region-ha p1b-1: the acquire table takes a terminated owner's expired lock`.
+
+### Task 2: `termfence.Confirmer`: is this instance terminated, in this box's account and region [own review]
+
+**Files:**
+- Create: `internal/termfence/confirm.go`
+- Test: `internal/termfence/confirm_test.go`
+
+**Interfaces:**
+- Consumes: `termfence.EC2`, `DescribeInstance`, `FromDescribe` (existing).
+- Produces:
+ - `func SameAccountTerminated(self boxid.Cloud, iid string, o Observation) error`: nil only when `self.Complete()`, `iid != ""`, `iid != self.InstanceID`, and `o` is `Via == ViaDescribe`, `Found`, `o.InstanceID == iid`, `o.Account == self.Account`, `o.Region == self.Region`, `o.State == "terminated"`. Every refusal wraps `ErrNotEvidence`.
+ - `type Confirmer struct { API func(ctx context.Context, region string) (EC2, error); Self func() boxid.Cloud; Now func() time.Time; Logf func(string, ...any); /* unexported cache, mutex */ }`
+ - `func (c *Confirmer) Terminated(ctx context.Context, iid string) (bool, error)`: on a cache miss, one describe through `DescribeInstance(ctx, api, boxid.Cloud{Provider: "aws", Account: self.Account, Region: self.Region, InstanceID: iid})`; true only when `SameAccountTerminated` is nil. `ErrNotEvidence` answers `(false, nil)`; any other error `(false, err)`. A true answer is cached `ConfirmPositiveTTL`; false and errors `ConfirmNegativeTTL`. `API` is called lazily, once, and its client kept. An incomplete `Self()` answers `(false, err)` with no describe.
+ - `const ConfirmPositiveTTL = 24 * time.Hour`, `ConfirmNegativeTTL = 10 * time.Second`.
+ - **Observation points (r2.3).** Every real describe logs `termfence: describe %s: %s` (the iid, then the state, `not found`, or the error). The first accepted evidence for an iid logs `termfence: %s confirmed terminated (first evidence, request %s)` once per process. A cache hit logs nothing. Nil `Logf` means `log.Printf`.
+
+- [ ] **Step 1: Write the failing tests** with the package's existing fake `EC2` (see `fence_test.go`'s describe fake), capturing `Logf`:
+ - `TestConfirmTerminatedOwner`: a reply naming `i-b`, account and region equal to self's, state `terminated` → `(true, nil)`; the request asked for `i-b` alone in self's region; one `describe` line and one `first evidence` line.
+ - `TestConfirmStatesOtherThanTerminated`: `running`, `stopped`, `stopping`, `shutting-down`, `pending` → `(false, nil)`; an empty reply (NotFound) → `(false, nil)`.
+ - `TestConfirmRefusesOtherAccountOrRegion`: the reply's `OwnerId` differs → false; self's region is `eu-west-1` and the describe is issued only there.
+ - `TestConfirmRefusesSelfAndIncompleteIdentity`: `iid == self.InstanceID` → false with no describe; `Self()` missing the account → `(false, err)` with no describe.
+ - `TestConfirmCachesPositiveForADay`: two calls 23 h apart make one describe and one `first evidence` line; a call at 24 h + 1 s makes a second describe and no second `first evidence` line.
+ - `TestConfirmErrorIsCachedBriefly`: a describe error → `(false, err)`; a call 5 s later makes no describe and answers `(false, err)` again; a call at 11 s describes again.
+ - `TestConfirmNegativeCachedTenSeconds`: `running`, then a call at 9 s makes no describe; at 11 s with `terminated` → true.
+- [ ] **Step 2: Run** `nice -n 19 go test ./internal/termfence -run 'TestConfirm' -count=1`. Expected: FAIL (undefined).
+- [ ] **Step 3: Implement** `confirm.go` with the signatures above. The cache stores the answer and the error per iid.
+- [ ] **Step 4: Run** the Step 2 command and the whole package: `nice -n 19 go test ./internal/termfence -count=1`. Expected: PASS.
+- [ ] **Step 5: Commit** `region-ha p1b-1: termfence.Confirmer, one cached describe per owner`.
+
+### Task 3: The box knows its account and region; an HA acquire refuses without the full identity
+
+**Files:**
+- Modify: `internal/host/haself.go` (`haSelfNow`, `haSelfRetry`, `readInstanceID` → `readIdentity`)
+- Modify: `internal/host/agent.go:232` (the retry starts on `!self.Complete()`)
+- Modify: `internal/lease/ha.go:66-70` (the self check in `acquireHATTL`)
+- Test: `internal/host/haself_test.go`, `internal/lease/ha_test.go`
+
+**Interfaces:**
+- Consumes: `hafresh.Self` with `Account`, `Region`, and `Self.Complete` (Task 1).
+- Produces:
+ - `func readIdentity(client *http.Client, base string) (iid, account, region string, err error)`: the same IMDSv2 token and document read, within `haIdentityRead`, decoding `instanceId`, `accountId` and `region`.
+ - `haSelfNow` fills all four fields; `haSelfRetry` sets the identity only once it is `Complete()`, and `agent.go:232` starts it whenever the startup identity is not `Complete()`. One predicate, both places (r1.2).
+ - `lease.AcquireHA` returns `ErrNoSelf` when the self is not `Complete()`. Its message becomes `"lease: this box's identity (reference, instance id, account, region) is not known yet; HA acquire refused"`.
+
+- [ ] **Step 1: Write the failing tests:**
+ - `TestHASelfNowNamesTheBox` (extend): the fake IMDS document carries `accountId` `111122223333` and `region` `eu-west-1`; `haSelfNow` returns both.
+ - `TestHASelfRetryWaitsForTheWholeIdentity`: a document with `instanceId` but no `region` does not call `set`; the next tick with all three does, once.
+ - `TestHASelfRetrySetsALateInstanceID` (update): its fake document gains `accountId` and `region`.
+ - `TestAgentRetriesAPartialIdentity`: through the production entry (the code at `agent.go:232`, extracted to a function if needed): a startup identity with `IID` but no `Region` starts the retry, and a later complete document reaches `lease.CurrentSelf()`.
+ - `TestAcquireHARefusesWithoutInstanceID`: `lease.SetSelf(hafresh.Self{Ref: "a"})`, then `AcquireHA` → `errors.Is(err, ErrNoSelf)` with zero requests on the fake store; the same with `IID` set and `Region` empty.
+- [ ] **Step 2: Run** `nice -n 19 go test ./internal/host -run 'TestHASelf|TestAgentRetriesAPartialIdentity' -count=1` and `nice -n 19 go test ./internal/lease -run 'TestAcquireHARefusesWithout' -count=1`. Expected: FAIL.
+- [ ] **Step 3: Implement** the changes. Update every `lease` and `activator` test fixture that sets an HA self with only `Ref` or `Ref` and `IID` so it carries all four (the build and `go test ./internal/lease ./internal/activator -run 'HA|SameBox' -count=1` find them).
+- [ ] **Step 4: Run** the Step 2 commands and `nice -n 19 go test ./internal/lease ./internal/activator -run 'HA|SameBox|Lease' -count=1`. Expected: PASS.
+- [ ] **Step 5: Commit** `region-ha p1b-1: the box's lease identity carries its account and region`.
+
+### Task 4: The activator hands the proof to the HA acquire; the agent wires the confirmer [own review]
+
+**Files:**
+- Modify: `internal/activator/hawake.go:317` (the `Proofs` built in `acquireClassified`)
+- Modify: `internal/activator/activator.go` (a new `ExecBackend` field next to `StartupSwept`)
+- Modify: `internal/lease/ha.go` (the acquire's log word)
+- Modify: `internal/host/agent.go:476` (the wiring)
+- Test: `internal/activator/hatakeover_test.go` (create), `internal/lease/ha_test.go`, the nearest existing agent-wiring test in `internal/host`
+
+**Interfaces:**
+- Consumes: `hafresh.Proofs.OwnerTerminated` (Task 1), `termfence.Confirmer.Terminated` (Task 2), the full `hafresh.Self` (Task 3).
+- Produces:
+ - `ExecBackend.OwnerTerminated func(ctx context.Context, iid string) (bool, error)`. Nil: no takeover (as in P1a).
+ - `func (b *ExecBackend) ownerTerminated(ctx context.Context, rt registry.Route) func(iid string) (bool, error)`: nil when the field is nil. On true it logs `activator: %s: the holder %s is terminated (EC2) and its lease expired; taking the host over`. On an error it logs at most once a minute per host (a twin of `sameBoxState.alarm`'s throttle).
+ - `lease`: the acquire's log word follows the winning round's decision: `first wake`, `clean marker`, `unclean marker`, `same-box takeover`, `holder terminated`. `classifyAndTake`'s callback keeps the last `hafresh.Decision` it saw.
+ - The agent builds one `termfence.Confirmer` with `Self` from `lease.CurrentSelf()` (as `boxid.Cloud{Provider: "aws", ...}`) and `API` building an `ec2.Client` through `rootaws.LoadDefaultConfig(ctx, awsconfig.WithRegion(region))`, and sets `eb.OwnerTerminated = confirmer.Terminated`.
+
+- [ ] **Step 1: Write the failing tests:**
+ - `hatakeover_test.go`, `TestTakeoverOfATerminatedHolder`: a fake HA lock owned by `box/v1;ref=b;iid=i-b;pid=7;ha=1`, expired; `OwnerTerminated` answers true for `i-b`. The wake acquires, the lock's new owner names this box with generation + 1, the lease log says `holder terminated`, and the wake restores (`haWake.view` has no marker; the keep reason is `no-marker`).
+ - `TestTakeoverWaitsForExpiry`: the same lock, unexpired: the wake fails with `errLeaseHeld`, `OwnerTerminated` is not called, nothing written.
+ - `TestTakeoverDescribeFailureKeepsHostDown`: expired; `OwnerTerminated` answers an error: `errLeaseRefused`, lock unchanged.
+ - `TestNoTakeoverWithoutTheOracle`: `OwnerTerminated` nil; an expired lock of `i-b` is refused, nothing written.
+ - An agent-wiring test: `eb.OwnerTerminated` is set when the agent builds the backend.
+- [ ] **Step 2: Run** `nice -n 19 go test ./internal/activator -run 'TestTakeover|TestNoTakeover' -count=1`. Expected: FAIL.
+- [ ] **Step 3: Implement** the field, `ownerTerminated`, the `Proofs` at `hawake.go:317` (`hafresh.Proofs{SameBoxEmpty: b.sameBoxEmpty(ctx, rt), OwnerTerminated: b.ownerTerminated(ctx, rt)}`), the log word and the agent wiring.
+- [ ] **Step 4: Run** the Step 2 command, then `nice -n 19 go test ./internal/activator ./internal/lease ./internal/host -run 'HA|SameBox|Takeover|Lease|AgentEntry' -count=1`, then the three `go build` targets from Task 1 Step 4. Expected: PASS and clean builds.
+- [ ] **Step 5: Commit** `region-ha p1b-1: the HA wake takes a terminated holder's host once its lease expired`.
+
+### Task 5: The simulation terminates boxes [own review]
+
+**Files:**
+- Modify: `internal/sim/regionha/world_test.go` (termination truth, the confirmer), `actions_test.go` (`terminate`, `lateUpload`, `decideAcquire`'s proofs), `invariants_test.go` (I5 after a termination), `rules_test.go` (new rules), `witness_test.go` (one witness per new rule), `sim_test.go` (the action mix, the finalization)
+- Modify: `internal/sim/regionha/expected-outcomes.txt` only if a rule is a documented miss
+
+**Interfaces:**
+- Consumes: `hafresh.DecideAcquire` with `OwnerTerminated` (Task 1). The model drives the real decision; mutations change only what the model hands it.
+- Produces:
+ - `func (w *world) terminate(b *box)`: everything `crash` does, plus every unit's processes gone (stragglers included), the box's disk and local copies gone, and the box never restarts. `w.terminated[iid]` (with its tick) is world truth, read by the oracles. EC2 visibility follows 1 to 12 ticks later (`w.visibleAt[iid]`).
+ - The confirmer, a separate model function the mutations change: true only once visible; a seeded 10 % of its calls answer an error while faults are on.
+ - **`lateUpload`:** a process that dies (crash or terminate) with a replica or manifest upload in flight lands it at a seeded tick from 0 up to `TTL - 1` ticks after its last renewal, through the existing `replicaWrite` / `manifestWrite` with the dead pid. This models P1a's and the legacy path's assumption: an upload already sent settles within the lease. The existing writer oracle fails I1 if it lands after another process took the lock.
+ - **Finalization and I5 after a termination (r1.4, r2.2):** at the end of a run, for every host whose lock names a box terminated in truth, if some live box of the host's pool exists: turn faults off; advance past the visibility bound and the lock's expiry; give each such box one confirmation attempt, then one fault-free wake attempt. Only then fail I5 if no box holds the host. The schedule reads world truth, never the confirmer, so a mutated confirmer cannot skip the check. With no eligible survivor, I5 does not apply.
+- New rules (each caught alone, each with a witness):
+ - `"takeover-unconfirmed"`: the confirmer answers true for a box that is alive or hung. Expected: I1.
+ - `"takeover-before-expiry"`: the model hands `DecideAcquire` a lock whose expiry it moved to the past, for a terminated owner. Witness: terminate with a replica upload in flight that lands at tick `TTL - 2`, a survivor's wake right after visibility. Expected: I1 (the late write after the take).
+ - `"no-takeover"`: the confirmer never answers true. Witness: terminate, no requests at all until finalization. Expected: I5.
+
+- [ ] **Step 1: Write the three witnesses** in `witness_test.go` and add the rules to `allRules`.
+- [ ] **Step 2: Run** `nice -n 19 go test ./internal/sim/regionha -run 'TestWitness' -count=1`. Expected: FAIL (the actions and rules are not modelled).
+- [ ] **Step 3: Implement** `terminate`, visibility, the confirmer, `lateUpload`, the finalization, the I5 check and the action mix (terminate at about the rate of `crash`).
+- [ ] **Step 4: Run** the witnesses, then one sweep as `mutate.sh`'s header says: `D=$(mktemp -d -p "$TMPDIR" rhasim.XXXXXX); go test -c -o "$D/regionha.test" ./internal/sim/regionha/ && RHASIM_PAR=2 nice -n 19 internal/sim/regionha/mutate.sh "$D/regionha.test" 3000; rm -r "$D"`. Expected: every rule caught alone, no EXPECTED-MISS change, the unmutated sweep clean.
+- [ ] **Step 5: Commit** `region-ha p1b-1: the simulation terminates boxes`.
+
+### Task 6: Dev drill. Needs Paul's go before anything touches dev.
+
+Release and roll by the platform release recipe in the README and the roll-order rule (dev boxes, dev console, check; flagship only after this drill passes, with `CONSOLE_HA_REGIONS` unset there). Log every step with UTC times in the session's own roll log. Collect the observation points with `journalctl -u carlos-edge --since <t> | grep -E 'termfence: |holder terminated|taking the host over|restored \('` on each survivor.
+
+- [ ] **Step 1: Pre-checks on dev.** On leo and sophie, from the agent's environment: `aws ec2 describe-instances --instance-ids <the other box's id> --region eu-west-1` answers (the role allows it). Both boxes run the new release; `agent: lease locks name this box` shows the iid. Every HA lock on dev carries `iid=`.
+- [ ] **Step 2: The third box.** In `platform-infrastructure/dev`, add `region-ie-c.tf`, a copy of `region-ie-b.tf` with `host_ie_c`, `carlos-dev-ie-c`, `carlos-dev-host-c`, and its outputs renamed `ie_c_eip` and `ie_c_instance_id` (referencing `module.host_ie_c`). Run `tofu init` (the new module) and `tofu validate`, read `tofu plan -target=module.host_ie_c`, then apply only that module (`tofu apply -target=module.host_ie_c`; a whole-root apply restarts every box). Bootstrap it as ie-b was, with `CARLOS_POOLS=hapair`, and check `hapair-a1`'s route is nested on it and its certificate is mirrored.
+- [ ] **Step 3: Stop drill.** Wake `hapair-a1` on box C (requests through C only) and write a row. Read `lock.json`: C's owner, no marker. `aws ec2 stop-instances --skip-os-shutdown` C, and read `lock.json` again: unchanged. Probe through leo and sophie every 5 s until 5 minutes past the lock's `expires_at`. Expected: held until expiry, refused after (`stopped` in the describe lines); never taken; at most one `termfence: describe` line per 10 s per box.
+- [ ] **Step 4: Takeover drill.** `aws ec2 start-instances` C and wait for its agent. Wake `hapair-a1` on C again (requests through C only), write rows w1 to w3, check `lock.json` is C's non-marker lock, then `aws ec2 terminate-instances --skip-os-shutdown` C, probing through leo and sophie every 5 s, and check `lock.json` is still C's. Expected: held until expiry; then `termfence: ... confirmed terminated (first evidence ...)`, `the holder ... is terminated (EC2) and its lease expired; taking the host over`, `HA lease acquired ... (holder terminated)`, `restored (no-marker)`; rows w1 to w3 present except at most the last second's (stream class). Record separately: the terminate call, the lock's `expires_at`, each survivor's first evidence, the take, `restored`, first 200. **Pass: no take before `expires_at`; first 200 within 1 minute after `expires_at`; no write lost before the last second.**
+- [ ] **Step 5: Clean up.** `tofu destroy -target=module.host_ie_c` and delete `region-ie-c.tf` (one commit adding, one removing, or neither pushed: say which in the log). `hapair-a1` asleep behind a clean marker. Pools on leo and sophie stay.
+- [ ] **Step 6: Report** on the branch's amadan discussion: both timelines, describe counts, and any deviation.
+
+## Census
+
+Agent-run changes only (`internal/hafresh`, `internal/termfence`, `internal/lease`, `internal/activator`, `internal/host`'s agent wiring and identity read). Expected classes: `body` and `sites`. Run `make census-card`, CLAIMS, `make census-propose`; a cross-model reviewer approves.
+
+## Spec gaps and follow-ups
+
+- **Storage fencing** (r1.1, r2.1): replica and manifest writes carry no ownership generation, so every takeover, legacy hosts' included, relies on an upload settling within the 15-minute lease. A generation-isolated layout (or publication conditional on the lock's generation) is its own design. It is the precondition for same-box re-take before expiry and for takeover before expiry. To be filed on amadan with the round 1 and 2 findings.
+- **A lock without `iid=`** written by P1a on a box that had not learned its instance id can never be taken over. Task 3 stops new ones; Task 6 Step 1 checks dev for old ones.
+- **Cross-region requests** for a taken-over host may still dial the dead box until its edges entry ages out (§9.3 step 2 is deferred). Step 4 notes whether dev sees it.
+- **Always-on workers and due wakes** of a dead box's host wait for a request (no scan in this slice).
+- **#440** items (publisher mutex, files outside the files dir, BindsTo premise) stay on #440.
diff --git a/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-BRIEF-1.md b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-BRIEF-1.md
new file mode 100644
index 000000000..b5e86c9e8
--- /dev/null
+++ b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-BRIEF-1.md
@@ -0,0 +1,58 @@
+# Review brief: Region HA P1b-1 plan (takeover and fast re-take), round 1 of 3
+
+Repo carlos/platform, branch `region-ha-p1b1-takeover`, the commit that adds this brief.
+Under review: `docs/superpowers/plans/2026-10-27-region-ha-p1b1-takeover.md`.
+Authorities: `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` (rev 6.1, MERGED) and
+`docs/superpowers/plans/2026-10-26-region-ha-p1a-first-slice.md` (P1a, MERGED as fd93024, #433 fix 80343a5),
+plus the code on this branch (main at 81db4870). Do not review against unmerged branches; if this work needs one, say so as a P1 and stop.
+
+You are an independent reviewer. Read the plan, then the code it names, and check every claim against that code.
+
+## Fixed: do not re-argue
+
+- Paul's ruling N-HA8 (in the plan): this slice is only (1) takeover on EC2-confirmed termination, request-driven,
+ and (2) same-box re-take before expiry with P1a's existing same-box proof. Forwarding, duties, scan, the SQS
+ consumer, edges-file deletion, the serving latch, hairpin and roles are deferred. Report only mechanisms in this
+ slice that fail to honour the spec's safety rules, not the absence of deferred pieces.
+- The spec's rulings §2 (N-HA1..N-HA7) and "expiry alone never lets another box acquire".
+- The drill uses a throwaway third dev box (Paul).
+
+## What to check
+
+1. **Single writer.** Can either new table row (`OwnerTerminated`, `ReasonSameBoxEarly`) let two processes write
+ one host's database, replica or files at once? In particular: an in-flight renewal or replication PUT from the
+ old process; a hung (SIGSTOP) agent while a new agent process runs; pid reuse; the activator calling acquire
+ for a host it already holds (`internal/activator/hasamebox.go`, `hawake.go:270-330`, `internal/lease/ha.go`).
+2. **Termination evidence.** Is `SameAccountTerminated` plus the cache as strict as §9.2 and
+ `internal/termfence/fence.go`'s `Verify`? Is caching an error or a negative for 10 s, and a positive for 24 h,
+ safe? Can a positive be wrong (instance id reuse is impossible on EC2; check for anything else)?
+3. **Identity.** Task 3 makes `AcquireHA` refuse without iid/account/region. Does anything on main construct
+ `hafresh.Self` or call `lease.SetSelf` in a way this breaks (console, CLI, tests, `haSelfRetry` timing)? Does
+ refusing at early boot strand a host?
+4. **The restore after takeover.** Does P1a's no-marker restore path actually run for a taken-over lock (the view
+ has a held, non-marker owner of another box), including files and the H6 trio? Cite the code.
+5. **Tests and the simulation.** Do the named tests exercise what the plan claims? Are Task 5's rules catchable by
+ the model as it is (`internal/sim/regionha`), and is the I5 extension well-defined?
+6. **The drill.** Is Task 6 runnable as written on dev (`platform-infrastructure/dev/region-ie-b.tf` uses
+ `infra/modules/region-host` from the GitHub mirror's main), and do its pass bounds follow §9.8?
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review. (The census, and review of any newly changed
+ security, root, termination or production-storage behaviour, still check the fix; see AGENTS.md, "Stopping rules".)
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the section or task, the problem, the evidence (file:line, verified), the
+failure scenario, a concrete fix and the invariant or trust boundary it breaks (that is its fault family). End with
+exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites.
diff --git a/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-BRIEF-2.md b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-BRIEF-2.md
new file mode 100644
index 000000000..72d6a8036
--- /dev/null
+++ b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-BRIEF-2.md
@@ -0,0 +1,71 @@
+# Review brief: Region HA P1b-1 plan (takeover and fast re-take), round 2 of 3
+
+Repo carlos/platform, branch `region-ha-p1b1-takeover`, the commit that adds this brief (rev 2).
+Under review: `docs/superpowers/plans/2026-10-27-region-ha-p1b1-takeover.md`.
+Authorities: `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` (rev 6.1, MERGED) and
+`docs/superpowers/plans/2026-10-26-region-ha-p1a-first-slice.md` (P1a, MERGED as fd93024, #433 fix 80343a5),
+plus the code on this branch (main at 81db4870). Do not review against unmerged branches; if this work needs one, say so as a P1 and stop.
+
+You are an independent reviewer. Read the plan, then the code it names, and check every claim against that code.
+
+## Fixed: do not re-argue
+
+- Paul's ruling N-HA8 (in the plan): this slice is only (1) takeover on EC2-confirmed termination, request-driven,
+ and (2) same-box re-take before expiry with P1a's existing same-box proof. Forwarding, duties, scan, the SQS
+ consumer, edges-file deletion, the serving latch, hairpin and roles are deferred. Report only mechanisms in this
+ slice that fail to honour the spec's safety rules, not the absence of deferred pieces.
+- The spec's rulings §2 (N-HA1..N-HA7) and "expiry alone never lets another box acquire".
+- The drill uses a throwaway third dev box (Paul).
+
+## What to check
+
+1. **Single writer.** Can either new table row (`OwnerTerminated`, `ReasonSameBoxEarly`) let two processes write
+ one host's database, replica or files at once? In particular: an in-flight renewal or replication PUT from the
+ old process; a hung (SIGSTOP) agent while a new agent process runs; pid reuse; the activator calling acquire
+ for a host it already holds (`internal/activator/hasamebox.go`, `hawake.go:270-330`, `internal/lease/ha.go`).
+2. **Termination evidence.** Is `SameAccountTerminated` plus the cache as strict as §9.2 and
+ `internal/termfence/fence.go`'s `Verify`? Is caching an error or a negative for 10 s, and a positive for 24 h,
+ safe? Can a positive be wrong (instance id reuse is impossible on EC2; check for anything else)?
+3. **Identity.** Task 3 makes `AcquireHA` refuse without iid/account/region. Does anything on main construct
+ `hafresh.Self` or call `lease.SetSelf` in a way this breaks (console, CLI, tests, `haSelfRetry` timing)? Does
+ refusing at early boot strand a host?
+4. **The restore after takeover.** Does P1a's no-marker restore path actually run for a taken-over lock (the view
+ has a held, non-marker owner of another box), including files and the H6 trio? Cite the code.
+5. **Tests and the simulation.** Do the named tests exercise what the plan claims? Are Task 5's rules catchable by
+ the model as it is (`internal/sim/regionha`), and is the I5 extension well-defined?
+6. **The drill.** Is Task 6 runnable as written on dev (`platform-infrastructure/dev/region-ie-b.tf` uses
+ `infra/modules/region-host` from the GitHub mirror's main), and do its pass bounds follow §9.8?
+
+## Round 2
+
+Earlier rounds: `docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-R1.md` (round 1, NOT READY: 3 P1, 2 P2). The plan's
+"Round 1 dispositions" table says how each was handled.
+
+First give one line per P1 and P2 from round 1: resolved, partly, or not. Carry every unresolved or partly resolved
+finding forward at its current severity, then add new findings. The verdict covers everything outstanding.
+
+On r1.1 specifically: the plan answers with a 60 s settle (a time margin), not generation fencing, and lists fencing as
+a follow-up. Judge whether the settle's argument (kernel flush or reset, S3's idle-request timeout, PUT commit time)
+holds for both the terminated-box and the restarted-agent cases. If you still rate it P1, say exactly which in-flight
+request survives 60 s past its sender's death, and how.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review. (The census, and review of any newly changed
+ security, root, termination or production-storage behaviour, still check the fix; see AGENTS.md, "Stopping rules".)
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the section or task, the problem, the evidence (file:line, verified), the
+failure scenario, a concrete fix and the invariant or trust boundary it breaks (that is its fault family). End with
+exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites.
diff --git a/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-BRIEF-3.md b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-BRIEF-3.md
new file mode 100644
index 000000000..26b99ba80
--- /dev/null
+++ b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-BRIEF-3.md
@@ -0,0 +1,72 @@
+# Review brief: Region HA P1b-1 plan (takeover of a terminated box's hosts), round 3 of 3 (final)
+
+Repo carlos/platform, branch `region-ha-p1b1-takeover`, the commit that adds this brief (rev 3).
+Under review: `docs/superpowers/plans/2026-10-27-region-ha-p1b1-takeover.md`.
+Authorities: `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` (rev 6.1, MERGED) and
+`docs/superpowers/plans/2026-10-26-region-ha-p1a-first-slice.md` (P1a, MERGED as fd93024, #433 fix 80343a5),
+plus the code on this branch (main at 81db4870). Do not review against unmerged branches; if this work needs one, say so as a P1 and stop.
+
+You are an independent reviewer. Read the plan, then the code it names, and check every claim against that code.
+
+## Fixed: do not re-argue
+
+- Paul's rulings N-HA8 and N-HA9 (in the plan): this slice is only takeover on EC2-confirmed termination of an
+ expired lock, request-driven. Forwarding, duties, scan, the SQS
+ consumer, edges-file deletion, the serving latch, hairpin and roles are deferred. Report only mechanisms in this
+ slice that fail to honour the spec's safety rules, not the absence of deferred pieces.
+- The spec's rulings §2 (N-HA1..N-HA7) and "expiry alone never lets another box acquire".
+- The drill uses a throwaway third dev box (Paul).
+
+## What to check
+
+1. **Single writer.** Can the one new table row (an expired lock of a terminated owner) let two processes write
+ one host's database, replica or files at once, beyond what P1a's expired-lock paths already accept? In
+ particular: a hung box that is not terminated; a box stopped and started; the activator's other callers (`internal/activator/hasamebox.go`, `hawake.go:270-330`, `internal/lease/ha.go`).
+2. **Termination evidence.** Is `SameAccountTerminated` plus the cache as strict as §9.2 and
+ `internal/termfence/fence.go`'s `Verify`? Is caching an error or a negative for 10 s, and a positive for 24 h,
+ safe? Can a positive be wrong (instance id reuse is impossible on EC2; check for anything else)?
+3. **Identity.** Task 3 makes `AcquireHA` refuse without iid/account/region. Does anything on main construct
+ `hafresh.Self` or call `lease.SetSelf` in a way this breaks (console, CLI, tests, `haSelfRetry` timing)? Does
+ refusing at early boot strand a host?
+4. **The restore after takeover.** Does P1a's no-marker restore path actually run for a taken-over lock (the view
+ has a held, non-marker owner of another box), including files and the H6 trio? Cite the code.
+5. **Tests and the simulation.** Do the named tests exercise what the plan claims? Are Task 5's rules catchable by
+ the model as it is (`internal/sim/regionha`), and is the I5 extension well-defined?
+6. **The drill.** Is Task 6 runnable as written on dev (`platform-infrastructure/dev/region-ie-b.tf` uses
+ `infra/modules/region-host` from the GitHub mirror's main), and do its pass bounds follow §9.8?
+
+## Round 3 (final)
+
+Earlier rounds: `CODEX-PLAN-REGION-HA-P1B1-R1.md` (NOT READY: 3 P1, 2 P2) and `CODEX-PLAN-REGION-HA-P1B1-R2.md`
+(NOT READY: 1 P1, 2 P2). After round 2, stopping rule 2 applied to the storage-generation fault family and Paul
+ruled N-HA9 (in the plan): takeover only once the terminated owner's lock has also expired; same-box re-take stays
+at expiry as in P1a; the settle rule is gone; storage fencing is a follow-up design. N-HA9 is fixed: do not ask for
+storage fencing in this slice. Report it only if this slice relies on a margin shorter than the one P1a and the
+legacy path already rely on (the 15-minute lease), or breaks that margin.
+
+First give one line per P1 and P2 from round 2: resolved, partly, or not. Carry every unresolved or partly resolved
+finding forward at its current severity, then add new findings. The verdict covers everything outstanding.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review. (The census, and review of any newly changed
+ security, root, termination or production-storage behaviour, still check the fix; see AGENTS.md, "Stopping rules".)
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the section or task, the problem, the evidence (file:line, verified), the
+failure scenario, a concrete fix and the invariant or trust boundary it breaks (that is its fault family). End with
+exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another round.
+- **NOT READY**: one or more P1s, listed.
+
+This is round 3: a NOT READY also says whether the P1s share one cause, and whether refusing the case up front or
+cutting the feature would remove them.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites.
diff --git a/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-R1.md b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-R1.md
new file mode 100644
index 000000000..ac2aeac69
--- /dev/null
+++ b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-R1.md
@@ -0,0 +1,64 @@
+Reviewed `region-ha-p1b1-takeover` at `c5e8bde0a2601a9fe01dffa8edf2ae79ef2dde23`. No files changed, subagents spawned, or tests run.
+
+1. **P1 — Tasks 1 and 4: takeover does not fence outstanding data uploads.**
+
+ The new rows permit immediate acquisition after termination or the same-box proof ([plan:80](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/docs/superpowers/plans/2026-10-27-region-ha-p1b1-takeover.md:80)). The conditional write protects `lock.json`, but replication uses the ordinary replica client without a lease-generation fence ([lease.go:429](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/lease/lease.go:429)). Its LTX keys contain transaction ranges, and uploads carry no write precondition ([replica_client.go:702](/home/paulca/go/pkg/mod/github.com/benbjohnson/litestream@v0.5.14/s3/replica_client.go:702)). Files publication checks the manifest’s ETag, independently of the lease ([publisher.go:291](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/hostfiles/publisher.go:291)).
+
+ **Failure scenario:** an old process sends an upload, then dies before receiving its result. The replacement acquires and restores before that upload commits. The old upload subsequently changes the replica or manifest after restoration; an LTX upload can collide with the replacement’s transaction range. Process death and empty cgroups do not establish that a remote request has settled. S3 provides no atomic relationship between updates to these separate keys. [https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)
+
+ **Fix:** specify storage fencing for both replica and manifest publication before enabling these rows—for example, generation-isolated data with authoritative conditional publication. Add a witness that delays an already-sent upload until after takeover and restore. Old lease renewals themselves are protected by the lock ETag; that protection must extend to data.
+
+ **Fault family:** I1, storage writes crossing ownership generations.
+
+2. **P1 — Task 3: an incomplete initial identity can permanently disable HA acquisition.**
+
+ Task 3 requires all identity fields and changes the retry loop’s completion condition ([plan:138](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/docs/superpowers/plans/2026-10-27-region-ha-p1b1-takeover.md:138)), but the production caller starts that loop only when `self.IID == ""` ([agent.go:232](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/host/agent.go:232)).
+
+ **Failure scenario:** the initial document supplies an instance ID but omits account or region—the partial-document case Task 3 explicitly tests. Every HA acquire refuses, yet no retry starts, even when IMDS subsequently returns a complete document. Testing `haSelfRetry` directly misses this.
+
+ The existing retry test also supplies only `instanceId`; under the proposed completion condition it times out unless updated ([haself_test.go:73](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/host/haself_test.go:73)).
+
+ **Fix:** use the same completeness predicate when starting and completing retries. Add a production-entry test covering partial initial identity followed by complete identity, and update the existing retry fixture.
+
+ **Fault family:** identity admission and recovery liveness.
+
+3. **P1 — Task 5: `early-retake-own-process` cannot produce its promised I1 failure in the existing model.**
+
+ The plan requires dropping only `AcquiredHere` to produce “two awake entries on one box” ([plan:196](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/docs/superpowers/plans/2026-10-27-region-ha-p1b1-takeover.md:196)). However:
+
+ - The remaining proof still requires the slice to be empty ([actions_test.go:17](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/sim/regionha/actions_test.go:17)).
+ - Requests do not acquire while an entry exists ([actions_test.go:822](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/sim/regionha/actions_test.go:822)).
+ - `startWake` overwrites the single entry for that host ([actions_test.go:289](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/sim/regionha/actions_test.go:289)).
+ - The write oracle compares box identity and PID, not acquisition generation ([invariants_test.go:80](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/sim/regionha/invariants_test.go:80)).
+
+ **Failure scenario:** the required mutation remains undetected, so Task 5’s “every rule caught alone” gate cannot pass through the stated mechanism.
+
+ **Fix:** explicitly model a retained old lease/publisher while tenant processes are absent, permit the second acquire attempt, and distinguish acquisition generations in the write oracle. Alternatively, test the forbidden acquisition directly with an I3 oracle. Specify a witness reachable under the single mutation.
+
+ **Fault family:** simulation fidelity at the acquisition-generation boundary.
+
+4. **P2 — Task 5: I5 counts unsuccessful opportunities as proof of stranding.**
+
+ The plan injects describe errors on 10% of calls, then declares a host stranded after every survivor has attempted a wake ([plan:192](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/docs/superpowers/plans/2026-10-27-region-ha-p1b1-takeover.md:192)).
+
+ **Failure scenario:** every survivor’s attempt receives an injected error; correct refusal is reported as an I5 violation. With no survivors, “every surviving box” is vacuously satisfied. Also, if I5 reads the mutated confirmation function, `no-takeover` can suppress its own oracle precondition. Existing finalization neither supplies takeover attempts nor defines these distinctions ([world_test.go:537](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/sim/regionha/world_test.go:537)).
+
+ **Fix:** define termination visibility independently of the mutated confirmer, require an eligible survivor, clear transient faults, and supply completed fault-free wake attempts before checking I5.
+
+ **Fault family:** liveness-oracle fairness and independence.
+
+5. **P2 — Task 6: graceful shutdown can bypass both intended drill cases.**
+
+ Steps 4–5 use ordinary EC2 stop and terminate operations while expecting a held, non-marker lock ([plan:212](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/docs/superpowers/plans/2026-10-27-region-ha-p1b1-takeover.md:212)). These operations attempt graceful OS shutdown. [https://aws.amazon.com/about-aws/whats-new/2025/07/amazon-ec2-skip-os-shutdown-option-during-stop-terminate/](https://aws.amazon.com/about-aws/whats-new/2025/07/amazon-ec2-skip-os-shutdown-option-during-stop-terminate/)
+
+ The agent calls `svc.Shutdown` ([agent.go:1107](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/host/agent.go:1107)); a successful HA stop publishes a release marker ([activator.go:4498](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/activator/activator.go:4498)). A survivor may therefore acquire legitimately before termination confirmation. The stop drill’s “never taken” assertion can fail on correct behavior, and the takeover drill can exercise marker acquisition instead.
+
+ The five-minute stop observation also cannot guarantee “held, then refused”: the lease TTL is fifteen minutes ([lease.go:40](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/lease/lease.go:40)).
+
+ **Fix:** explicitly bypass graceful shutdown within the approved disposable-box scope; verify C owns a non-marker lock before and after fault injection. Observe through its recorded expiry to test expired refusal. Record termination confirmation and restore duration separately: §9.8 describes estimates, not an unconditional three-minute guarantee.
+
+ **Fault family:** drill validity and recovery measurement.
+
+The no-marker restore path itself checks out: the acquired view reaches `restoreHA`, `DecideKeep` rejects a missing marker, and restoration replaces the database, files, platform env and wake state ([backend_exec.go:844](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/activator/backend_exec.go:844), [hawake.go:434](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/activator/hawake.go:434), [hawake.go:605](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/activator/hawake.go:605)). No P3 findings.
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-R2.md b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-R2.md
new file mode 100644
index 000000000..39272c112
--- /dev/null
+++ b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-R2.md
@@ -0,0 +1,53 @@
+- **r1.1 — Partly resolved, still P1:** the settle handles short delays, but multipart completion can outlast 60 seconds.
+- **r1.2 — Resolved:** Task 3 fixes both retry predicates, updates fixtures, and adds a production-entry test.
+- **r1.3 — Resolved:** `duplicateWake` and the acquire-time oracle make the replacement mutation catchable.
+- **r1.4 — Partly resolved, still P2:** truth and eligibility are independent, but finalization can check liveness before a survivor’s settle timer has elapsed.
+- **r1.5 — Resolved:** the drill bypasses graceful shutdown, checks non-marker ownership, observes expiry, and separates timing components.
+
+Reviewed `region-ha-p1b1-takeover` at `c98b239bc601d4e999e0bf1be14f098d1719bf02`. No files changed, subagents spawned, or tests run.
+
+1. **P1 — Tasks 1, 2, 4 and 5: the 60-second settle does not establish that outstanding replica uploads have finished.**
+
+ The argument at [plan:22](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/docs/superpowers/plans/2026-10-27-region-ha-p1b1-takeover.md:22) assumes a fully received upload commits within seconds. The actual replica path uses the SDK’s multipart uploader: [replica_client.go:733](/home/paulca/go/pkg/mod/github.com/benbjohnson/litestream@v0.5.14/s3/replica_client.go:733), which calls `CompleteMultipartUpload` at [upload.go:888](/home/paulca/go/pkg/mod/github.com/aws/aws-sdk-go-v2/feature/s3/manager@v1.20.18/upload.go:888).
+
+ AWS explicitly documents that this operation can take several minutes after receipt, sending whitespace while processing. An idle-request timeout therefore does not bound this operation. [https://docs.aws.amazon.com/AmazonS3/latest/API/API_CompleteMultipartUpload.html](https://docs.aws.amazon.com/AmazonS3/latest/API/API_CompleteMultipartUpload.html)
+
+ **Failure scenario:** the old agent uploads all parts of an LTX file and sends the completion request, then dies. S3 has accepted the complete request and is still assembling the object. The replacement waits 60 seconds, acquires, and restores without that object. The old completion subsequently publishes into the same replica prefix. Its key contains transaction ranges, with no ownership generation or write condition ([replica_client.go:702](/home/paulca/go/pkg/mod/github.com/benbjohnson/litestream@v0.5.14/s3/replica_client.go:702)), so it can conflict with the replacement’s history.
+
+ This applies both to a restarted agent and to a terminated box: closing the sender’s connection supplies neither an acknowledged abort nor a storage fence for an already accepted operation. Termination confirmation adds elapsed time, but establishes no upper bound on completion.
+
+ Task 5 excludes this execution by making every late upload finish before `Settle` ([plan:214](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/docs/superpowers/plans/2026-10-27-region-ha-p1b1-takeover.md:214)). Consequently, its clean sweep would validate the assumed bound, not establish it.
+
+ **Fix:** require generation-isolated storage with authoritative publication, or another enforceable storage fence, before enabling these acquisitions. Include an accepted multipart completion landing after takeover in the unmutated model. Keep both new acquisition rows disabled until that boundary is established.
+
+ **Fault family:** I1, storage writes crossing ownership generations; carried from r1.1.
+
+2. **P2 — Task 5: the final I5 check can still report a correctly refused takeover as stranded.**
+
+ The confirmer’s settle starts at its **first evidence**, not at termination ([plan:125](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/docs/superpowers/plans/2026-10-27-region-ha-p1b1-takeover.md:125)). However, finalization advances time and then gives each survivor only one wake attempt ([plan:216](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/docs/superpowers/plans/2026-10-27-region-ha-p1b1-takeover.md:216)). The existing [world_test.go:537](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/sim/regionha/world_test.go:537) supplies no earlier confirmation attempts.
+
+ **Failure scenario:** neither survivor queried the terminated owner during the random walk. After finalization’s advance, each first wake records its first evidence and correctly refuses pending settlement. I5 immediately fails, although another attempt after six ticks would succeed.
+
+ **Fix:** after clearing faults and passing the independent visibility bound, give survivors a confirmation attempt, advance through settlement, then give them fault-free wake attempts before asserting I5. Keep this schedule independent of the mutated confirmer so `no-takeover` cannot suppress the check. Add a witness with no requests between termination and finalization.
+
+ **Fault family:** liveness-oracle fairness and independence; carried from r1.4.
+
+3. **P2 — Tasks 2, 4 and 6: the required drill measurements have no specified observation points.**
+
+ Task 6 requires Describe counts from agent logs and each survivor’s first termination evidence ([plan:236](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/docs/superpowers/plans/2026-10-27-region-ha-p1b1-takeover.md:236)). Task 4 specifies only a successful-proof log after settlement and throttled error logs ([plan:183](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/docs/superpowers/plans/2026-10-27-region-ha-p1b1-takeover.md:183)). Task 2 specifies no logging or counters for actual Describe calls or `firstSeen`.
+
+ **Failure scenario:** the drill records takeover time but cannot establish when that survivor first confirmed termination, or distinguish cached negative answers from repeated Describe requests. The required settle and request-rate measurements remain unverified.
+
+ **Fix:** add observation points for actual Describe attempts and the first accepted termination evidence, including IID and timestamp, and specify how the drill collects them.
+
+ **Fault family:** drill validity and recovery measurement.
+
+The no-marker restore path checks out: acquisition preserves the classified view, [backend_exec.go:844](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/activator/backend_exec.go:844) passes it to `restoreHA`, and [keep.go:70](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/hafresh/keep.go:70) refuses reuse without a marker. Database restoration is followed by clean files restoration, including the two file-based secrets, platform env, and wake state ([hawake.go:434](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/activator/hawake.go:434), [hawake.go:605](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/activator/hawake.go:605)).
+
+The specified termination checks match the relevant identity/state checks in `Verify`; negative/error caching remains conservative. Old renewals are protected by the lock’s ETag. The existing same-box proof rejects hosts acquired by this process, while the control service restricts sweep access to the systemd main PID ([peer_edge.go:93](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/instancectl/peer_edge.go:93)). I found no additional console or CLI identity caller broken by Task 3.
+
+No P3 findings.
+
+This is round 2 of 3, with the storage-generation fault family unresolved in two consecutive rounds. Stopping rule 2 applies: the choices are an enforceable refusal gate, cutting these takeover paths, or establishing the invariant at one storage boundary with a witness. I recommend deferring both new rows pending that boundary, rather than another time-margin adjustment.
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-R3.md b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-R3.md
new file mode 100644
index 000000000..4b01d65fe
--- /dev/null
+++ b/docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-R3.md
@@ -0,0 +1,28 @@
+- **r2.1 P1 — Resolved by N-HA9:** takeover now requires expiry; the early takeover rows and 60-second settle are removed.
+- **r2.2 P2 — Resolved:** finalization uses independent termination truth, passes visibility and expiry, and supplies confirmation and wake attempts before checking I5.
+- **r2.3 P2 — Resolved:** Task 2 specifies describe and first-evidence logs; Task 6 specifies their collection.
+
+Reviewed `region-ha-p1b1-takeover` at `1f187aeaf13ec5dac292629d0dcbcff99d18a7cb`. No files changed, subagents spawned, or tests run.
+
+No P1 findings.
+
+1. **P2 — Task 6, Step 2: complete the third-box configuration instructions.**
+
+ [Plan:227](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/docs/superpowers/plans/2026-10-27-region-ha-p1b1-takeover.md:227) specifies copying `region-ie-b.tf` and changing three names. Those substitutions leave both output declarations named `ie_b_eip` and `ie_b_instance_id`, duplicating the declarations in the original file ([region-ie-b.tf:22](/home/paulca/amadan.net/carlos/platform-infrastructure/dev/region-ie-b.tf:22)). I verified this by applying the specified substitutions in memory.
+
+ **Failure scenario:** following the recipe produces duplicate output definitions, preventing configuration validation. After correcting those names, the newly added module also needs installation before apply; OpenTofu documents that step under `init`. [https://opentofu.org/docs/cli/commands/init/](https://opentofu.org/docs/cli/commands/init/)
+
+ **Fix:** explicitly rename the outputs to `ie_c_eip` and `ie_c_instance_id`, retain their references to `module.host_ie_c`, and run `tofu init` and validation before reviewing and applying the targeted plan.
+
+ **Fault family:** drill reproducibility and acceptance evidence.
+
+The remaining checks support the plan:
+
+- **Single writer:** the new row preserves expiry and requires termination evidence. Competing survivors remain serialized by the conditional write and reclassification loop ([legacytake.go:82](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/lease/legacytake.go:82)). Same-box recovery retains its startup-sweep and acquired-here checks.
+- **Evidence and identity:** the proposed predicate matches the relevant identity and state checks in `Verify`. Negative/error caching delays recovery without granting authority. Production identity becomes complete once and then remains stable; failed early wakes are removed so subsequent requests retry ([activator.go:1924](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/activator/activator.go:1924)).
+- **Restore:** acquisition preserves the old view. `restorePlain` passes it to `restoreHA`; no marker prevents local reuse. Database restore is followed by clean files restoration, including the file-based secrets and platform environment ([backend_exec.go:844](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/activator/backend_exec.go:844), [hawake.go:434](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/activator/hawake.go:434), [hawake.go:605](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/activator/hawake.go:605)).
+- **Simulation:** the proposed witnesses are catchable: hung-owner takeover violates the running-unit check; premature takeover is exposed by the late upload’s holder check; suppressed confirmation fails the independent final I5 check.
+
+No P3 findings. Fix the listed P2 without reopening this review.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/docs/superpowers/plans/CODEX-REVIEW-BRIEF-REGION-HA-P1B1-BRANCH-1.md b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-REGION-HA-P1B1-BRANCH-1.md
new file mode 100644
index 000000000..254295bb2
--- /dev/null
+++ b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-REGION-HA-P1B1-BRANCH-1.md
@@ -0,0 +1,51 @@
+# Review brief: Region HA P1b-1 branch (takeover of a terminated box's hosts), round 1 of 3
+
+Repo carlos/platform, branch `region-ha-p1b1-takeover`, commit 7305110c6a17ae41f4c3938560e6e5c4009badb0.
+Under review: the diff 42f9f091..7305110c (the code; 42f9f091 is the approved plan rev 3.1 on top of main 81db4870),
+packaged with its commit list and stat in `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/.superpowers/sdd/2026-10-27-region-ha-p1b1-takeover/review-42f9f091..7305110c.diff` (read it first).
+Authorities: `docs/superpowers/plans/2026-10-27-region-ha-p1b1-takeover.md` (rev 3.1; its own Astra review closed READY AFTER FIXES at
+round 3), the spec `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` (rev 6.1 plus this branch's N-HA8/N-HA9 edits), and
+P1a as merged on main (fd93024, 80343a5). Do not review against unmerged branches.
+
+You are an independent reviewer. Read the diff, then the code it calls, and check every claim against that code. Each task with its own
+review (1, 2, 4, 5) passed it; the ledger of those reviews and their deferred minors is
+`.superpowers/sdd/2026-10-27-region-ha-p1b1-takeover/progress.md` (read the "Progress" section). Task 3 had no per-task review (AGENTS.md stopping rule 3): review it in full.
+
+## Fixed: do not re-argue
+
+- Paul's rulings N-HA8 and N-HA9 (the plan's "Rulings"): takeover only of an EXPIRED lock whose owner EC2 confirms terminated, request-driven;
+ same-box recovery unchanged from P1a; storage fencing, the SQS consumer, the scan, forwarding and edges-file deletion are later slices.
+- The census (TestPlan14RootReadCensus currently fails on this branch) is handled by the next step; do not review census rows.
+
+## What to check
+
+1. **Single writer (I1).** Across the whole branch, can any path take or write a host's lock, replica or files that another live process
+ holds? Include the interaction of the new row with P1a's same-box recovery, the legacy path, the obligation retry and releases.
+2. **Termination evidence and the confirmer** as wired in production (`internal/host/agent.go`): identity read at each call, EC2 only
+ through rootaws, the cache and single-flight, the describe budget.
+3. **Task 3, identity.** `readIdentity`, `haSelfRetry` and its start in `RunAgent`, `AcquireHA`'s refusal; can a box be left without a
+ complete identity for its process's life, or can a legacy host be affected?
+4. **The simulation** (`internal/sim/regionha`): does it still model P1a's paths faithfully, and do the new rules test what they claim?
+5. **Deferred minors and parked items** in the ledger: say which must be fixed before merge.
+6. **Binary size:** linux/arm64 `-s -w` measured at 52,887,714 bytes against the 53,000,000 ceiling (`.amadan/ci.d/20-cross@5`). Anything
+ in the diff that pulls more of the SDK than needed?
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review. (The census, and review of any newly changed security, root, termination
+ or production-storage behaviour, still check the fix; see AGENTS.md, "Stopping rules".)
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the file or task, the problem, the evidence (file:line, verified), the failure scenario, a concrete
+fix and the invariant or trust boundary it breaks (its fault family). End with exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites or the simulation sweep.
diff --git a/docs/superpowers/plans/CODEX-REVIEW-REGION-HA-P1B1-BRANCH-1.md b/docs/superpowers/plans/CODEX-REVIEW-REGION-HA-P1B1-BRANCH-1.md
new file mode 100644
index 000000000..3871d25f5
--- /dev/null
+++ b/docs/superpowers/plans/CODEX-REVIEW-REGION-HA-P1B1-BRANCH-1.md
@@ -0,0 +1,33 @@
+No P1 found in `42f9f091..7305110c`. One P2 needs fixing before merge.
+
+1. **P2 — SDK retries exceed the describe budget.**
+ [hatakeover.go:39](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/host/hatakeover.go:39) constructs the EC2 client with its default retry policy. [DescribeInstance:159](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/termfence/fence.go:159) overrides only the region. The pinned SDK defaults to [three attempts](/home/paulca/go/pkg/mod/github.com/aws/aws-sdk-go-v2@v1.44.0/aws/retry/standard.go:27), including retries for HTTP 503 and `RequestLimitExceeded`.
+
+ **Failure scenario:** a throttled describe can send three requests before the confirmer caches its error for ten seconds. Concurrent callers share that operation, but its internal retries bypass the stated request budget. The single log entry also understates requests made.
+
+ **Fix:** disable SDK retries on this takeover client, preserving the method-value wrapper. Add a transport-level test returning a retryable error: assert one HTTP request, no additional request during the negative-cache interval, then one after expiry.
+
+ **Fault family:** termination-confirmation request budget and observability.
+
+2. **P3 — Existing timing prose contradicts N-HA9.**
+ [Spec:78](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md:78) still promises immediate takeover; [spec:436](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md:436) says expiry matters only for same-box recovery.
+
+ **Failure scenario:** an operator reads those passages and expects recovery before expiry. **Fix:** mark N-HA3’s timing superseded and update §9.7 for cross-box expiry. **Fault family:** documented takeover contract. Remains a follow-up, as already classified in the ledger.
+
+3. **P3 — Leader cancellation lacks its deferred regression test.**
+ [confirm_test.go:281](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b1/internal/termfence/confirm_test.go:281) tests cancellation of a waiting caller, not the caller performing the describe.
+
+ **Failure scenario:** a future change could mishandle the leader’s cancellation without this test detecting it. I found no present implementation failure. **Fix:** deterministically cancel the leader, verify remaining waiters receive its error, and check cache suppression followed by retry after ten seconds. **Fault family:** concurrent confirmation and cancellation. Remains a follow-up.
+
+The other review checks produced no additional findings:
+
+- Conditional acquires, legacy refusal, same-box recovery and release obligations preserve the single-writer boundary under N-HA9’s accepted timing assumption.
+- Task 3 retries partial identities until complete; HA acquisition refuses incomplete identity. Legacy acquisition does not gain that refusal.
+- The simulation retains P1a’s paths, captures the dead writer’s PID, and bases termination liveness checks on world truth. The parked difference in even-seed random walks does not require a pre-merge fix.
+- The EC2 method-value wrapper avoids retaining the whole client method set. The reported binary measurement leaves **112,286 bytes** of headroom; I did not independently rebuild it.
+
+`git diff --check` passed. The targeted Go test could not start because the sandbox denied creation of its work directory. No files were edited, no subagents were spawned, and no full suites or simulation sweep ran. Census remains the separate next step.
+
+Fix the P2 without reopening this review, retaining the required census and scoped termination-change checks.
+
+READY AFTER FIXES
\ No newline at end of file
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 b6cd4fc56..7a4e33a31 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
@@ -75,11 +75,13 @@ These stand from spec 1 and spec 2.
| Roll order | Dev boxes, dev console, check, flagship boxes, flagship console. |
| N-HA1 | HA is built **without claims**. The Litestream S3 lease is the only single-writer guard. |
| N-HA2 | Replaces H25. Once every instance's DB and files are in S3, the old box joins the load balancer as an ordinary member. Its instances are slept one at a time and wake on the group boxes. The old box is removed once empty. IE's platform box stays outside the group. |
-| N-HA3 | Failover is "a few minutes, lower is better", met **without shortening every lease**. Once EC2 confirms a box is terminated, a survivor takes over its leases at once. |
+| N-HA3 | Failover is "a few minutes, lower is better", met **without shortening every lease**. Once EC2 confirms a box is terminated, a survivor takes over its leases at once. Superseded on timing by N-HA9: the takeover waits for the lease to expire until storage fencing exists. |
| N-HA4 | N-box offline moves and seed import join this plan series. Dev and the first test region may go HA with both refused. No carloku.com region retires its old box until both work in N-box regions. |
| N-HA5 | App files on the continuous (top-plan) class sync every 10 s. `instance.key`, `report.token` and `<host>.env` sync at about 1 s. |
| N-HA6 | Confirms A16 (2026-10-26): the cheaper replication classes stay available in HA regions and lose up to their interval on a failover, stated plainly. H3's ~1 s applies to the stream class. |
| N-HA7 | (2026-10-26, after P1a plan round 2) **P1a gives HA only to hosts born HA**: created after their region's HA activation, which the console stamps on the record (`ha: true`, from `CONSOLE_HA_REGIONS`). P1a migrates no existing host; existing hosts behave exactly as today. Migrating existing hosts is its own later slice: an operator-run, held, offline step (the host stopped and held on every box, verified, published, then released). |
+| N-HA8 | (2026-10-27) **P1b is cut into slices.** The first, P1b-1, is takeover on confirmed termination, request-driven: no termination queue consumer, no scan, no duties. A born-HA host on a dead box otherwise never comes back, which is worse than a legacy host. |
+| N-HA9 | (2026-10-27, after Astra rounds 1 and 2) **A survivor takes a terminated box's lock only once that lock has also expired.** A same-box re-take stays at expiry, as in P1a. An upload the dead process already sent can still land: `CompleteMultipartUpload` can run for minutes after S3 receives it, and replica and manifest keys carry no ownership generation. A time margin shorter than the lease is not defensible, and the 15-minute lease is the margin every legacy takeover and P1a's same-box recovery already rely on. Taking over sooner needs storage fencing, which is its own design. |
### 2.2 Author's calls
@@ -401,7 +403,7 @@ On an HA box, the lease package's acquire reads first: one GET of `lock.json` wi
| A release marker, clean or not | Conditional PUT, with `If-Match`. |
| Held and unexpired | A held answer naming the owner (§6.2). |
| Expired, owner is this box's instance id | Conditional PUT, only with the emptiness proof of §9.6. Otherwise refused. |
-| Expired or unexpired, owner confirmed terminated (§9.2) | Conditional PUT: the takeover. |
+| Expired, owner confirmed terminated (§9.2, N-HA9) | Conditional PUT: the takeover. A terminated owner's unexpired lock is held until it expires, because a write the dead process already sent can still land. |
| A lifted tombstone, left by a move before the region went HA | Conditional PUT; never keep the local copy. |
| Anything else | Refused: another box's expired lease, an old-format owner, or a live tombstone. |
@@ -427,11 +429,11 @@ Rev 3's automatic replacement (A22 of rev 3) is cut (astra-2.2): a peer's recent
After an agent crash, a box may re-take its own expired lease only once it has proven the old writer gone. Its agent stops the host's units, and proves the host's cgroups empty.
- **No proof, no recovery.** Layouts with no such proof are refused: nested and rootfs instances, `Backing=unit`, and boxes without cgroup delegation. `wakeHostProven` accepts all of those today (`internal/activator/opset.go:437-453`), and startup cleanup is best-effort (`internal/host/agent.go:592-598`).
- **What a refusal does.** It raises the suspect-holder alarm. The runbook step terminates the box, which then makes the takeover path apply.
-- **Same-box takeover before expiry** stays a later improvement.
+- **Same-box takeover before expiry** stays a later improvement. Storage fencing is its precondition: until stores refuse writes from an earlier owner, no box may take a lock early, even its own.
### 9.7 Clock skew
-Expiry now matters only for a box re-taking its own lease, which uses one clock. The margin is still bounded:
+Expiry matters for a box re-taking its own lease and for a survivor taking over a terminated box's lock (N-HA9); each decision reads expiry on one clock, the deciding box's own. The margin is still bounded:
- chrony (Amazon Time Sync) is required on every box;
- the safety margin (5 s, `health.go:19`) must exceed twice the maximum offset, so the maximum allowed offset is 2 s;
- each box publishes its chrony offset, and an alarm fires above 1 s (§20).
@@ -447,6 +449,7 @@ These are estimates; dev measures each one (§21).
| EC2 reports `terminated`; the event arrives | 30 s to 2 min | 30 s to 2 min after the group's terminate |
| First request: acquire, describe, takeover, restore | about a second, plus the restore | the same |
| **Total, request-driven instances** | **about 1 to 3 min** | **about 2 to 5 min** |
+| Until storage fencing (N-HA9) | takeover also waits for the lease to expire, so the totals above are up to about 15 minutes after the last renewal | the same |
| Always-on workers, ticks, due wakes | one sweep (30 s or less) after confirmation; backoffs cancelled | the same |
| Worst case, event lost | the next request's dial failure confirms at once; with no requests, view ageing (15 min) | the same |
@@ -672,6 +675,7 @@ S3 prices: LIST and PUT $0.005 per 1,000; GET $0.0004 per 1,000; DELETE free.
|---|---|
| P0 | The removals this series owns (§16.3); rides in P1a. |
| P1a | **First slice** (N-HA7). Born-HA hosts only: the record flag and `CONSOLE_HA_REGIONS`; owner format, HA acquire, release marker, keep rule, retry queue (§5); the first-wake leftover refusal and empty baseline; files and wake-state publication and the H6 trio (§8); key producers (§7.3); same-box proof (§9.6); the move and import refusals for HA hosts (§14). No migration. |
+| P1b-1 | **Slice of P1b** (N-HA8). Takeover on confirmed termination, request-driven: the acquire table takes a terminated owner's expired lock (§9.4, N-HA9). No termination queue consumer, no scan, no duties. |
| P1b | Forwarding (§6), duties and the scan (§7), takeover and same-box proof (§9), admission, latch and lifecycle hook (§10, §4.3), hairpin (§12.4), roles. |
| P2 | Console: role and readiness doors, capacity metric, create refusals (§11), the HA move and import refusals (§14), ingress list, the S2 §8 rewrites (§15). |
| P3 | Infrastructure and boot (§12): group mode, NLB security group, lifecycle hook, boot script, IAM, alarms. |
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index d97a017e8..7efa860b1 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -337,6 +337,13 @@ type ExecBackend struct {
// Nil: never proven, and every same-box takeover of an expired HA lock
// is refused.
StartupSwept func() bool
+ // OwnerTerminated asks EC2 whether another box's instance is confirmed
+ // terminated (termfence.Confirmer.Terminated), the proof that hands an
+ // HA host whose lease expired to a surviving box (hatakeover.go). Nil:
+ // no takeover, and another box's expired HA lock is always refused.
+ OwnerTerminated func(ctx context.Context, iid string) (bool, error)
+ // takeover is the takeover proof's log throttle (hatakeover.go).
+ takeover takeoverState
// sameBox is the same-box recovery's state (hasamebox.go): the hosts
// this process has acquired (acquiredHere).
sameBox sameBoxState
diff --git a/internal/activator/harelease_test.go b/internal/activator/harelease_test.go
index 63e352680..2d96a625b 100644
--- a/internal/activator/harelease_test.go
+++ b/internal/activator/harelease_test.go
@@ -901,9 +901,9 @@ func TestFailedWakeKeepsLeaseWhileSliceHoldsAReplacement(t *testing.T) {
t.Fatalf("no retained wake with its replica: %+v", u)
}
other := s.peer(t)
- lease.SetSelf(hafresh.Self{Ref: "b", IID: "i-b"})
+ lease.SetSelf(hafresh.Self{Ref: "b", IID: "i-b", Account: "111122223333", Region: "eu-west-1"})
_, err := other.b.Acquire(context.Background(), other.rt)
- lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a"})
+ lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a", Account: "111122223333", Region: "eu-west-1"})
var held *errLeaseHeld
if !errors.As(err, &held) {
t.Fatalf("another box acquired the host beside its replacement: %v", err)
diff --git a/internal/activator/hasamebox.go b/internal/activator/hasamebox.go
index e084b9a6d..fbb69bb99 100644
--- a/internal/activator/hasamebox.go
+++ b/internal/activator/hasamebox.go
@@ -17,11 +17,12 @@ import (
// second writer on the same box after an agent crash).
//
// When the agent dies with an HA host awake, the host's lock stops
-// renewing. No other box ever takes an expired HA lock
-// (hafresh.ReasonOtherExpired), so the host comes back only on this box,
-// once the lock has expired (up to one lease TTL, lease.LeaseTTL, 15
-// minutes, after the crash), and only on proof that nothing of the host
-// still runs here: hafresh.Proofs.SameBoxEmpty, which is sameBoxEmpty.
+// renewing. No other box takes an expired HA lock of a box that is not
+// confirmed terminated (hafresh.ReasonOtherExpired, hatakeover.go), and
+// this box is not, so the host comes back only on this box, once the lock
+// has expired (up to one lease TTL, lease.LeaseTTL, 15 minutes, after the
+// crash), and only on proof that nothing of the host still runs here:
+// hafresh.Proofs.SameBoxEmpty, which is sameBoxEmpty.
//
// The proof is root's existing stop-and-prove for nested units; P1a adds
// none. sameBoxEmpty answers true only when all of these hold:
diff --git a/internal/activator/hasecrets_test.go b/internal/activator/hasecrets_test.go
index 07fde366e..38411d021 100644
--- a/internal/activator/hasecrets_test.go
+++ b/internal/activator/hasecrets_test.go
@@ -351,9 +351,9 @@ func TestFirstWakeCrashBeforePublishRemints(t *testing.T) {
// Another box is refused the expired lease.
other := s.restart(t)
- lease.SetSelf(hafresh.Self{Ref: "b", IID: "i-b"})
+ lease.SetSelf(hafresh.Self{Ref: "b", IID: "i-b", Account: "111122223333", Region: "eu-west-1"})
_, err = other.wakeForTest(context.Background())
- lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a"})
+ lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a", Account: "111122223333", Region: "eu-west-1"})
var refused *errLeaseRefused
if !errors.As(err, &refused) || !strings.Contains(refused.reason, hafresh.ReasonOtherExpired) {
t.Fatalf("another box took it: %v", err)
@@ -381,9 +381,9 @@ func TestFirstWakeCrashBeforePublishRemints(t *testing.T) {
t.Fatalf("the app started before its secrets were acknowledged: the manifest held %q", atSpawn)
}
// Another box is still refused: the host is held.
- lease.SetSelf(hafresh.Self{Ref: "b", IID: "i-b"})
+ lease.SetSelf(hafresh.Self{Ref: "b", IID: "i-b", Account: "111122223333", Region: "eu-west-1"})
_, err = other.b.Acquire(context.Background(), other.rt)
- lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a"})
+ lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a", Account: "111122223333", Region: "eu-west-1"})
var held *errLeaseHeld
if !errors.As(err, &held) {
t.Fatalf("another box acquired the woken host: %v", err)
diff --git a/internal/activator/hatakeover.go b/internal/activator/hatakeover.go
new file mode 100644
index 000000000..b0e7842ec
--- /dev/null
+++ b/internal/activator/hatakeover.go
@@ -0,0 +1,70 @@
+package activator
+
+import (
+ "context"
+ "log"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// Region HA P1b-1, the takeover of a terminated holder's host.
+//
+// An HA lock that expired while another box held it is taken only when
+// that box's instance is confirmed terminated: hafresh.DecideAcquire asks
+// hafresh.Proofs.OwnerTerminated, which is ownerTerminated, only for an
+// expired lock of another box's non-empty instance id, so an unexpired
+// lock is held without asking (N-HA9). The answer is EC2's, in this box's
+// own account and region (termfence.Confirmer): a stopped, running or
+// unknown instance, another account or region, or a describe that failed,
+// refuses the wake and nothing is written. The host then stays down until
+// the holder comes back and releases it, or EC2 confirms it terminated.
+
+// ownerTerminated is the takeover proof for rt's acquire: nil (no
+// takeover) when OwnerTerminated is not wired. A confirmed termination is
+// logged; a failed describe is logged at most once a minute per host.
+func (b *ExecBackend) ownerTerminated(ctx context.Context, rt registry.Route) func(iid string) (bool, error) {
+ if b.OwnerTerminated == nil {
+ return nil
+ }
+ return func(iid string) (bool, error) {
+ gone, err := b.OwnerTerminated(ctx, iid)
+ if err != nil {
+ b.takeover.alarm(rt.Host, iid, err)
+ return false, err
+ }
+ if gone {
+ log.Printf("activator: %s: the holder %s is terminated (EC2) and its lease expired; taking the host over", rt.Host, iid)
+ }
+ return gone, nil
+ }
+}
+
+// takeoverAlarmEvery is how often one host's failed takeover proof is
+// logged again while its wakes keep failing.
+const takeoverAlarmEvery = sameBoxAlarmEvery
+
+// takeoverState is when each host's failed takeover proof was last logged.
+type takeoverState struct {
+ mu sync.Mutex
+ alarmed map[string]time.Time
+}
+
+// alarm logs a takeover refused because EC2 could not be asked, at most
+// once a minute per host (the twin of sameBoxState.alarm).
+func (s *takeoverState) alarm(host, iid string, why error) {
+ s.mu.Lock()
+ now := time.Now()
+ last, seen := s.alarmed[host]
+ if seen && now.Sub(last) < takeoverAlarmEvery {
+ s.mu.Unlock()
+ return
+ }
+ if s.alarmed == nil {
+ s.alarmed = map[string]time.Time{}
+ }
+ s.alarmed[host] = now
+ s.mu.Unlock()
+ log.Printf("activator: ALERT %s: the takeover of %s's expired HA lock is refused: EC2 did not answer whether it is terminated: %v (the host stays down until EC2 confirms the holder terminated)", host, iid, why)
+}
diff --git a/internal/activator/hatakeover_test.go b/internal/activator/hatakeover_test.go
new file mode 100644
index 000000000..c6e7649bc
--- /dev/null
+++ b/internal/activator/hatakeover_test.go
@@ -0,0 +1,170 @@
+package activator
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// Region HA P1b-1: a born-HA host whose holder box is terminated, and
+// whose lease has expired, is taken over by the first wake at a surviving
+// box. These run through the production Acquire against the lock fixture.
+
+// heldByB is box b's HA lease on the host, expiring at expires.
+const heldByB = "box/v1;ref=b;iid=i-b;pid=7;ha=1"
+
+// terminatedOracle is an OwnerTerminated that answers yes, no or err for
+// every id, and records the ids it was asked about.
+type terminatedOracle struct {
+ mu sync.Mutex
+ asked []string
+ yes map[string]bool
+ err error
+}
+
+func (o *terminatedOracle) terminated(_ context.Context, iid string) (bool, error) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ o.asked = append(o.asked, iid)
+ if o.err != nil {
+ return false, o.err
+ }
+ return o.yes[iid], nil
+}
+
+func (o *terminatedOracle) calls() []string {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ return append([]string(nil), o.asked...)
+}
+
+// takeoverBackend is an HA backend whose host's lock is b's lease,
+// expiring at expires, with oracle (nil: none wired) as OwnerTerminated.
+func takeoverBackend(t *testing.T, expires time.Time, oracle *terminatedOracle) (*ExecBackend, registry.Route, []byte) {
+ t.Helper()
+ b, rt := haBackend(t, "shop.example.com")
+ if oracle != nil {
+ b.OwnerTerminated = oracle.terminated
+ }
+ if o, ok := hafresh.ParseOwner(heldByB); !ok || !o.HA || o.IID != "i-b" {
+ t.Fatalf("fixture: %q does not parse as b's HA owner", heldByB)
+ }
+ body := leaseBody(t, heldByB, expires)
+ putLockFor(t, b, rt, body)
+ return b, rt, body
+}
+
+func lockBodyOf(b *ExecBackend, rt registry.Route) []byte {
+ return haFixOf(b).fx.LockBody(b.Cfg.hibernatePrefix(rt.Host))
+}
+
+func TestTakeoverOfATerminatedHolder(t *testing.T) {
+ ctx := context.Background()
+ logs := captureLog(t)
+ oracle := &terminatedOracle{yes: map[string]bool{"i-b": true}}
+ b, rt, _ := takeoverBackend(t, time.Now().Add(-time.Minute), oracle)
+ l, err := b.Acquire(ctx, rt)
+ if err != nil {
+ t.Fatalf("the terminated holder's expired lock was not taken: %v", err)
+ }
+ releaseHALease(t, l)
+ if got := oracle.calls(); len(got) != 1 || got[0] != "i-b" {
+ t.Fatalf("OwnerTerminated asked about %v, want [i-b]", got)
+ }
+ v, err := hafresh.DecodeLock(lockBodyOf(b, rt), "x")
+ if err != nil {
+ t.Fatal(err)
+ }
+ o, ok := hafresh.ParseOwner(v.Lock.Owner)
+ if !ok || !o.HA || o.Ref != "a" || o.IID != "i-a" || v.Lock.Generation != 10 || v.Lock.Release != nil {
+ t.Fatalf("the taken lock is %+v, want this box's HA lease at generation 10", v.Lock)
+ }
+ if !strings.Contains(logs.String(), "HA lease acquired in") || !strings.Contains(logs.String(), "(holder terminated)") {
+ t.Fatalf("the lease log does not say the holder was terminated:\n%s", logs)
+ }
+ if !strings.Contains(logs.String(), "activator: shop.example.com: the holder i-b is terminated (EC2) and its lease expired; taking the host over") {
+ t.Fatalf("the activator did not log the takeover:\n%s", logs)
+ }
+ w, ok := b.haAcquired(rt.Host)
+ if !ok || w.view.Absent || w.view.Lock.Release != nil || w.view.Lock.Owner != heldByB {
+ t.Fatalf("the wake classified %+v, want b's expired lease and no marker", w.view)
+ }
+ if fresh, err := b.Restore(ctx, rt); err != nil || fresh {
+ t.Fatalf("restore after the takeover: fresh %v, err %v", fresh, err)
+ }
+ if restoreCalls(b) != 1 {
+ t.Fatalf("%d replica restores, want 1", restoreCalls(b))
+ }
+ if !strings.Contains(logs.String(), "activator: shop.example.com: restored ("+hafresh.KeepNoMarker+")") {
+ t.Fatalf("the restore's keep reason is not %s:\n%s", hafresh.KeepNoMarker, logs)
+ }
+}
+
+// A terminated holder's lock is not taken before it expires (N-HA9): the
+// wake is held, the cloud is not asked, nothing is written.
+func TestTakeoverWaitsForExpiry(t *testing.T) {
+ ctx := context.Background()
+ oracle := &terminatedOracle{yes: map[string]bool{"i-b": true}}
+ b, rt, body := takeoverBackend(t, time.Now().Add(10*time.Minute), oracle)
+ _, err := b.Acquire(ctx, rt)
+ var held *errLeaseHeld
+ if !errors.As(err, &held) || held.holder != heldByB {
+ t.Fatalf("an unexpired lock of a terminated holder: %v", err)
+ }
+ if got := oracle.calls(); len(got) != 0 {
+ t.Fatalf("OwnerTerminated was asked about %v for an unexpired lock", got)
+ }
+ if lockWrites(t, b, rt) != 0 || !bytes.Equal(lockBodyOf(b, rt), body) {
+ t.Fatal("the held wake wrote the lock")
+ }
+}
+
+// A describe that fails proves nothing: the wake is refused, the lock
+// stays b's, and the refusal is logged once a minute, not once a wake.
+func TestTakeoverDescribeFailureKeepsHostDown(t *testing.T) {
+ ctx := context.Background()
+ logs := captureLog(t)
+ oracle := &terminatedOracle{err: errors.New("RequestLimitExceeded")}
+ b, rt, body := takeoverBackend(t, time.Now().Add(-time.Minute), oracle)
+ for range 3 {
+ _, err := b.Acquire(ctx, rt)
+ var refused *errLeaseRefused
+ if !errors.As(err, &refused) || !strings.Contains(refused.reason, hafresh.ReasonOtherExpired) {
+ t.Fatalf("a failed describe: %v", err)
+ }
+ }
+ if lockWrites(t, b, rt) != 0 || !bytes.Equal(lockBodyOf(b, rt), body) {
+ t.Fatal("the refused wake wrote the lock")
+ }
+ if n := strings.Count(logs.String(), "RequestLimitExceeded (the host stays down"); n != 1 {
+ t.Fatalf("the describe failure was logged %d times in three wakes, want 1:\n%s", n, logs)
+ }
+ if strings.Contains(logs.String(), "taking the host over") {
+ t.Fatalf("a failed describe logged a takeover:\n%s", logs)
+ }
+}
+
+// Without the oracle (P1a's wiring), another box's expired lock is never
+// taken.
+func TestNoTakeoverWithoutTheOracle(t *testing.T) {
+ ctx := context.Background()
+ b, rt, body := takeoverBackend(t, time.Now().Add(-time.Minute), nil)
+ if b.ownerTerminated(ctx, rt) != nil {
+ t.Fatal("a proof was built with no OwnerTerminated wired")
+ }
+ _, err := b.Acquire(ctx, rt)
+ var refused *errLeaseRefused
+ if !errors.As(err, &refused) || refused.reason != hafresh.ReasonOtherExpired {
+ t.Fatalf("an expired lock of another box with no oracle: %v", err)
+ }
+ if lockWrites(t, b, rt) != 0 || !bytes.Equal(lockBodyOf(b, rt), body) {
+ t.Fatal("the refused wake wrote the lock")
+ }
+}
diff --git a/internal/activator/hawake.go b/internal/activator/hawake.go
index a779944d0..b643dd40e 100644
--- a/internal/activator/hawake.go
+++ b/internal/activator/hawake.go
@@ -314,7 +314,7 @@ func (b *ExecBackend) acquireClassified(ctx context.Context, rt registry.Route)
if err := b.haContained(rt); err != nil {
return nil, refusedUncontained(err)
}
- proofs := hafresh.Proofs{SameBoxEmpty: b.sameBoxEmpty(ctx, rt)}
+ proofs := hafresh.Proofs{SameBoxEmpty: b.sameBoxEmpty(ctx, rt), OwnerTerminated: b.ownerTerminated(ctx, rt)}
held, err := acquireHALease(ctx, b.Cfg.Bucket, prefix, b.Cfg.Region, hafresh.Marker{Lifetime: entry.ID}, proofs)
if err != nil {
return nil, leaseError(err)
diff --git a/internal/activator/hawake_test.go b/internal/activator/hawake_test.go
index fd117bd22..ccccc1e58 100644
--- a/internal/activator/hawake_test.go
+++ b/internal/activator/hawake_test.go
@@ -72,7 +72,7 @@ func haBackendEmptyIndex(t *testing.T, host string) (*ExecBackend, registry.Rout
if err := lease.SetObligationDir(t.TempDir()); err != nil {
t.Fatal(err)
}
- lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a"})
+ lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a", Account: "111122223333", Region: "eu-west-1"})
root := t.TempDir()
b := testExecBackend(t)
b.Cfg.Bucket = fx.Bucket
@@ -884,7 +884,7 @@ func TestLeaseRefusedAnswers503RetryAfter10(t *testing.T) {
// obligation store) go back as they were once its test ends.
func TestHAFixtureRestoresLeaseGlobals(t *testing.T) {
defer lease.ProcessStateForTest()()
- lease.SetSelf(hafresh.Self{Ref: "outer", IID: "i-outer"})
+ lease.SetSelf(hafresh.Self{Ref: "outer", IID: "i-outer", Account: "111122223333", Region: "eu-west-1"})
t.Run("fixture", func(t *testing.T) {
haBackend(t, "shop.example.com")
if got := lease.CurrentSelf(); got.Ref != "a" {
diff --git a/internal/hafresh/acquire.go b/internal/hafresh/acquire.go
index 2c59ab1cd..b3382f9e2 100644
--- a/internal/hafresh/acquire.go
+++ b/internal/hafresh/acquire.go
@@ -36,7 +36,13 @@ type Decision struct {
// Proofs are the facts DecideAcquire cannot read from the lock.
// SameBoxEmpty proves that nothing of the host still runs on this box
// (Task 12); nil, false or an error refuses the same-box takeover.
-type Proofs struct{ SameBoxEmpty func() (bool, error) }
+// OwnerTerminated asks the cloud whether the instance id is confirmed
+// terminated (a stopped or unknown instance is not); nil, false or an
+// error refuses the takeover of another box's expired lock.
+type Proofs struct {
+ SameBoxEmpty func() (bool, error)
+ OwnerTerminated func(iid string) (bool, error)
+}
// Refusal reasons, matched by callers and tests.
const (
@@ -46,6 +52,8 @@ const (
ReasonBadMarker = "malformed release marker"
ReasonSameBoxUnsure = "same box without emptiness proof"
ReasonOtherExpired = "another box's expired lease"
+ ReasonSameBox = "same box, proven empty"
+ ReasonTerminated = "holder terminated"
)
// DecideAcquire is the HA acquire's one table (I1), for HA hosts only:
@@ -56,8 +64,11 @@ const (
// - an unexpired HA owner: held, by that owner;
// - expired, owned by this box's non-empty instance id: take only with
// the same-box emptiness proof, else refuse;
-// - expired, any other box: refuse. Expiry alone never hands an HA lock
-// to another box.
+// - expired, owned by another box's non-empty instance id: take only
+// when the cloud confirms that instance terminated, else refuse.
+// Expiry alone never hands an HA lock to another box, and a
+// terminated owner's lock is not taken before it expires (N-HA9);
+// - expired, owned by a box with no instance id: refuse.
func DecideAcquire(v View, self Self, now time.Time, p Proofs) Decision {
if v.Absent {
return Decision{ActCreate, ReasonAbsent}
@@ -76,9 +87,12 @@ func DecideAcquire(v View, self Self, now time.Time, p Proofs) Decision {
if !now.After(v.Lock.ExpiresAt) {
return Decision{ActHeld, v.Lock.Owner}
}
- if self.IID == "" || o.IID != self.IID {
+ if o.IID == "" {
return Decision{ActRefuse, ReasonOtherExpired}
}
+ if o.IID != self.IID {
+ return decideOtherExpired(o, p)
+ }
if p.SameBoxEmpty == nil {
return Decision{ActRefuse, ReasonSameBoxUnsure}
}
@@ -89,5 +103,21 @@ func DecideAcquire(v View, self Self, now time.Time, p Proofs) Decision {
if !empty {
return Decision{ActRefuse, ReasonSameBoxUnsure}
}
- return Decision{ActTake, "same box, proven empty"}
+ return Decision{ActTake, ReasonSameBox}
+}
+
+// decideOtherExpired is the row for an expired lock of another box's
+// non-empty instance id.
+func decideOtherExpired(o Owner, p Proofs) Decision {
+ if p.OwnerTerminated == nil {
+ return Decision{ActRefuse, ReasonOtherExpired}
+ }
+ gone, err := p.OwnerTerminated(o.IID)
+ if err != nil {
+ return Decision{ActRefuse, ReasonOtherExpired + ": " + err.Error()}
+ }
+ if !gone {
+ return Decision{ActRefuse, ReasonOtherExpired}
+ }
+ return Decision{ActTake, ReasonTerminated}
}
diff --git a/internal/hafresh/acquire_test.go b/internal/hafresh/acquire_test.go
index dc9e8a076..8a5e51356 100644
--- a/internal/hafresh/acquire_test.go
+++ b/internal/hafresh/acquire_test.go
@@ -12,10 +12,13 @@ func TestDecideAcquireTable(t *testing.T) {
now := time.Unix(1_800_000_000, 0)
self := Self{Ref: "a", IID: "i-a"}
exp := now.Add(-time.Minute)
- other, mine := OwnerFor(Self{"b", "i-b"}, 9, true), OwnerFor(self, 9, true)
+ other, mine := OwnerFor(Self{Ref: "b", IID: "i-b"}, 9, true), OwnerFor(self, 9, true)
yes := Proofs{SameBoxEmpty: func() (bool, error) { return true, nil }}
no := Proofs{SameBoxEmpty: func() (bool, error) { return false, nil }}
broken := Proofs{SameBoxEmpty: func() (bool, error) { return true, errors.New("cgroup unreadable") }}
+ terminated := Proofs{OwnerTerminated: func(string) (bool, error) { return true, nil }}
+ terminatedErr := Proofs{OwnerTerminated: func(string) (bool, error) { return true, errors.New("ec2 unreachable") }}
+ noIIDOther := OwnerFor(Self{Ref: "c"}, 9, true)
for i, c := range []struct {
v View
p Proofs
@@ -38,6 +41,12 @@ func TestDecideAcquireTable(t *testing.T) {
{View{Lock: Lock{ExpiresAt: exp, Owner: OwnerFor(self, 9, false)}}, yes, ActRefuse},
{View{Lock: Lock{ExpiresAt: exp, Owner: "released/v1;ref=b"}}, yes, ActRefuse},
{View{Lock: Lock{ExpiresAt: exp, Owner: other}}, Proofs{}, ActRefuse},
+ // Another box's lock, EC2 confirming it terminated: taken only
+ // once expired; a failed confirmation or an iid-less owner refuses.
+ {View{Lock: Lock{ExpiresAt: exp, Owner: other}}, terminated, ActTake},
+ {View{Lock: Lock{ExpiresAt: now.Add(time.Minute), Owner: other}}, terminated, ActHeld},
+ {View{Lock: Lock{ExpiresAt: exp, Owner: other}}, terminatedErr, ActRefuse},
+ {View{Lock: Lock{ExpiresAt: exp, Owner: noIIDOther}}, terminated, ActRefuse},
} {
if got := DecideAcquire(c.v, self, now, c.p).Action; got != c.want {
t.Errorf("case %d: %v, want %v", i, got, c.want)
@@ -53,11 +62,16 @@ func TestDecideAcquireTable(t *testing.T) {
{View{Lock: Lock{ExpiresAt: exp, Owner: other}}, yes, ReasonOtherExpired},
{View{Lock: Lock{ExpiresAt: exp, Owner: mine}}, Proofs{}, ReasonSameBoxUnsure},
{View{Lock: Lock{ExpiresAt: now.Add(time.Minute), Owner: other}}, Proofs{}, other},
+ {View{Lock: Lock{ExpiresAt: exp, Owner: other}}, terminated, ReasonTerminated},
+ {View{Lock: Lock{ExpiresAt: exp, Owner: mine}}, yes, ReasonSameBox},
} {
if got := DecideAcquire(c.v, self, now, c.p).Reason; got != c.want {
t.Errorf("reason %q, want %q", got, c.want)
}
}
+ if got := DecideAcquire(View{Lock: Lock{ExpiresAt: exp, Owner: other}}, self, now, terminatedErr).Reason; !strings.HasPrefix(got, ReasonOtherExpired+": ") {
+ t.Fatalf("terminated-proof error reason %q", got)
+ }
// A box whose instance id is still unknown never proves itself the
// owner of an expired lock, even one with no iid either.
noIID := OwnerFor(Self{Ref: "a"}, 9, true)
@@ -66,6 +80,63 @@ func TestDecideAcquireTable(t *testing.T) {
}
}
+func TestDecideAcquireReasons(t *testing.T) {
+ now := time.Unix(1_800_000_000, 0)
+ self := Self{Ref: "a", IID: "i-a"}
+ v := View{Lock: Lock{ExpiresAt: now.Add(-time.Minute), Owner: OwnerFor(Self{Ref: "b", IID: "i-b"}, 9, true)}}
+ d := DecideAcquire(v, self, now, Proofs{OwnerTerminated: func(string) (bool, error) { return true, nil }})
+ if d.Action != ActTake || d.Reason != ReasonTerminated {
+ t.Fatalf("terminated take: %+v", d)
+ }
+ d = DecideAcquire(v, self, now, Proofs{OwnerTerminated: func(string) (bool, error) { return false, errors.New("throttled") }})
+ if d.Action != ActRefuse || d.Reason != ReasonOtherExpired+": throttled" {
+ t.Fatalf("proof error: %+v", d)
+ }
+}
+
+// Each proof is asked only about the lock it can speak to.
+func TestDecideAcquireProofScope(t *testing.T) {
+ now := time.Unix(1_800_000_000, 0)
+ self := Self{Ref: "a", IID: "i-a"}
+ exp, live := now.Add(-time.Minute), now.Add(time.Minute)
+ b, mine := OwnerFor(Self{Ref: "b", IID: "i-b"}, 9, true), OwnerFor(self, 9, true)
+ noIID := OwnerFor(Self{Ref: "c"}, 9, true)
+ for _, c := range []struct {
+ name string
+ lock Lock
+ wantTerm []string
+ wantSameBox int
+ }{
+ {"expired other", Lock{ExpiresAt: exp, Owner: b}, []string{"i-b"}, 0},
+ {"unexpired other", Lock{ExpiresAt: live, Owner: b}, nil, 0},
+ {"unexpired mine", Lock{ExpiresAt: live, Owner: mine}, nil, 0},
+ {"expired mine", Lock{ExpiresAt: exp, Owner: mine}, nil, 1},
+ {"expired iid-less owner", Lock{ExpiresAt: exp, Owner: noIID}, nil, 0},
+ } {
+ var term []string
+ same := 0
+ p := Proofs{
+ SameBoxEmpty: func() (bool, error) { same++; return true, nil },
+ OwnerTerminated: func(iid string) (bool, error) { term = append(term, iid); return true, nil },
+ }
+ DecideAcquire(View{Lock: c.lock}, self, now, p)
+ if strings.Join(term, ",") != strings.Join(c.wantTerm, ",") || same != c.wantSameBox {
+ t.Errorf("%s: OwnerTerminated calls %v, SameBoxEmpty calls %d; want %v, %d", c.name, term, same, c.wantTerm, c.wantSameBox)
+ }
+ }
+}
+
+// A stopped box is not a terminated one: EC2 answering false leaves the
+// lock to its owner.
+func TestDecideAcquireStoppedOwnerIsNotTaken(t *testing.T) {
+ now := time.Unix(1_800_000_000, 0)
+ v := View{Lock: Lock{ExpiresAt: now.Add(-time.Minute), Owner: OwnerFor(Self{Ref: "b", IID: "i-b"}, 9, true)}}
+ d := DecideAcquire(v, Self{Ref: "a", IID: "i-a"}, now, Proofs{OwnerTerminated: func(string) (bool, error) { return false, nil }})
+ if d.Action != ActRefuse || d.Reason != ReasonOtherExpired {
+ t.Fatalf("%+v", d)
+ }
+}
+
func TestMarkerBodyFormat(t *testing.T) {
at := time.Date(2026, 10, 26, 12, 0, 0, 0, time.UTC)
body, err := MarkerBody(7, Marker{V: 1, Box: "a", IID: "i-a", Lifetime: "L1", TXID: 12, FilesGen: "3:ab", At: at, Clean: true})
diff --git a/internal/hafresh/owner.go b/internal/hafresh/owner.go
index 516fe1ab1..22a7c657b 100644
--- a/internal/hafresh/owner.go
+++ b/internal/hafresh/owner.go
@@ -9,8 +9,15 @@ import (
)
// Self is this box's identity as a lease owner: its reference (the label
-// it publishes metrics under) and its cloud instance id, "" until known.
-type Self struct{ Ref, IID string }
+// it publishes metrics under), its cloud instance id ("" until known),
+// and the cloud account and region it runs in. OwnerFor writes only the
+// reference and the instance id.
+type Self struct{ Ref, IID, Account, Region string }
+
+// Complete reports whether all four fields are known.
+func (s Self) Complete() bool {
+ return s.Ref != "" && s.IID != "" && s.Account != "" && s.Region != ""
+}
// Owner is a parsed owner string.
type Owner struct {
diff --git a/internal/hafresh/owner_test.go b/internal/hafresh/owner_test.go
index 49750575b..c5fc0a50f 100644
--- a/internal/hafresh/owner_test.go
+++ b/internal/hafresh/owner_test.go
@@ -54,3 +54,20 @@ func TestParseOwnerIsStrict(t *testing.T) {
}
}
}
+
+func TestSelfComplete(t *testing.T) {
+ full := hafresh.Self{Ref: "a", IID: "i-a", Account: "123456789012", Region: "eu-west-2"}
+ if !full.Complete() {
+ t.Fatal("all four fields set is incomplete")
+ }
+ for name, s := range map[string]hafresh.Self{
+ "ref": {IID: "i-a", Account: "123456789012", Region: "eu-west-2"},
+ "iid": {Ref: "a", Account: "123456789012", Region: "eu-west-2"},
+ "account": {Ref: "a", IID: "i-a", Region: "eu-west-2"},
+ "region": {Ref: "a", IID: "i-a", Account: "123456789012"},
+ } {
+ if s.Complete() {
+ t.Errorf("without %s: complete", name)
+ }
+ }
+}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index cb6cb3528..8297dfac9 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -223,15 +223,14 @@ func dataDir() string {
// Before it starts, a box its region's group launched resolves its group
// reference, whatever the switches say: the loops runAgent starts read
// the box's label once and keep it (agentEntry, agententry.go). Then it
-// names the box as the owner of the lease locks it writes; an instance id
-// IMDS did not answer within 2 seconds is asked for again every minute.
+// names the box as the owner of the lease locks it writes; an instance id,
+// account or region IMDS did not answer within 2 seconds is asked for
+// again every minute.
func RunAgent(args []string) {
var self hafresh.Self
identity := func() hafresh.Self { self = haSelfNow(os.Getenv, haIMDSClient); return self }
agentEntry(os.Getenv, resolveGroupBoxReference, groupReferenceBackoff, log.Printf, identity, func() {
- if self.IID == "" {
- go haSelfRetry(context.Background(), os.Getenv, haIMDSClient, time.Minute, lease.SetSelf)
- }
+ startHASelfRetry(context.Background(), self, os.Getenv, haIMDSClient, time.Minute, lease.SetSelf)
runAgent(args, productionClaimFactory)
})
}
@@ -474,6 +473,10 @@ func runAgent(args []string, buildClaims ClaimFactory) {
eb.Lifetimes = boxLifetimes
eb.Registry = reg
eb.StartupSwept = seedSweptAtStart.Load
+ // Region HA P1b-1: the takeover of a host whose holder box is
+ // terminated and whose lease expired asks EC2 through one oracle.
+ confirmer := haOwnerConfirmer()
+ eb.OwnerTerminated = confirmer.Terminated
if fs, err := newProductionFilesStore(agentCtx, cfg.Bucket, cfg.Region); err != nil {
log.Printf("agent: region HA: files store: %v (every HA restore that needs it fails)", err)
} else {
diff --git a/internal/host/haself.go b/internal/host/haself.go
index bb9f73dca..71930b2ac 100644
--- a/internal/host/haself.go
+++ b/internal/host/haself.go
@@ -18,19 +18,30 @@ import (
var haIMDSClient = &http.Client{Timeout: haIdentityRead}
// haSelfNow is this box's identity as a lease owner (lease.SetSelf): its
-// reference is the label it publishes metrics under, and its instance id
-// comes from one identity-document read, given 2 seconds, "" when that
-// read fails.
+// reference is the label it publishes metrics under, and its instance id,
+// account and region come from one identity-document read, given 2
+// seconds, "" when that read fails (or the document lacks one).
// agentEntry calls it after the group-reference wait, so a group box's
// label is its resolved group reference.
func haSelfNow(getenv func(string) string, client *http.Client) hafresh.Self {
- iid, _ := readInstanceID(client, imdsBase)
- return hafresh.Self{Ref: metricsBoxLabel(getenv, readMachineID()), IID: iid}
+ iid, account, region, _ := readIdentity(client, imdsBase)
+ return hafresh.Self{Ref: metricsBoxLabel(getenv, readMachineID()), IID: iid, Account: account, Region: region}
}
-// haSelfRetry asks again, every tick, for an instance id the startup read
-// missed, and hands the identity to set once it has one. It returns then,
-// or when ctx ends.
+// startHASelfRetry is RunAgent's rule for the retry: a startup identity
+// that is not Complete starts haSelfRetry, in its own goroutine, and a
+// complete one starts nothing. It reports whether it started.
+func startHASelfRetry(ctx context.Context, startup hafresh.Self, getenv func(string) string, client *http.Client, every time.Duration, set func(hafresh.Self)) bool {
+ if startup.Complete() {
+ return false
+ }
+ go haSelfRetry(ctx, getenv, client, every, set)
+ return true
+}
+
+// haSelfRetry asks again, every tick, for an identity the startup read
+// missed or only half got, and hands it to set once it is Complete. It
+// returns then, or when ctx ends.
func haSelfRetry(ctx context.Context, getenv func(string) string, client *http.Client, every time.Duration, set func(hafresh.Self)) {
t := time.NewTicker(every)
defer t.Stop()
@@ -40,19 +51,20 @@ func haSelfRetry(ctx context.Context, getenv func(string) string, client *http.C
return
case <-t.C:
}
- if s := haSelfNow(getenv, client); s.IID != "" {
+ if s := haSelfNow(getenv, client); s.Complete() {
set(s)
return
}
}
}
-// haIdentityRead is the whole of one instance-id read: token and document.
+// haIdentityRead is the whole of one identity read: token and document.
const haIdentityRead = 2 * time.Second
-// readInstanceID reads the instance id from the identity document (IMDSv2),
-// the token and the document together within haIdentityRead.
-func readInstanceID(client *http.Client, base string) (string, error) {
+// readIdentity reads the instance id, account id and region from the
+// identity document (IMDSv2), the token and the document together within
+// haIdentityRead. A field the document lacks comes back "".
+func readIdentity(client *http.Client, base string) (iid, account, region string, err error) {
ctx, cancel := context.WithTimeout(context.Background(), haIdentityRead)
defer cancel()
get := func(method, path string, hdr map[string]string) ([]byte, error) {
@@ -79,21 +91,23 @@ func readInstanceID(client *http.Client, base string) (string, error) {
}
tok, err := get(http.MethodPut, "/latest/api/token", map[string]string{"X-aws-ec2-metadata-token-ttl-seconds": "60"})
if err != nil {
- return "", fmt.Errorf("IMDS token: %w", err)
+ return "", "", "", fmt.Errorf("IMDS token: %w", err)
}
token := strings.TrimSpace(string(tok))
if token == "" {
- return "", fmt.Errorf("IMDS token: empty")
+ return "", "", "", fmt.Errorf("IMDS token: empty")
}
doc, err := get(http.MethodGet, imdsIdentityDocument, map[string]string{"X-aws-ec2-metadata-token": token})
if err != nil {
- return "", err
+ return "", "", "", err
}
var d struct {
InstanceID string `json:"instanceId"`
+ AccountID string `json:"accountId"`
+ Region string `json:"region"`
}
if err := json.Unmarshal(doc, &d); err != nil {
- return "", fmt.Errorf("IMDS identity document: %w", err)
+ return "", "", "", fmt.Errorf("IMDS identity document: %w", err)
}
- return strings.TrimSpace(d.InstanceID), nil
+ return strings.TrimSpace(d.InstanceID), strings.TrimSpace(d.AccountID), strings.TrimSpace(d.Region), nil
}
diff --git a/internal/host/haself_test.go b/internal/host/haself_test.go
index 1b422d63a..771cebf81 100644
--- a/internal/host/haself_test.go
+++ b/internal/host/haself_test.go
@@ -33,13 +33,13 @@ func TestAgentEntrySetsOwnerBeforeRun(t *testing.T) {
}
}
-// The box's reference is its metrics label; its instance id comes from one
-// identity-document read, "" when that read fails.
+// The box's reference is its metrics label; its instance id, account and
+// region come from one identity-document read, "" when that read fails.
func TestHASelfNowNamesTheBox(t *testing.T) {
- f := &fakeIMDS{doc: `{"accountId":"123456789012","instanceId":"i-0a61f580df1acfa65"}`}
+ f := &fakeIMDS{doc: `{"accountId":"111122223333","instanceId":"i-0a61f580df1acfa65","region":"eu-west-1"}`}
getenv := envOf(map[string]string{"CARLOS_FLEET": "pi", "CARLOS_FLEET_BOX": "pi-box"})
want := metricsBoxLabel(getenv, readMachineID())
- if got := haSelfNow(getenv, imdsClient(f)); got != (hafresh.Self{Ref: want, IID: "i-0a61f580df1acfa65"}) ||
+ if got := haSelfNow(getenv, imdsClient(f)); got != (hafresh.Self{Ref: want, IID: "i-0a61f580df1acfa65", Account: "111122223333", Region: "eu-west-1"}) ||
!slices.Equal(f.calls, []string{"PUT /latest/api/token", "GET " + imdsIdentityDocument}) {
t.Fatalf("%+v after %q, want ref %q", got, f.calls, want)
}
@@ -70,7 +70,7 @@ func (f *failingFor) RoundTrip(r *http.Request) (*http.Response, error) {
// until it answers, then set once, with the reference; the retry ends
// there, or when its context does.
func TestHASelfRetrySetsALateInstanceID(t *testing.T) {
- f := &failingFor{fakeIMDS: &fakeIMDS{doc: `{"instanceId":"i-0abc"}`}, n: 2}
+ f := &failingFor{fakeIMDS: &fakeIMDS{doc: `{"accountId":"111122223333","instanceId":"i-0abc","region":"eu-west-1"}`}, n: 2}
getenv := envOf(map[string]string{"CARLOS_FLEET": "pi", "CARLOS_FLEET_BOX": "pi-box"})
var set []hafresh.Self
done := make(chan struct{})
@@ -83,7 +83,7 @@ func TestHASelfRetrySetsALateInstanceID(t *testing.T) {
case <-time.After(10 * time.Second):
t.Fatal("the retry never ended")
}
- if want := (hafresh.Self{Ref: metricsBoxLabel(getenv, readMachineID()), IID: "i-0abc"}); len(set) != 1 || set[0] != want || len(f.calls) != 6 {
+ if want := (hafresh.Self{Ref: metricsBoxLabel(getenv, readMachineID()), IID: "i-0abc", Account: "111122223333", Region: "eu-west-1"}); len(set) != 1 || set[0] != want || len(f.calls) != 6 {
t.Fatalf("set %+v after %d requests, want once %+v after 3 reads", set, len(f.calls), want)
}
@@ -91,3 +91,73 @@ func TestHASelfRetrySetsALateInstanceID(t *testing.T) {
cancel()
haSelfRetry(ctx, getenv, imdsClient(&fakeIMDS{status: 500}), time.Hour, func(hafresh.Self) { t.Fatal("set with no instance id") })
}
+
+// docSwitch serves a document that changes between reads.
+type docSwitch struct {
+ *fakeIMDS
+ docs []string // the document each read gets; the last one repeats
+ read int
+}
+
+func (d *docSwitch) RoundTrip(r *http.Request) (*http.Response, error) {
+ if r.URL.Path == imdsIdentityDocument {
+ d.fakeIMDS.doc = d.docs[min(d.read, len(d.docs)-1)]
+ d.read++
+ }
+ return d.fakeIMDS.RoundTrip(r)
+}
+
+// A document with an instance id but no region is not an identity yet:
+// the retry waits for the tick that brings all of it, and sets it once.
+func TestHASelfRetryWaitsForTheWholeIdentity(t *testing.T) {
+ d := &docSwitch{fakeIMDS: &fakeIMDS{}, docs: []string{
+ `{"accountId":"111122223333","instanceId":"i-0abc"}`,
+ `{"accountId":"111122223333","instanceId":"i-0abc"}`,
+ `{"accountId":"111122223333","instanceId":"i-0abc","region":"eu-west-1"}`,
+ }}
+ getenv := envOf(map[string]string{"CARLOS_FLEET": "pi", "CARLOS_FLEET_BOX": "pi-box"})
+ var set []hafresh.Self
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ haSelfRetry(context.Background(), getenv, &http.Client{Transport: d}, time.Millisecond, func(s hafresh.Self) { set = append(set, s) })
+ }()
+ select {
+ case <-done:
+ case <-time.After(10 * time.Second):
+ t.Fatal("the retry never ended")
+ }
+ want := hafresh.Self{Ref: metricsBoxLabel(getenv, readMachineID()), IID: "i-0abc", Account: "111122223333", Region: "eu-west-1"}
+ if len(set) != 1 || set[0] != want || d.read != 3 {
+ t.Fatalf("set %+v after %d document reads, want once %+v after 3", set, d.read, want)
+ }
+}
+
+// The production entry (the code RunAgent runs once the group reference
+// is resolved): a startup identity with an instance id but no region
+// starts the retry, and a later complete document reaches the lease
+// identity. A complete startup identity starts nothing.
+func TestAgentRetriesAPartialIdentity(t *testing.T) {
+ t.Cleanup(func() { lease.SetSelf(hafresh.Self{}) })
+ getenv := envOf(map[string]string{"CARLOS_FLEET": "pi", "CARLOS_FLEET_BOX": "pi-box"})
+ ref := metricsBoxLabel(getenv, readMachineID())
+ partial := hafresh.Self{Ref: ref, IID: "i-0abc", Account: "111122223333"}
+ d := &docSwitch{fakeIMDS: &fakeIMDS{}, docs: []string{`{"accountId":"111122223333","instanceId":"i-0abc","region":"eu-west-1"}`}}
+ lease.SetSelf(partial)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ if !startHASelfRetry(ctx, partial, getenv, &http.Client{Transport: d}, time.Millisecond, lease.SetSelf) {
+ t.Fatal("a partial identity did not start the retry")
+ }
+ want := hafresh.Self{Ref: ref, IID: "i-0abc", Account: "111122223333", Region: "eu-west-1"}
+ deadline := time.Now().Add(10 * time.Second)
+ for lease.CurrentSelf() != want {
+ if time.Now().After(deadline) {
+ t.Fatalf("the lease identity stayed %+v, want %+v", lease.CurrentSelf(), want)
+ }
+ time.Sleep(time.Millisecond)
+ }
+ if startHASelfRetry(ctx, want, getenv, &http.Client{Transport: d}, time.Hour, lease.SetSelf) {
+ t.Fatal("a complete identity started the retry")
+ }
+}
diff --git a/internal/host/hatakeover.go b/internal/host/hatakeover.go
new file mode 100644
index 000000000..701901fe8
--- /dev/null
+++ b/internal/host/hatakeover.go
@@ -0,0 +1,50 @@
+package host
+
+import (
+ "context"
+
+ awsconfig "github.com/aws/aws-sdk-go-v2/config"
+ "github.com/aws/aws-sdk-go-v2/service/ec2"
+
+ "github.com/carlosframework/platform/internal/boxid"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/rootaws"
+ "github.com/carlosframework/platform/internal/termfence"
+)
+
+// haOwnerConfirmer is the box's one termination oracle for Region HA
+// takeovers (activator.ExecBackend.OwnerTerminated): it asks EC2, in this
+// box's own account and region, whether another box's instance is
+// terminated. Its identity is the lease's, read at each call, because the
+// box's identity can arrive after the backend is built; until it is
+// complete every answer is an error and no client is built. Every box
+// gets one; only an HA host's wake ever asks it.
+func haOwnerConfirmer() *termfence.Confirmer {
+ return &termfence.Confirmer{API: haTakeoverEC2, Self: haCloudSelf}
+}
+
+// haCloudSelf is the lease's identity as a cloud identity.
+func haCloudSelf() boxid.Cloud {
+ s := lease.CurrentSelf()
+ return boxid.Cloud{Provider: "aws", Account: s.Account, Region: s.Region, InstanceID: s.IID}
+}
+
+// haTakeoverEC2 builds the oracle's EC2 client for region, through root's
+// AWS loader. The SDK's own retries are off: the confirmer's ten-second
+// negative cache is the only retry, so one call is one request.
+func haTakeoverEC2(ctx context.Context, region string) (termfence.EC2, error) {
+ cfg, err := rootaws.LoadDefaultConfig(ctx, awsconfig.WithRegion(region), awsconfig.WithRetryMaxAttempts(1))
+ if err != nil {
+ return nil, err
+ }
+ return describeInstances(ec2.NewFromConfig(cfg).DescribeInstances), nil
+}
+
+// describeInstances is termfence.EC2 from one method value. A *ec2.Client
+// stored in an interface keeps every EC2 method in the binary (see
+// awsinv.factoryFor, discussion #275); a method value keeps one.
+type describeInstances func(context.Context, *ec2.DescribeInstancesInput, ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error)
+
+func (f describeInstances) DescribeInstances(ctx context.Context, in *ec2.DescribeInstancesInput, opts ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error) {
+ return f(ctx, in, opts...)
+}
diff --git a/internal/host/hatakeover_wiring_test.go b/internal/host/hatakeover_wiring_test.go
new file mode 100644
index 000000000..15d522cf4
--- /dev/null
+++ b/internal/host/hatakeover_wiring_test.go
@@ -0,0 +1,105 @@
+package host
+
+import (
+ "context"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/boxid"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/termfence"
+)
+
+// RunAgent builds one termination oracle and hands it to the backend
+// before the Service starts (syntactic, like TestAgentWiresTheHAWake).
+func TestAgentWiresTheTakeoverOracle(t *testing.T) {
+ src, err := os.ReadFile("agent.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ body := string(src)
+ start := strings.Index(body, "Start: svc.Start,")
+ built := strings.Index(body, "confirmer := haOwnerConfirmer()")
+ wired := strings.Index(body, "eb.OwnerTerminated = confirmer.Terminated")
+ if start < 0 || built < 0 || wired < built || wired > start {
+ t.Fatalf("the takeover oracle is not built and wired before the Service starts (built %d, wired %d, start %d)", built, wired, start)
+ }
+ if strings.Count(body, "haOwnerConfirmer()") != 1 {
+ t.Fatal("more than one termination oracle is built")
+ }
+}
+
+// The oracle's identity is the lease's, read at each call: an identity
+// that arrives after the backend is built is the one it asks with, and
+// before it arrives every answer is an error, with no EC2 client built.
+func TestHAOwnerConfirmerReadsTheLateIdentity(t *testing.T) {
+ t.Cleanup(lease.ProcessStateForTest())
+ c := haOwnerConfirmer()
+ built := 0
+ c.API = func(context.Context, string) (termfence.EC2, error) { built++; return nil, os.ErrNotExist }
+ lease.SetSelf(hafresh.Self{Ref: "a"})
+ if got := c.Self(); got.Complete() {
+ t.Fatalf("an incomplete lease identity read as %+v", got)
+ }
+ if yes, err := c.Terminated(context.Background(), "i-b"); yes || err == nil || built != 0 {
+ t.Fatalf("before the identity: %v, %v, %d clients built", yes, err, built)
+ }
+ lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a", Account: "111122223333", Region: "eu-west-1"})
+ want := boxid.Cloud{Provider: "aws", Account: "111122223333", Region: "eu-west-1", InstanceID: "i-a"}
+ if got := c.Self(); got != want {
+ t.Fatalf("the oracle's identity is %+v, want %+v", got, want)
+ }
+ if got := haOwnerConfirmer(); got.API == nil {
+ t.Fatal("no EC2 client builder")
+ }
+}
+
+// The oracle's describe is one HTTP request, not the SDK's three: the
+// confirmer's ten-second negative cache is the only retry. The client is the
+// production-built one, aimed at a server that answers 503.
+func TestHAOwnerConfirmerDescribeIsOneRequest(t *testing.T) {
+ t.Cleanup(lease.ProcessStateForTest())
+ var requests atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests.Add(1)
+ w.WriteHeader(http.StatusServiceUnavailable)
+ io.WriteString(w, `<Response><Errors><Error><Code>RequestLimitExceeded</Code><Message>slow down</Message></Error></Errors><RequestID>req-1</RequestID></Response>`)
+ }))
+ defer srv.Close()
+ t.Setenv("AWS_ENDPOINT_URL_EC2", srv.URL)
+ t.Setenv("AWS_ACCESS_KEY_ID", "AKIDEXAMPLE")
+ t.Setenv("AWS_SECRET_ACCESS_KEY", "secret")
+ t.Setenv("AWS_SESSION_TOKEN", "")
+ t.Setenv("AWS_PROFILE", "")
+ t.Setenv("AWS_EC2_METADATA_DISABLED", "true")
+ lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a", Account: "111122223333", Region: "eu-west-1"})
+
+ now := time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC)
+ c := haOwnerConfirmer()
+ c.Now = func() time.Time { return now }
+ c.Logf = func(string, ...any) {}
+
+ if yes, err := c.Terminated(context.Background(), "i-b"); yes || err == nil {
+ t.Fatalf("a throttled describe answered %v, %v", yes, err)
+ }
+ if got := requests.Load(); got != 1 {
+ t.Fatalf("the first call made %d requests, want 1 (the SDK retried)", got)
+ }
+ now = now.Add(termfence.ConfirmNegativeTTL - time.Second)
+ c.Terminated(context.Background(), "i-b")
+ if got := requests.Load(); got != 1 {
+ t.Fatalf("inside the negative cache: %d requests, want 1", got)
+ }
+ now = now.Add(2 * time.Second)
+ c.Terminated(context.Background(), "i-b")
+ if got := requests.Load(); got != 2 {
+ t.Fatalf("after the negative cache: %d requests, want 2", got)
+ }
+}
diff --git a/internal/lease/ha.go b/internal/lease/ha.go
index 9ab131d86..a72a42e15 100644
--- a/internal/lease/ha.go
+++ b/internal/lease/ha.go
@@ -27,9 +27,10 @@ func (e *RefusedError) Error() string { return "lease: HA acquire refused: " + e
// prefix already holds something.
const ReasonLeftoverData = "leftover data"
-// ErrNoSelf refuses an HA acquire before SetSelf: an HA lock's owner must
-// name the box.
-var ErrNoSelf = errors.New("lease: no box identity set; HA acquire refused")
+// ErrNoSelf refuses an HA acquire until SetSelf has named the whole box
+// (hafresh.Self.Complete): an HA lock's owner must name it, and a takeover
+// proves it from its account and region.
+var ErrNoSelf = errors.New("lease: this box's identity (reference, instance id, account, region) is not known yet; HA acquire refused")
// AcquireHA is the acquire for HA hosts, and the only one: it never falls
// back to litestream's AcquireLease or to the legacy path.
@@ -39,8 +40,10 @@ var ErrNoSelf = errors.New("lease: no box identity set; HA acquire refused")
// 1. The lock is read with its ETag and classified (hafresh.DecideAcquire).
// 2. Absent: the prefix must be empty (PrefixEmpty), else *RefusedError
// "leftover data"; then a create, If-None-Match: *.
-// 3. A marker, or this box's expired lock with Proofs.SameBoxEmpty: a
-// take, If-Match the ETag classified, generation+1, the HA owner.
+// 3. A marker, this box's expired lock with Proofs.SameBoxEmpty, or
+// another box's expired lock with Proofs.OwnerTerminated: a take,
+// If-Match the ETag classified, generation+1, the HA owner. The log
+// names the rule that won.
// 4. Held: *HeldError. Refused: *RefusedError. Nothing written.
// 5. A lost condition re-reads and reclassifies, at most three rounds.
//
@@ -50,7 +53,8 @@ var ErrNoSelf = errors.New("lease: no box identity set; HA acquire refused")
// id, lifetime) is kept for the handle's unclean releases; an empty box or
// instance id is this box's own.
//
-// The budget: a marker or same-box wake is 1 GET and 1 PUT; a first wake
+// The budget: a marker, same-box or takeover wake is 1 GET and 1 PUT (a
+// takeover's describe is the caller's, not S3's); a first wake
// 1 GET, 1 LIST (max-keys 1) and 1 PUT.
func AcquireHA(ctx context.Context, bucket, prefix, region string, base hafresh.Marker, p hafresh.Proofs) (*Held, error) {
return acquireHATTL(ctx, bucket, prefix, region, base, p, LeaseTTL)
@@ -61,7 +65,7 @@ func acquireHATTL(ctx context.Context, bucket, prefix, region string, base hafre
return nil, ErrNoObligationStore
}
s := self.Load()
- if s == nil || s.Ref == "" {
+ if s == nil || !s.Complete() {
return nil, ErrNoSelf
}
me := *s
@@ -87,8 +91,11 @@ func acquireHATTL(ctx context.Context, bucket, prefix, region string, base hafre
leaser.Path = loc
leaser.TTL = ttl
leaser.Owner = hafresh.OwnerFor(me, os.Getpid(), true) // renewals keep it
+ // won is the last round's decision: the one whose write landed.
+ var won hafresh.Decision
lease, view, started, err := classifyAndTake(ctx, client, bucket, key, leaser.Owner, ttl, func(v hafresh.View) error {
d := hafresh.DecideAcquire(v, me, time.Now(), p)
+ won = d
switch d.Action {
case hafresh.ActCreate:
empty, err := prefixEmpty(ctx, client, bucket, loc)
@@ -126,20 +133,27 @@ func acquireHATTL(ctx context.Context, bucket, prefix, region string, base hafre
defer cancel()
return nil, errors.Join(fmt.Errorf("acquire HA lease: %w", err), releaseWithMarker(relCtx, leaser, region, cur, uncleanMarker(base, 0)))
}
- log.Printf("lease: %s: HA lease acquired in %s (%s)", prefix, time.Since(began).Round(time.Millisecond), viewWord(view))
+ log.Printf("lease: %s: HA lease acquired in %s (%s)", prefix, time.Since(began).Round(time.Millisecond), takeWord(won, view))
return &Held{leaser: leaser, region: region, rn: rn, ha: true, view: view, base: base}, nil
}
-func viewWord(v hafresh.View) string {
- switch {
- case v.Absent:
+// takeWord names the rule that won the take, d, for the acquire's log:
+// the winning round's decision over v, the view it classified.
+func takeWord(d hafresh.Decision, v hafresh.View) string {
+ switch d.Reason {
+ case hafresh.ReasonAbsent:
return "first wake"
- case v.Lock.Release != nil && v.Lock.Release.Clean:
- return "clean marker"
- case v.Lock.Release != nil:
+ case hafresh.ReasonMarker:
+ if v.Lock.Release != nil && v.Lock.Release.Clean {
+ return "clean marker"
+ }
return "unclean marker"
+ case hafresh.ReasonSameBox:
+ return "same-box takeover"
+ case hafresh.ReasonTerminated:
+ return "holder terminated"
}
- return "same-box takeover"
+ return d.Reason
}
// HA reports whether the handle holds an HA lease (AcquireHA).
diff --git a/internal/lease/ha_test.go b/internal/lease/ha_test.go
index d3e9587fa..fff0dde8a 100644
--- a/internal/lease/ha_test.go
+++ b/internal/lease/ha_test.go
@@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"errors"
+ "log"
"net/http"
"os"
"slices"
@@ -46,7 +47,7 @@ func haBox(t *testing.T) string {
t.Helper()
lease.ResetForTest()
t.Cleanup(lease.ResetForTest)
- lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a"})
+ lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a", Account: "111122223333", Region: "eu-west-1"})
dir := t.TempDir()
if err := lease.SetObligationDir(dir); err != nil {
t.Fatal(err)
@@ -184,7 +185,7 @@ func TestAcquireHAFirstWakeRefusesLeftovers(t *testing.T) {
func TestAcquireHARefusesWithoutWriting(t *testing.T) {
haBox(t)
other := hafresh.OwnerFor(hafresh.Self{Ref: "b", IID: "i-b"}, 9, true)
- mine := hafresh.OwnerFor(hafresh.Self{Ref: "a", IID: "i-a"}, 9, true)
+ mine := hafresh.OwnerFor(hafresh.Self{Ref: "a", IID: "i-a", Account: "111122223333", Region: "eu-west-1"}, 9, true)
empty := func(ok bool) hafresh.Proofs {
return hafresh.Proofs{SameBoxEmpty: func() (bool, error) { return ok, nil }}
}
@@ -239,6 +240,28 @@ func TestAcquireHARefusesWithoutSelf(t *testing.T) {
}
}
+// An HA owner names the whole box: a reference alone, or everything but
+// the region, is refused before any request.
+func TestAcquireHARefusesWithoutInstanceID(t *testing.T) {
+ for _, self := range []hafresh.Self{
+ {Ref: "a"},
+ {Ref: "a", IID: "i-a"},
+ {Ref: "a", IID: "i-a", Account: "111122223333"},
+ {Ref: "a", IID: "i-a", Region: "eu-west-1"},
+ } {
+ lease.ResetForTest()
+ lease.SetSelf(self)
+ if err := lease.SetObligationDir(t.TempDir()); err != nil {
+ t.Fatal(err)
+ }
+ fx := leasetest.NewLockFixture(t)
+ if _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}); !errors.Is(err, lease.ErrNoSelf) || len(fx.Requests()) != 0 {
+ t.Fatalf("%+v: %v after %v", self, err, fx.Requests())
+ }
+ }
+ lease.ResetForTest()
+}
+
// r2.1: the PUT lands, its answer arrives past the safe deadline. The
// acquire fails and leaves the lock an unclean marker, never deleted.
func TestAcquireHALateAckWritesUncleanMarker(t *testing.T) {
@@ -326,7 +349,7 @@ func TestLegacyTakeKeepsLegacyLocks(t *testing.T) {
func TestHAAcquireRefusedWithoutObligationStore(t *testing.T) {
lease.ResetForTest()
t.Cleanup(lease.ResetForTest)
- lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a"})
+ lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a", Account: "111122223333", Region: "eu-west-1"})
fx := leasetest.NewLockFixture(t)
if _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}); !errors.Is(err, lease.ErrNoObligationStore) || len(fx.Requests()) != 0 {
t.Fatal(err)
@@ -352,7 +375,7 @@ func TestAcquireCleanupObligationSurvivesRestart(t *testing.T) {
t.Fatalf("not persisted: %v", err)
}
lease.ResetForTest() // a new process
- lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a"})
+ lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a", Account: "111122223333", Region: "eu-west-1"})
if err := lease.SetObligationDir(dir); err != nil || len(lease.PendingObligations()) != 1 {
t.Fatalf("not loaded: %v", err)
}
@@ -396,3 +419,74 @@ func TestAcquireHAWithAFailingObligationReadsNothing(t *testing.T) {
t.Fatal("the obligation was dropped")
}
}
+
+// lockedLog is the standard logger's output, for one test.
+type lockedLog struct {
+ mu sync.Mutex
+ b strings.Builder
+}
+
+func (l *lockedLog) Write(p []byte) (int, error) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return l.b.Write(p)
+}
+
+func (l *lockedLog) String() string { l.mu.Lock(); defer l.mu.Unlock(); return l.b.String() }
+
+func captureLog(t *testing.T) *lockedLog {
+ t.Helper()
+ l := &lockedLog{}
+ prev, flags := log.Writer(), log.Flags()
+ log.SetOutput(l)
+ log.SetFlags(0)
+ t.Cleanup(func() { log.SetOutput(prev); log.SetFlags(flags) })
+ return l
+}
+
+// The acquire's log names the rule that won the take: the decision of the
+// round whose write landed, not the first round's.
+func TestAcquireHALogsTheWinningRule(t *testing.T) {
+ mine := hafresh.OwnerFor(hafresh.Self{Ref: "a", IID: "i-a", Account: "111122223333", Region: "eu-west-1"}, 9, true)
+ other := hafresh.OwnerFor(hafresh.Self{Ref: "b", IID: "i-b"}, 7, true)
+ clean, _ := hafresh.MarkerBody(3, hafresh.Marker{V: 1, Box: "b", IID: "i-b", Clean: true})
+ unclean, _ := hafresh.MarkerBody(3, hafresh.Marker{V: 1, Box: "b", IID: "i-b"})
+ proofs := hafresh.Proofs{
+ SameBoxEmpty: func() (bool, error) { return true, nil },
+ OwnerTerminated: func(iid string) (bool, error) { return iid == "i-b", nil },
+ }
+ for _, c := range []struct {
+ name string
+ body []byte // nil: no lock
+ change []byte // the lock as the first write finds it, nil: unchanged
+ word string
+ }{
+ {"absent", nil, nil, "first wake"},
+ {"clean marker", clean, nil, "clean marker"},
+ {"unclean marker", unclean, nil, "unclean marker"},
+ {"own expired", leaseBody(mine, time.Now().Add(-time.Hour)), nil, "same-box takeover"},
+ {"terminated holder", leaseBody(other, time.Now().Add(-time.Hour)), nil, "holder terminated"},
+ {"lost to a terminated holder", clean, leaseBody(other, time.Now().Add(-time.Hour)), "holder terminated"},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ haBox(t)
+ logs := captureLog(t)
+ fx := leasetest.NewLockFixture(t)
+ if c.body != nil {
+ fx.PutLock("instances/h", c.body)
+ }
+ if c.change != nil {
+ var once sync.Once
+ fx.BeforeWrite(func(string, string) { once.Do(func() { fx.PutLock("instances/h", c.change) }) })
+ }
+ h, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, proofs)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer h.Release(ctx)
+ if want := "(" + c.word + ")"; !strings.Contains(logs.String(), "HA lease acquired in") || !strings.Contains(logs.String(), want) {
+ t.Fatalf("the acquire's log does not say %s:\n%s", want, logs)
+ }
+ })
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 9a65d869d..eb9a55677 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -16,3 +16,4 @@ plan14-root-reads-analytics-onramp.tsv f5afdacd495705841fcc8441eaefe0efb9db7056d
plan14-root-reads-nearest-region-scan.tsv f5afdacd495705841fcc8441eaefe0efb9db7056de281bb06d1714960a5575b7
plan14-root-reads-plans-6b-checkout-flow.tsv f5afdacd495705841fcc8441eaefe0efb9db7056de281bb06d1714960a5575b7
plan14-root-reads-nearest-region-followups.tsv f5afdacd495705841fcc8441eaefe0efb9db7056de281bb06d1714960a5575b7
+plan14-root-reads-region-ha-p1b1.tsv 185170fe393cb565d18a3359dee5ace12676b3e1adecb8b638199d25ceeb779f
diff --git a/internal/provision/testdata/plan14-root-reads-region-ha-p1b1.tsv b/internal/provision/testdata/plan14-root-reads-region-ha-p1b1.tsv
new file mode 100644
index 000000000..40df3bfb7
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-region-ha-p1b1.tsv
@@ -0,0 +1,18 @@
+# Census overlay region-ha-p1b1, written by census-propose (#369). census-ruling-region-ha-p1b1, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-region-ha-p1b1.md.
+# 1 body, 1 sites, 5 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 1 removed: each unit's declaration, or each envelope's directory, is absent from the scanned tree, so its row goes, a frozen declaration is retired as absent, and an envelope is retired.
+# 2 new dispositions: 0 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 4e5587abf5fca2ac92c28ced3e51c8840af979581eb8732c3071829fde22eaa8 internal/activator/hatakeover.go ExecBackend.ownerTerminated legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b1;basis=new (region HA P1b-1): returns nil without eb.OwnerTerminated; else a closure calling it with the lock owner's instance id (from the HA lock, written by a box agent) and logging rt.Host on a takeover and, at most once a minute per host, on an error; the id goes only to EC2 DescribeInstances in this box's own account and region and is checked against the reply (termfence.SameAccountTerminated); root never calls it registry:Host@280,registry:Host@446 453ee2e95d0effb965bcb0f0e405d0da765e746806c77b975042dafbc89f8a8d
+@legacy d57c3b6770686a97af4963b0e83fe62e2a796f93af9d65d2879b0ea2776b5137 internal/host/haself.go readIdentity legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b1;basis=replaces readInstanceID (region HA P1b-1): the same IMDSv2 token and identity-document read within 2 s, each body io.ReadAll capped at 64 KiB, now decoding accountId and region beside instanceId; IMDS answers only for this instance; no tenant or app input; root never calls it file:ReadAll@537 acfe205becd4143144071a52dac849f574eb5a249a49488d3f2cfb6dbbf9dcb0
+@legacy 111e0388bdc64f3beca31e29a26c1fb42c990d9ae0a08581c7bf6936e8f6cc1a internal/activator/hawake.go ExecBackend.acquireClassified legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: the acquire's classification: a legacy route (sidecar, hand-added or not an instance) takes lease.Acquire and refuses on an HA-format lock; otherwise isHA (a record read error fails the wake, never falls back to legacy); not HA takes lease.Acquire, and an HA-format lock there marks the host HA for good and continues; HA requires haContained before any lock request, then lease.AcquireHA with the same-box proof; held and refused leases map to errLeaseHeld and errLeaseRefused (leaseError); +registry:Host, +whole:Route x7;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: the HA acquire's Proofs gain OwnerTerminated (b.ownerTerminated(ctx, rt)) beside SameBoxEmpty; one more whole:Route site passes the route to ownerTerminated; nothing new is read; the proof is consulted only by hafresh.DecideAcquire for another box's expired HA lock registry:Host@106,whole:Route@1199,whole:Route@1318,whole:Route@1363,whole:Route@1657,whole:Route@195,whole:Route@564,whole:Route@615,whole:Route@896 9cd7938fd864876b89fd093ccfbe8c88ae8c2b7d2dbac7910c86e2d25abf5089
+internal/host/agent.go runAgent authority B,C,D,F rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites file:Exec@17043,file:Open@1150,file:Statfs@42964,registry:App@11199,whole:Route@11191,whole:Route@27219 20f83bd9ac4a8f5ccbdce95ceb6560633d517340eee5a266d13d353d1c281e06
+internal/activator/hatakeover.go ExecBackend.ownerTerminated legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b1;basis=new (region HA P1b-1): returns nil without eb.OwnerTerminated; else a closure calling it with the lock owner's instance id (from the HA lock, written by a box agent) and logging rt.Host on a takeover and, at most once a minute per host, on an error; the id goes only to EC2 DescribeInstances in this box's own account and region and is checked against the reply (termfence.SameAccountTerminated); root never calls it registry:Host@280,registry:Host@446 453ee2e95d0effb965bcb0f0e405d0da765e746806c77b975042dafbc89f8a8d
+internal/host/haself.go readIdentity legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b1;basis=replaces readInstanceID (region HA P1b-1): the same IMDSv2 token and identity-document read within 2 s, each body io.ReadAll capped at 64 KiB, now decoding accountId and region beside instanceId; IMDS answers only for this instance; no tenant or app input; root never calls it file:ReadAll@537 acfe205becd4143144071a52dac849f574eb5a249a49488d3f2cfb6dbbf9dcb0
+internal/activator/hawake.go ExecBackend.acquireClassified legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: the acquire's classification: a legacy route (sidecar, hand-added or not an instance) takes lease.Acquire and refuses on an HA-format lock; otherwise isHA (a record read error fails the wake, never falls back to legacy); not HA takes lease.Acquire, and an HA-format lock there marks the host HA for good and continues; HA requires haContained before any lock request, then lease.AcquireHA with the same-box proof; held and refused leases map to errLeaseHeld and errLeaseRefused (leaseError); +registry:Host, +whole:Route x7;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: the HA acquire's Proofs gain OwnerTerminated (b.ownerTerminated(ctx, rt)) beside SameBoxEmpty; one more whole:Route site passes the route to ownerTerminated; nothing new is read; the proof is consulted only by hafresh.DecideAcquire for another box's expired HA lock registry:Host@106,whole:Route@1199,whole:Route@1318,whole:Route@1363,whole:Route@1657,whole:Route@195,whole:Route@564,whole:Route@615,whole:Route@896 9cd7938fd864876b89fd093ccfbe8c88ae8c2b7d2dbac7910c86e2d25abf5089
+@remove internal/host/haself.go readInstanceID
+@removed internal/host/haself.go readInstanceID H3 census-ruling-region-ha-p1b1;absent;basis=removed: replaced by readIdentity (same reads, two more decoded fields)
+@coverage internal/activator f56620f1f876769e5cd956b2598c4ed9adcc412fd253ee4a88ce074c9f2ea9cc
+@coverage internal/hafresh 5a01361dc342f9684a7cc37778803722f61099cbbb03324512121e4c1a044351
+@coverage internal/host 444688eeb31ffeaa52ebbdc1f4775fe88c89f737fcf7ce4a227781d80d0e33b3
+@coverage internal/lease 45c526aff79916c93bb855048ba71c45867e45146414c2f1525d5600cdd9d632
+@coverage internal/termfence 53ee9d49ba33d6594cbc1479c69909fec9023ca9bdb6ba645f85d7aa7fe1d85b
diff --git a/internal/sim/regionha/actions_test.go b/internal/sim/regionha/actions_test.go
index 6864c7eb0..97df872d7 100644
--- a/internal/sim/regionha/actions_test.go
+++ b/internal/sim/regionha/actions_test.go
@@ -29,13 +29,23 @@ func (w *world) sliceEmpty(b *box, h string) bool {
return true
}
-// decideAcquire is hafresh.DecideAcquire with this box's proofs.
+// decideAcquire is hafresh.DecideAcquire with this box's proofs: the
+// same-box emptiness proof and the confirmer.
func (w *world) decideAcquire(b *box, h string, v hafresh.View) hafresh.Decision {
proof := func() (bool, error) { return w.sameBoxEmpty(b, h), nil }
if !on("same-box-no-proof") {
proof = func() (bool, error) { return true, nil }
}
- d := hafresh.DecideAcquire(v, b.Self, w.now(), hafresh.Proofs{SameBoxEmpty: proof})
+ if !on("takeover-before-expiry") && !v.Absent && v.Lock.Release == nil && !w.now().After(v.Lock.ExpiresAt) {
+ // A caller that asks EC2 first and treats a confirmed termination
+ // as the lease's end: it hands the table an expiry in the past.
+ if o, ok := hafresh.ParseOwner(v.Lock.Owner); ok && o.IID != "" && o.IID != b.Self.IID {
+ if gone, err := w.ownerTerminated(o.IID); err == nil && gone {
+ v.Lock.ExpiresAt = w.now().Add(-tick)
+ }
+ }
+ }
+ d := hafresh.DecideAcquire(v, b.Self, w.now(), hafresh.Proofs{SameBoxEmpty: proof, OwnerTerminated: w.ownerTerminated})
if !on("expiry-authorizes") && d.Action == hafresh.ActRefuse && d.Reason == hafresh.ReasonOtherExpired {
d = hafresh.Decision{Action: hafresh.ActTake, Reason: "expired"}
}
@@ -171,7 +181,7 @@ func (w *world) wake(b *box, h string, o wakeOpts, pre *pending) string {
switch {
case strings.HasPrefix(why, "held"):
w.event("refused-held")
- case why == hafresh.ReasonOtherExpired:
+ case strings.HasPrefix(why, hafresh.ReasonOtherExpired):
w.event("refused-other-expired")
case strings.HasPrefix(why, hafresh.ReasonSameBoxUnsure):
w.event("refused-same-box")
@@ -185,7 +195,11 @@ func (w *world) wake(b *box, h string, o wakeOpts, pre *pending) string {
}
b.AcquiredHere[h] = true
if !e.View.Absent && e.View.Lock.Release == nil {
- w.event("same-box-retake")
+ if o, _ := hafresh.ParseOwner(e.View.Lock.Owner); o.IID == b.Self.IID {
+ w.event("same-box-retake")
+ } else {
+ w.event("takeover")
+ }
}
w.logf("box%d: %s: acquired over %s", b.ID, h, viewWord(e.View))
if o.CrashBeforeRestore {
@@ -716,6 +730,16 @@ func (w *world) retryObligation(b *box, ob *obligation, fails bool) bool {
// crash kills b's agent: its memory goes (entries, pending acquires, owed
// markers not on disk, publishers); the host units outlive it as orphans.
func (w *world) crash(b *box) {
+ w.die(b)
+ w.event("crash")
+ w.logf("box%d: the agent crashes", b.ID)
+}
+
+// die is every death of b's agent process: the uploads it had in flight
+// are left to land (inFlight), and its memory goes.
+func (w *world) die(b *box) {
+ w.inFlight(b)
+ w.landLate()
b.Agent = agentDown
for _, h := range w.hosts {
for _, u := range b.Units[h] {
@@ -730,8 +754,122 @@ func (w *world) crash(b *box) {
b.Strays = nil
b.AcquiredHere = map[string]bool{}
b.Swept = false
- w.event("crash")
- w.logf("box%d: the agent crashes", b.ID)
+}
+
+// terminate is the instance's termination: everything crash does, and
+// every unit's processes go with it (stragglers and orphans included), the
+// disk goes (local copies, release records, obligations on disk), and the
+// box never restarts. w.terminated is the truth; EC2 shows it 1 to 12
+// steps later (one in a scripted world; a witness may move it).
+func (w *world) terminate(b *box) {
+ w.die(b)
+ b.Units = map[string][]*unit{}
+ b.Local = map[string]*localCopy{}
+ b.Disk = map[string]*obligation{}
+ d := 1
+ if !w.scripted {
+ d = 1 + w.rng.Intn(12)
+ }
+ w.terminated[b.Self.IID] = w.step
+ w.visibleAt[b.Self.IID] = w.step + d
+ w.event("terminate")
+ w.logf("box%d: the instance %s is terminated; EC2 shows it from step %d", b.ID, b.Self.IID, w.step+d)
+}
+
+// lateWrite is an upload a dead agent process sent before it died: a
+// replica upload (TXID, Ver), or a files manifest commit (Pub, Files). It
+// lands at step At, under the dead process's pid.
+type lateWrite struct {
+ Box *box
+ PID int
+ Host string
+ At int
+ TXID uint64
+ Ver int
+ Pub *publisher
+ Files files
+}
+
+// inFlight is what b's dying agent process had sent and not seen settle:
+// for each host it holds, a seeded coin each for a replica upload and for
+// the commit of an in-flight files snapshot. The replica upload is of the
+// position not yet uploaded; with none, of the tenant's last transaction,
+// committed just before the death (not once the release has stopped the
+// unit). Only a running agent sends, and only while its lease has time
+// left: a hung agent, or one whose lease has expired, has nothing in
+// flight. A scripted world draws nothing; its witness calls lateUpload.
+func (w *world) inFlight(b *box) {
+ if w.scripted || b.Agent != agentUp {
+ return
+ }
+ for _, h := range w.hosts {
+ e, l := b.Entries[h], b.Local[h]
+ if e == nil || stepOf(e.Expires) <= w.step {
+ continue
+ }
+ if l != nil && (l.TXID > e.Uploaded || e.Releasing == nil) && w.pct(50) {
+ if l.TXID == e.Uploaded {
+ w.tenantWrite(b, h, false)
+ }
+ w.lateUpload(b, h, true, w.landing(e))
+ }
+ if pub := e.Pub; pub != nil && pub.Inflight != nil && !pub.Broken && w.pct(50) {
+ w.lateUpload(b, h, false, w.landing(e))
+ }
+ }
+}
+
+// landing is a seeded step from now up to the last step of the lease, at
+// most TTL - 1 steps after its last renewal: an upload sent now completes
+// within the lease, never before it was sent and never after expiry.
+func (w *world) landing(e *entry) int {
+ return w.step + w.rng.Intn(stepOf(e.Expires)-w.step)
+}
+
+// lateUpload is an upload b's agent process sent for h before it died, a
+// replica upload of its local position (replica) or the commit of its
+// in-flight files snapshot, landing at step at (now or later) through
+// replicaWrite or manifestWrite with the dead pid. It
+// models P1a's and the legacy path's assumption: an upload already sent
+// settles within the lease. The writer oracle (checkHolder) fails I1 if it
+// lands after another process took the lock.
+func (w *world) lateUpload(b *box, h string, replica bool, at int) {
+ if at < w.step {
+ w.fail("MODEL", "box%d: %s: an upload sent at step %d cannot complete at step %d", b.ID, h, w.step, at)
+ return
+ }
+ lw := &lateWrite{Box: b, PID: b.PID, Host: h, At: at}
+ what := "manifest commit"
+ if replica {
+ l := b.Local[h]
+ lw.TXID, lw.Ver = l.TXID, l.Ver
+ what = fmt.Sprintf("replica upload txid %d", l.TXID)
+ } else {
+ pub := b.Entries[h].Pub
+ lw.Pub, lw.Files = pub, pub.Inflight.Files
+ pub.Inflight = nil
+ }
+ w.late = append(w.late, lw)
+ w.event("late-upload")
+ w.logf("box%d: %s: pid %d dies with a %s in flight; it lands at step %d", b.ID, h, b.PID, what, at)
+}
+
+// landLate lands every late upload whose step has come.
+func (w *world) landLate() {
+ var keep []*lateWrite
+ for _, lw := range w.late {
+ if lw.At > w.step {
+ keep = append(keep, lw)
+ continue
+ }
+ w.logf("box%d: %s: an upload sent by the dead pid %d lands", lw.Box.ID, lw.Host, lw.PID)
+ if lw.Pub != nil {
+ w.manifestWrite(lw.Box, lw.Pub, lw.Files)
+ } else {
+ w.replicaWrite(lw.Box, lw.PID, lw.Host, lw.TXID, lw.Ver)
+ }
+ }
+ w.late = keep
}
// restart starts a new agent process: its startup sweep (which, when it
@@ -914,10 +1052,22 @@ func init() {
w.crash(b)
return true
}},
+ // The instance is terminated, at the rate of a crash, in the odd
+ // seeds' worlds only (w.terminations). At most one a world: a
+ // terminated box never comes back, so more would leave most worlds
+ // with one box for most of the walk.
+ action{"terminate", 2, func(w *world) bool {
+ b := w.randomBox()
+ if !w.terminations || w.calm() || len(w.terminated) > 0 {
+ return false
+ }
+ w.terminate(b)
+ return true
+ }},
action{"agent-restart", 6, func(w *world) bool {
b := w.randomBox()
sweepOK := !w.fault(30)
- if b.Agent != agentDown {
+ if b.Agent != agentDown || w.isTerminated(b) {
return false
}
w.restart(b, sweepOK)
diff --git a/internal/sim/regionha/invariants_test.go b/internal/sim/regionha/invariants_test.go
index 12cc94853..12891dadc 100644
--- a/internal/sim/regionha/invariants_test.go
+++ b/internal/sim/regionha/invariants_test.go
@@ -27,6 +27,10 @@ import (
// host whose agent crashed waits behind its own expired lease for its
// box's recovery (§9.6), and leftover objects under an absent lock
// refuse the first wake (the leftover action's, not a lease's).
+// After a termination (P1b-1, r1.4, r2.2): a host behind the lease of a
+// box terminated in truth is held by a live box of its pool once the
+// finalization has given each one a confirmation and a fault-free wake
+// (finalTakeovers). With no live box, I5 does not apply to that host.
//
// MODEL is the model's own consistency: a lock that does not decode.
@@ -114,6 +118,15 @@ func (w *world) checkLiveness() {
continue
}
v := w.view(h)
+ if o, dead := w.terminatedOwner(v); dead {
+ // The lease's box is gone with its obligations; the takeover is
+ // the release. Read from world truth, never the confirmer.
+ if len(w.survivors()) > 0 {
+ w.fail("I5", "%s is stranded behind the lease of %s, terminated at step %d, while a live box of its pool could take it (lock %s)",
+ h, o.IID, w.terminated[o.IID], w.lockString(h))
+ }
+ continue
+ }
if v.Lock.Release == nil && w.owed[h][p.ETag] {
w.fail("I5", "%s is stranded: the release marker owed for %s was never written (lock %s)", h, p.ETag, w.lockString(h))
}
diff --git a/internal/sim/regionha/rules_test.go b/internal/sim/regionha/rules_test.go
index 2fdd8336e..8086851b3 100644
--- a/internal/sim/regionha/rules_test.go
+++ b/internal/sim/regionha/rules_test.go
@@ -58,4 +58,9 @@ var allRules = []string{
"recover-without-sweep", // sameBoxEmpty needs this agent's startup sweep to have proven every unit stopped (r3.2)
"marker-before-slice-empty", // releaseHAClean holds the release until the host's slice reads empty (r3.2)
"failed-wake-before-slice-empty", // cleanupFailedWake and the reaper hold an HA release until the host's slice reads empty (haHostEmpty, final review F1)
+
+ // takeover of a terminated box's hosts (P1b-1, N-HA9)
+ "takeover-unconfirmed", // Proofs.OwnerTerminated: true only once EC2 shows the owner terminated, never for a box alive or hung
+ "takeover-before-expiry", // the takeover row needs the lock expired too: an upload the dead process sent lands within its lease (N-HA9)
+ "no-takeover", // a survivor of the pool takes a terminated owner's expired lock: the host comes back
}
diff --git a/internal/sim/regionha/sim_test.go b/internal/sim/regionha/sim_test.go
index 8828d4af9..b101d39d7 100644
--- a/internal/sim/regionha/sim_test.go
+++ b/internal/sim/regionha/sim_test.go
@@ -2,6 +2,7 @@ package regionha
import (
"fmt"
+ "math/rand"
"os"
"os/exec"
"reflect"
@@ -214,6 +215,7 @@ func TestEveryActionFires(t *testing.T) {
"reclassified", "late-ack", "failed-restore", "failed-after-replication", "crash-before-restore",
"marker-clean", "marker-unclean", "marker-owed", "obligation-discharged",
"release-held", "failed-wake-held", "ha-lock-on-legacy-path", "hang-resumed", "manifest-committed",
+ "terminate", "takeover", "late-upload", "confirm-error",
} {
if events[e] == 0 {
t.Errorf("no %s over 200 seeds", e)
@@ -221,3 +223,86 @@ func TestEveryActionFires(t *testing.T) {
}
t.Logf("completed: %v; events: %v", done, events)
}
+
+// TestLateUploadOnlyWithinLease: only a running agent with time left on
+// its lease has an upload in flight when it dies, and that upload lands
+// within the lease. An agent that hung past its lease's expiry sends
+// nothing: its death creates no late upload (Task 5 review r1, P2).
+func TestLateUploadOnlyWithinLease(t *testing.T) {
+ saved := mutated
+ mutated = ""
+ defer func() { mutated = saved }()
+ sent := 0
+ for seed := int64(1); seed <= 40; seed++ {
+ for _, hung := range []bool{true, false} {
+ w := newWorldN(seed, rand.New(rand.NewSource(seed)), 2, []string{sh})
+ A := w.boxes[0]
+ if r := w.wake(A, sh, wakeOpts{}, nil); r != "served" {
+ t.Fatalf("seed %d: A's wake: %s", seed, r)
+ }
+ w.tenantWrite(A, sh, true)
+ if hung {
+ w.hang(A, ttlTicks+5)
+ w.advance(ttlTicks + 3) // the lease expired at step 15; A still hangs
+ } else {
+ w.advance(3)
+ }
+ expires := stepOf(A.Entries[sh].Expires)
+ if seed%2 == 0 {
+ w.crash(A)
+ } else {
+ w.terminate(A)
+ }
+ if hung {
+ if n := w.events["late-upload"]; n != 0 || w.s3[sh].MaxTXID != 0 {
+ t.Errorf("seed %d: the death after an expired hang sent %d uploads (replica head %d)", seed, n, w.s3[sh].MaxTXID)
+ }
+ } else {
+ sent += w.events["late-upload"]
+ for _, lw := range w.late {
+ if lw.At < w.step || lw.At >= expires {
+ t.Errorf("seed %d: an upload sent at step %d lands at step %d, outside the lease ending at step %d", seed, w.step, lw.At, expires)
+ }
+ }
+ }
+ w.advance(ttlTicks)
+ if len(w.violations) > 0 {
+ t.Errorf("seed %d (hung %v): %v", seed, hung, w.violations)
+ }
+ }
+ }
+ if sent == 0 {
+ t.Fatal("no running agent's death had an upload in flight over 40 seeds; the check proves nothing")
+ }
+}
+
+// TestFinalAllTerminated: with every box of the host's pool terminated,
+// the finalization restarts none of them and I5 does not apply to the
+// host stranded behind the dead box's lease.
+func TestFinalAllTerminated(t *testing.T) {
+ saved := mutated
+ mutated = ""
+ defer func() { mutated = saved }()
+ w := newWitness()
+ A, _, _ := w.abc()
+ w.serve(t, A)
+ w.write(A, false)
+ w.syncNow(A, false)
+ for _, b := range w.boxes {
+ w.terminate(b)
+ }
+ lock := w.lockString(sh)
+ w.final()
+ for _, b := range w.boxes {
+ if b.Agent != agentDown {
+ t.Errorf("box%d is %s after the finalization; a terminated box never restarts", b.ID, b.Agent)
+ }
+ }
+ if w.events["restart"] != 0 || w.events["takeover"] != 0 || w.lockString(sh) != lock {
+ t.Errorf("restarts %d, takeovers %d, lock %s (was %s)", w.events["restart"], w.events["takeover"], w.lockString(sh), lock)
+ }
+ if len(w.violations) > 0 {
+ dump(t, w)
+ t.Fatalf("with no live box of the pool, I5 does not apply: %v", w.violations)
+ }
+}
diff --git a/internal/sim/regionha/witness_test.go b/internal/sim/regionha/witness_test.go
index 795de155a..650c595e8 100644
--- a/internal/sim/regionha/witness_test.go
+++ b/internal/sim/regionha/witness_test.go
@@ -62,6 +62,12 @@ var witnesses = []witness{
"r3.2: a unit of the host outlives the stop; the release waits for the slice, and a marker before it lets another box run beside the straggler", wStragglerHoldsRelease},
{"failed-wake-before-slice-empty", "failed-wake-before-slice-empty", "I1",
"final review F1: a wake fails after replication and a replacement invocation outlives its stop; the release waits for the slice, and an unclean marker before it lets another box run beside the replacement", wFailedWakeStragglerHoldsRelease},
+ {"takeover-unconfirmed", "takeover-unconfirmed", "I1",
+ "A hangs past the TTL, alive; EC2 shows it running, so B refuses its expired lease; a confirmer that answers terminated lets B run beside the hung box's unit", wTakeoverUnconfirmed},
+ {"takeover-before-expiry", "takeover-before-expiry", "I1",
+ "A is terminated with a replica upload in flight that lands at TTL - 2; B's wake right after visibility is held; a take before expiry lets A's upload land under B's lease", wTakeoverBeforeExpiry},
+ {"no-takeover", "no-takeover", "I5",
+ "r2.2: A is terminated while it holds the host, and no request comes until the finalization; a survivor that never takes over leaves the host down", wNoTakeover},
}
// TestWitnesses is the deterministic half of the mutation evidence.
@@ -497,6 +503,46 @@ func wFailedWakeStragglerHoldsRelease(t *testing.T, w *world) {
w.checkLiveness()
}
+func wTakeoverUnconfirmed(t *testing.T, w *world) {
+ A, B, _ := w.abc()
+ w.serve(t, A)
+ w.write(A, false)
+ w.syncNow(A, false)
+ w.hang(A, ttlTicks+3)
+ w.advance(ttlTicks + 1)
+ r := w.req(B, wakeOpts{})
+ expect(t, "takeover-unconfirmed", r == "refused: "+hafresh.ReasonOtherExpired, "B's wake over the hung A's expired lease: %s", r)
+ w.advance(3) // A resumes and renews
+}
+
+func wTakeoverBeforeExpiry(t *testing.T, w *world) {
+ A, B, _ := w.abc()
+ w.serve(t, A) // the lease's last renewal: this step
+ w.write(A, false)
+ w.lateUpload(A, sh, true, w.step+ttlTicks-2)
+ w.terminate(A)
+ w.check()
+ w.advance(w.visibleAt[A.Self.IID] - w.step)
+ r := w.req(B, wakeOpts{})
+ expect(t, "takeover-before-expiry", strings.HasPrefix(r, "refused: held"), "B's wake right after visibility, before expiry: %s", r)
+ w.advance(ttlTicks + 1 - w.step) // A's upload lands; the lease expires
+ if on("takeover-before-expiry") {
+ r = w.req(B, wakeOpts{})
+ expect(t, "takeover-before-expiry", r == "served" && w.events["takeover"] == 1, "B's wake after expiry: %s", r)
+ }
+}
+
+func wNoTakeover(t *testing.T, w *world) {
+ A, _, _ := w.abc()
+ w.serve(t, A)
+ w.write(A, false)
+ w.syncNow(A, false)
+ w.terminate(A)
+ w.check()
+ w.final()
+ expect(t, "no-takeover", w.events["takeover"] == 1, "no survivor took the terminated A's host: %s", w.lockString(sh))
+}
+
// TestKnownGapReusedHostnameLegacyWake documents a known gap, not a rule:
// with hostnames reused (#199's never-reuse rule not in force), a box whose
// lifetime index still holds a negative entry from the name's earlier
diff --git a/internal/sim/regionha/world_test.go b/internal/sim/regionha/world_test.go
index 2a08e6e0f..7dc8e7ca6 100644
--- a/internal/sim/regionha/world_test.go
+++ b/internal/sim/regionha/world_test.go
@@ -2,6 +2,7 @@ package regionha
import (
"encoding/json"
+ "errors"
"fmt"
"math/rand"
"sort"
@@ -226,6 +227,26 @@ type world struct {
// that ETag at the end, the marker was never written (I5).
owed map[string]map[string]bool
+ // terminated is world truth: the instances terminated, by instance id,
+ // at the step of their termination. visibleAt is the step from which
+ // EC2's DescribeInstances shows each one terminated. The oracles and the
+ // finalization read these; a box learns of a termination only through
+ // the confirmer (ownerTerminated), which the rules change.
+ terminated map[string]int
+ visibleAt map[string]int
+
+ // late are the uploads dead agent processes had in flight, each landing
+ // at its step (lateUpload).
+ late []*lateWrite
+
+ // faultsOff is set by the finalization: no fault from then on.
+ faultsOff bool
+
+ // terminations: the terminate action is enabled. The sweep splits by
+ // seed: odd seeds terminate, even seeds keep P1a's walk, every box
+ // alive throughout.
+ terminations bool
+
clock, nextETag, nextPID, nextInode, nextVer int64
// scripted is a witness's world: the timers run (expiry, hang ends,
@@ -260,6 +281,7 @@ func newWorld(seed int64, verbose bool) *world {
n := 2 + rng.Intn(4)
w := newWorldN(seed, rng, n, []string{"blog", "docs", "shop"})
w.verbose = verbose
+ w.terminations = seed%2 == 1
// A stale negative index entry: the box indexed an older, legacy
// incarnation of the host (r3.1).
for _, b := range w.boxes {
@@ -269,7 +291,7 @@ func newWorld(seed int64, verbose bool) *world {
}
}
}
- w.logf("world seed %d: %d boxes, hosts %v, stale negative entries %s", seed, n, w.hosts, w.staleString())
+ w.logf("world seed %d: %d boxes, hosts %v, stale negative entries %s, terminations %v", seed, n, w.hosts, w.staleString(), w.terminations)
return w
}
@@ -284,6 +306,9 @@ func newWorldN(seed int64, rng *rand.Rand, n int, hosts []string) *world {
events: map[string]int{},
owed: map[string]map[string]bool{},
nextPID: 100,
+
+ terminated: map[string]int{},
+ visibleAt: map[string]int{},
}
for _, h := range hosts {
w.s3[h] = &prefix{}
@@ -342,8 +367,8 @@ func (w *world) pct(p int) bool {
return w.rng.Intn(100) < p
}
-// fault is pct, and false once the world is calm.
-func (w *world) fault(p int) bool { return !w.calm() && w.pct(p) }
+// fault is pct, and false once the world is calm or the faults are off.
+func (w *world) fault(p int) bool { return !w.calm() && !w.faultsOff && w.pct(p) }
func (w *world) logf(format string, args ...any) {
w.trace = append(w.trace, fmt.Sprintf("[%d] ", w.step)+fmt.Sprintf(format, args...))
@@ -414,14 +439,82 @@ func (w *world) lockString(h string) string {
return fmt.Sprintf("lease{%s gen %d expires %s %s}", v.Lock.Owner, v.Lock.Generation, v.Lock.ExpiresAt.Sub(epoch), v.ETag)
}
+// ---- EC2 ----
+
+// ownerTerminated is the confirmer (termfence.Confirmer.Terminated, P1b-1
+// Task 2) as a box's acquire sees it: true only once DescribeInstances
+// shows the instance terminated, 1 to 12 steps after the termination.
+// While faults are on, a seeded 10 % of its calls fail. Only the rules
+// change it; the oracles read w.terminated and w.visibleAt instead.
+func (w *world) ownerTerminated(iid string) (bool, error) {
+ if !w.scripted && w.fault(10) {
+ w.event("confirm-error")
+ return false, errors.New("DescribeInstances failed")
+ }
+ if !on("takeover-unconfirmed") {
+ return true, nil // whatever the instance's state
+ }
+ if !on("no-takeover") {
+ return false, nil
+ }
+ _, dead := w.terminated[iid]
+ return dead && w.step >= w.visibleAt[iid], nil
+}
+
+// isTerminated is world truth: b's instance is terminated.
+func (w *world) isTerminated(b *box) bool {
+ _, dead := w.terminated[b.Self.IID]
+ return dead
+}
+
+// terminatedOwner is world truth about a lock: a lease (no marker) whose
+// owner's instance is terminated.
+func (w *world) terminatedOwner(v hafresh.View) (hafresh.Owner, bool) {
+ if v.Absent || v.Lock.Release != nil {
+ return hafresh.Owner{}, false
+ }
+ o, ok := hafresh.ParseOwner(v.Lock.Owner)
+ if !ok {
+ return hafresh.Owner{}, false
+ }
+ _, dead := w.terminated[o.IID]
+ return o, dead
+}
+
+// survivors are the live boxes of a host's pool. Every box of the model
+// serves every host, so the pool is every box not terminated.
+func (w *world) survivors() []*box {
+ var out []*box
+ for _, b := range w.boxes {
+ if !w.isTerminated(b) {
+ out = append(out, b)
+ }
+ }
+ return out
+}
+
+// holds reports whether some box holds h: it is awake there, or its
+// release is held there.
+func (w *world) holds(h string) bool {
+ for _, b := range w.boxes {
+ if b.Entries[h] != nil {
+ return true
+ }
+ }
+ return false
+}
+
+func stepOf(t time.Time) int { return int(t.Sub(epoch) / tick) }
+
// ---- timers and background work ----
-// tick advances the background of one step: an agent's hang ends;
-// stragglers exit; orphans restart by systemd; and every running agent's
-// held releases retry, its publishers and replicators run, its leases
-// renew and its owed markers retry. A scripted world runs only the timers
+// tick advances the background of one step: uploads dead processes sent
+// land; an agent's hang ends; stragglers exit; orphans restart by systemd;
+// and every running agent's held releases retry, its publishers and
+// replicators run, its leases renew and its owed markers retry. A scripted world runs only the timers
// and what follows from them.
func (w *world) tick() {
+ w.landLate()
for _, b := range w.boxes {
if b.Agent == agentHung && w.step >= b.HungTill {
b.Agent = agentUp
@@ -531,11 +624,16 @@ func (w *world) pick() *action {
}
// final clears every fault and lets the world settle: hung agents resume,
-// dead agents restart (their startup sweep succeeds), stragglers exit,
-// held releases finish and owed markers are retried. Then the liveness
-// oracle (I5).
+// dead agents restart (their startup sweep succeeds) unless their instance
+// is terminated, stragglers exit, held releases finish and owed markers
+// are retried. Then the takeovers after a termination (finalTakeovers)
+// and the liveness oracle (I5).
func (w *world) final() {
+ w.faultsOff = true
for _, b := range w.boxes {
+ if w.isTerminated(b) {
+ continue
+ }
switch b.Agent {
case agentHung:
b.Agent = agentUp
@@ -552,10 +650,53 @@ func (w *world) final() {
}
}
}
+ w.finalTakeovers()
w.checkLiveness()
w.logf("final: %d steps, %d violations", w.step, len(w.violations))
}
+// finalTakeovers is the finalization after a termination (r1.4, r2.2). For
+// every host no box holds whose lock is a lease of a box terminated in
+// truth, while a live box of its pool exists: the world advances past
+// EC2's visibility of the termination and past the lease's expiry, then
+// each live box in turn gets one confirmation attempt and one fault-free
+// wake, until one holds the host. The schedule reads world truth, never
+// the confirmer, so a mutated confirmer cannot skip it; checkLiveness then
+// fails I5 if no box holds the host. With no live box, I5 does not apply.
+func (w *world) finalTakeovers() {
+ var hs []string
+ until := w.step
+ for _, h := range w.hosts {
+ v := w.view(h)
+ o, dead := w.terminatedOwner(v)
+ if !dead || w.holds(h) || len(w.survivors()) == 0 {
+ continue
+ }
+ hs = append(hs, h)
+ until = max(until, w.visibleAt[o.IID], stepOf(v.Lock.ExpiresAt)+1)
+ }
+ if len(hs) == 0 {
+ return
+ }
+ w.logf("final: %v behind a terminated box's lease; advancing to step %d", hs, until)
+ w.advance(until - w.step)
+ for _, h := range hs {
+ o, dead := w.terminatedOwner(w.view(h))
+ if !dead {
+ continue
+ }
+ for _, b := range w.survivors() {
+ if w.holds(h) {
+ break
+ }
+ gone, err := w.ownerTerminated(o.IID)
+ w.logf("final: box%d asks EC2 about %s: terminated %v, error %v", b.ID, o.IID, gone, err)
+ w.logf("final: box%d: %s: wake: %s", b.ID, h, w.wake(b, h, wakeOpts{}, nil))
+ w.check()
+ }
+ }
+}
+
func runSeed(seed int64, verbose bool) *world {
w := newWorld(seed, verbose)
for i := 0; i < chaosSteps+calmSteps; i++ {
diff --git a/internal/termfence/confirm.go b/internal/termfence/confirm.go
new file mode 100644
index 000000000..dddb64e45
--- /dev/null
+++ b/internal/termfence/confirm.go
@@ -0,0 +1,228 @@
+package termfence
+
+import (
+ "context"
+ "errors"
+ "log"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/boxid"
+)
+
+const (
+ // ConfirmPositiveTTL keeps a "terminated" answer: an instance does not
+ // come back, and AWS forgets it within about an hour.
+ ConfirmPositiveTTL = 24 * time.Hour
+ // ConfirmNegativeTTL keeps every other answer, errors included, so a
+ // caller that asks every tick makes about one describe in ten seconds.
+ ConfirmNegativeTTL = 10 * time.Second
+)
+
+// SameAccountTerminated is Verify's identity and state check for a caller
+// that holds no roster entry for the instance: it is another box of this
+// box's own account and region, so self supplies both. It returns nil only
+// for a describe reply that names iid, in self's account and region, in the
+// state terminated. Every refusal wraps ErrNotEvidence.
+func SameAccountTerminated(self boxid.Cloud, iid string, o Observation) error {
+ switch {
+ case !self.Complete():
+ return refuse("this box has no proven cloud identity")
+ case iid == "":
+ return refuse("no instance to confirm")
+ case iid == self.InstanceID:
+ return refuse("%s is this box", iid)
+ case o.Via != ViaDescribe:
+ return refuse("source %q is not a describe", o.Via)
+ case !o.Found:
+ return refuse("the describe said nothing about %s; absence is not termination", iid)
+ case o.InstanceID != iid:
+ return refuse("observed %s, asked about %s", o.InstanceID, iid)
+ case o.Account != self.Account:
+ return refuse("observed in account %q, this box is in %q", o.Account, self.Account)
+ case o.Region != self.Region:
+ return refuse("observed in region %q, this box is in %q", o.Region, self.Region)
+ case o.State != stateTerminated:
+ return refuse("state is %q; only %q counts", o.State, stateTerminated)
+ }
+ return nil
+}
+
+// Confirmer answers whether another box's instance is terminated, asking
+// EC2 in this box's own account and region and nowhere else. One describe
+// per instance id per TTL; the cache lives as long as the process.
+type Confirmer struct {
+ // API builds the EC2 client for region. It is called until it first
+ // succeeds, never concurrently, and the client it returns is kept.
+ API func(ctx context.Context, region string) (EC2, error)
+ // Self is this box's proven cloud identity.
+ Self func() boxid.Cloud
+ // Now is time.Now when nil.
+ Now func() time.Time
+ // Logf is log.Printf when nil.
+ Logf func(string, ...any)
+
+ apiMu sync.Mutex // serializes client construction; spans every iid
+ api EC2
+
+ mu sync.Mutex // guards the fields below; never held across a call out
+ cache map[string]confirmed
+ inflight map[string]*flight
+ evident map[string]bool // instances whose first evidence is logged
+}
+
+type confirmed struct {
+ until time.Time
+ yes bool
+ err error
+}
+
+// flight is the one describe in progress for an instance id. Waiters take
+// its answer; res is written before done is closed.
+type flight struct {
+ done chan struct{}
+ res confirmed
+ waiters int
+}
+
+func (c *Confirmer) now() time.Time {
+ if c.Now != nil {
+ return c.Now()
+ }
+ return time.Now()
+}
+
+func (c *Confirmer) logf(format string, a ...any) {
+ if c.Logf != nil {
+ c.Logf(format, a...)
+ return
+ }
+ log.Printf(format, a...)
+}
+
+// Terminated reports whether the EC2 instance iid is terminated. It
+// answers false without error for this box's own instance and for anything
+// a describe does not prove: another state, another account or region, an
+// instance AWS no longer lists. A describe failure, or a Self that is not
+// a complete identity, is an error.
+//
+// At most one describe per instance id is in flight: callers that arrive
+// while one runs wait for it and take its answer, and the answer is cached
+// before they are released.
+func (c *Confirmer) Terminated(ctx context.Context, iid string) (bool, error) {
+ self := c.Self()
+ if !self.Complete() {
+ return false, errors.New("termfence: this box's cloud identity is incomplete")
+ }
+ if iid == "" || iid == self.InstanceID {
+ return false, nil
+ }
+ c.mu.Lock()
+ if e, ok := c.cache[iid]; ok && c.now().Before(e.until) {
+ c.mu.Unlock()
+ return e.yes, e.err
+ }
+ if f, ok := c.inflight[iid]; ok {
+ f.waiters++
+ c.mu.Unlock()
+ select {
+ case <-f.done:
+ return f.res.yes, f.res.err
+ case <-ctx.Done():
+ return false, ctx.Err()
+ }
+ }
+ f := &flight{done: make(chan struct{})}
+ if c.inflight == nil {
+ c.inflight = map[string]*flight{}
+ }
+ c.inflight[iid] = f
+ c.mu.Unlock()
+
+ // Publish and release even if ask panics.
+ f.res = confirmed{err: errors.New("termfence: the describe did not finish")}
+ defer func() {
+ c.publish(iid, f)
+ close(f.done)
+ }()
+ f.res = c.ask(ctx, self, iid)
+ return f.res.yes, f.res.err
+}
+
+// publish caches f's answer and ends the flight, in one step under the
+// mutex. An unexpired positive answer is never replaced by a negative or an
+// error.
+func (c *Confirmer) publish(iid string, f *flight) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ delete(c.inflight, iid)
+ now := c.now()
+ if old, ok := c.cache[iid]; ok && old.yes && now.Before(old.until) && !f.res.yes {
+ f.res = old
+ return
+ }
+ ttl := ConfirmNegativeTTL
+ if f.res.yes {
+ ttl = ConfirmPositiveTTL
+ }
+ f.res.until = now.Add(ttl)
+ if c.cache == nil {
+ c.cache = map[string]confirmed{}
+ }
+ c.cache[iid] = f.res
+}
+
+// client returns the kept client, building it on first use. Construction is
+// serialized across instance ids, the first success is kept, and a failure
+// is not: the next call tries again.
+func (c *Confirmer) client(ctx context.Context, region string) (EC2, error) {
+ c.apiMu.Lock()
+ defer c.apiMu.Unlock()
+ if c.api != nil {
+ return c.api, nil
+ }
+ api, err := c.API(ctx, region)
+ if err != nil {
+ return nil, err
+ }
+ c.api = api
+ return api, nil
+}
+
+// ask makes one describe and decides. The mutex is not held across it.
+func (c *Confirmer) ask(ctx context.Context, self boxid.Cloud, iid string) confirmed {
+ api, err := c.client(ctx, self.Region)
+ if err != nil {
+ c.logf("termfence: describe %s: %v", iid, err)
+ return confirmed{err: err}
+ }
+ out, err := DescribeInstance(ctx, api, boxid.Cloud{Provider: "aws", Account: self.Account, Region: self.Region, InstanceID: iid})
+ if err != nil {
+ c.logf("termfence: describe %s: %v", iid, err)
+ return confirmed{err: err}
+ }
+ o := FromDescribe(out, iid, self.Region)
+ if o.Found {
+ c.logf("termfence: describe %s: %s", iid, o.State)
+ } else {
+ c.logf("termfence: describe %s: not found", iid)
+ }
+ switch err := SameAccountTerminated(self, iid, o); {
+ case err == nil:
+ c.mu.Lock()
+ first := !c.evident[iid]
+ if c.evident == nil {
+ c.evident = map[string]bool{}
+ }
+ c.evident[iid] = true
+ c.mu.Unlock()
+ if first {
+ c.logf("termfence: %s confirmed terminated (first evidence, request %s)", iid, o.RequestID)
+ }
+ return confirmed{yes: true}
+ case errors.Is(err, ErrNotEvidence):
+ return confirmed{}
+ default:
+ return confirmed{err: err}
+ }
+}
diff --git a/internal/termfence/confirm_test.go b/internal/termfence/confirm_test.go
new file mode 100644
index 000000000..6b9c7e703
--- /dev/null
+++ b/internal/termfence/confirm_test.go
@@ -0,0 +1,463 @@
+package termfence
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/ec2"
+ "github.com/aws/aws-sdk-go-v2/service/ec2/types"
+
+ "github.com/carlosframework/platform/internal/boxid"
+)
+
+var confirmSelf = boxid.Cloud{Provider: "aws", Account: "111122223333", Region: "eu-west-1", InstanceID: "i-a"}
+
+type confirmRig struct {
+ f *fakeEC2
+ c *Confirmer
+ mu sync.Mutex
+ logs []string
+ at time.Time
+ apis int
+}
+
+func newConfirmRig(f *fakeEC2) *confirmRig {
+ r := &confirmRig{f: f, at: time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC)}
+ r.c = &Confirmer{
+ API: func(context.Context, string) (EC2, error) { r.apis++; return r.f, nil },
+ Self: func() boxid.Cloud { return confirmSelf },
+ Now: func() time.Time { return r.at },
+ Logf: func(format string, a ...any) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.logs = append(r.logs, strings.TrimSpace(fmt.Sprintf(format, a...)))
+ },
+ }
+ return r
+}
+
+func (r *confirmRig) count(prefix string) int {
+ n := 0
+ for _, l := range r.logs {
+ if strings.HasPrefix(l, prefix) {
+ n++
+ }
+ }
+ return n
+}
+
+func TestConfirmTerminatedOwner(t *testing.T) {
+ r := newConfirmRig(&fakeEC2{out: withRequestID(describe("111122223333", "i-b", types.InstanceStateNameTerminated), "req-1")})
+ ok, err := r.c.Terminated(context.Background(), "i-b")
+ if err != nil || !ok {
+ t.Fatalf("got %v, %v", ok, err)
+ }
+ if len(r.f.regions) != 1 || r.f.regions[0] != "eu-west-1" || len(r.f.ids[0]) != 1 || r.f.ids[0][0] != "i-b" {
+ t.Fatalf("called in %v for %v", r.f.regions, r.f.ids)
+ }
+ if r.count("termfence: describe i-b: terminated") != 1 {
+ t.Fatalf("logs %q", r.logs)
+ }
+ if r.count("termfence: i-b confirmed terminated (first evidence, request req-1)") != 1 || len(r.logs) != 2 {
+ t.Fatalf("logs %q", r.logs)
+ }
+}
+
+func TestConfirmStatesOtherThanTerminated(t *testing.T) {
+ for _, st := range []types.InstanceStateName{
+ types.InstanceStateNameRunning, types.InstanceStateNameStopped, types.InstanceStateNameStopping,
+ types.InstanceStateNameShuttingDown, types.InstanceStateNamePending,
+ } {
+ r := newConfirmRig(&fakeEC2{out: describe("111122223333", "i-b", st)})
+ ok, err := r.c.Terminated(context.Background(), "i-b")
+ if ok || err != nil {
+ t.Fatalf("%s: got %v, %v", st, ok, err)
+ }
+ if r.count("termfence: describe i-b: "+string(st)) != 1 || r.count("termfence: i-b confirmed") != 0 {
+ t.Fatalf("%s: logs %q", st, r.logs)
+ }
+ }
+ r := newConfirmRig(&fakeEC2{out: &ec2.DescribeInstancesOutput{}})
+ ok, err := r.c.Terminated(context.Background(), "i-b")
+ if ok || err != nil {
+ t.Fatalf("empty reply: got %v, %v", ok, err)
+ }
+ if r.count("termfence: describe i-b: not found") != 1 {
+ t.Fatalf("logs %q", r.logs)
+ }
+}
+
+func TestConfirmRefusesOtherAccountOrRegion(t *testing.T) {
+ r := newConfirmRig(&fakeEC2{out: describe("999999999999", "i-b", types.InstanceStateNameTerminated)})
+ ok, err := r.c.Terminated(context.Background(), "i-b")
+ if ok || err != nil {
+ t.Fatalf("other account: got %v, %v", ok, err)
+ }
+ if len(r.f.regions) != 1 || r.f.regions[0] != "eu-west-1" {
+ t.Fatalf("called in %v", r.f.regions)
+ }
+ if r.count("termfence: i-b confirmed") != 0 {
+ t.Fatalf("logs %q", r.logs)
+ }
+ // The identity check itself, without a describe.
+ good := FromDescribe(describe("111122223333", "i-b", types.InstanceStateNameTerminated), "i-b", "eu-west-1")
+ if err := SameAccountTerminated(confirmSelf, "i-b", good); err != nil {
+ t.Fatal(err)
+ }
+ bad := map[string]Observation{}
+ o := good
+ o.Region = "us-east-1"
+ bad["region"] = o
+ o = good
+ o.Via = ViaEvent
+ bad["event"] = o
+ o = good
+ o.InstanceID = "i-c"
+ bad["instance"] = o
+ o = good
+ o.Found = false
+ bad["notfound"] = o
+ for name, o := range bad {
+ if err := SameAccountTerminated(confirmSelf, "i-b", o); !errors.Is(err, ErrNotEvidence) {
+ t.Fatalf("%s: %v", name, err)
+ }
+ }
+ if err := SameAccountTerminated(confirmSelf, "i-a", good); !errors.Is(err, ErrNotEvidence) {
+ t.Fatalf("self: %v", err)
+ }
+}
+
+func TestConfirmRefusesSelfAndIncompleteIdentity(t *testing.T) {
+ r := newConfirmRig(&fakeEC2{out: describe("111122223333", "i-a", types.InstanceStateNameTerminated)})
+ ok, err := r.c.Terminated(context.Background(), "i-a")
+ if ok || err != nil || len(r.f.regions) != 0 {
+ t.Fatalf("self: got %v, %v, %d describes", ok, err, len(r.f.regions))
+ }
+ r.c.Self = func() boxid.Cloud { c := confirmSelf; c.Account = ""; return c }
+ ok, err = r.c.Terminated(context.Background(), "i-b")
+ if ok || err == nil || len(r.f.regions) != 0 {
+ t.Fatalf("incomplete: got %v, %v, %d describes", ok, err, len(r.f.regions))
+ }
+}
+
+func TestConfirmCachesPositiveForADay(t *testing.T) {
+ r := newConfirmRig(&fakeEC2{out: describe("111122223333", "i-b", types.InstanceStateNameTerminated)})
+ t0 := r.at
+ for _, at := range []time.Duration{0, 23 * time.Hour} {
+ r.at = t0.Add(at)
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); !ok || err != nil {
+ t.Fatalf("at %v: %v, %v", at, ok, err)
+ }
+ }
+ if len(r.f.regions) != 1 || r.count("termfence: i-b confirmed") != 1 {
+ t.Fatalf("describes %d, logs %q", len(r.f.regions), r.logs)
+ }
+ r.at = t0.Add(24*time.Hour + time.Second)
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); !ok || err != nil {
+ t.Fatalf("after a day: %v, %v", ok, err)
+ }
+ if len(r.f.regions) != 2 || r.count("termfence: i-b confirmed") != 1 || r.count("termfence: describe i-b") != 2 {
+ t.Fatalf("describes %d, logs %q", len(r.f.regions), r.logs)
+ }
+ if r.apis != 1 {
+ t.Fatalf("API built %d times", r.apis)
+ }
+}
+
+func TestConfirmErrorIsCachedBriefly(t *testing.T) {
+ boom := errors.New("throttled")
+ r := newConfirmRig(&fakeEC2{err: boom})
+ t0 := r.at
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); ok || !errors.Is(err, boom) {
+ t.Fatalf("got %v, %v", ok, err)
+ }
+ if r.count("termfence: describe i-b: throttled") != 1 {
+ t.Fatalf("logs %q", r.logs)
+ }
+ r.at = t0.Add(5 * time.Second)
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); ok || !errors.Is(err, boom) {
+ t.Fatalf("cached: got %v, %v", ok, err)
+ }
+ if len(r.f.regions) != 1 {
+ t.Fatalf("describes %d", len(r.f.regions))
+ }
+ r.at = t0.Add(11 * time.Second)
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); ok || !errors.Is(err, boom) {
+ t.Fatalf("after ttl: got %v, %v", ok, err)
+ }
+ if len(r.f.regions) != 2 {
+ t.Fatalf("describes %d", len(r.f.regions))
+ }
+}
+
+func TestConfirmNegativeCachedTenSeconds(t *testing.T) {
+ r := newConfirmRig(&fakeEC2{out: describe("111122223333", "i-b", types.InstanceStateNameRunning)})
+ t0 := r.at
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); ok || err != nil {
+ t.Fatalf("got %v, %v", ok, err)
+ }
+ r.at = t0.Add(9 * time.Second)
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); ok || err != nil || len(r.f.regions) != 1 {
+ t.Fatalf("cached: got %v, %v, %d describes", ok, err, len(r.f.regions))
+ }
+ r.f.out = describe("111122223333", "i-b", types.InstanceStateNameTerminated)
+ r.at = t0.Add(11 * time.Second)
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); !ok || err != nil || len(r.f.regions) != 2 {
+ t.Fatalf("after ttl: got %v, %v, %d describes", ok, err, len(r.f.regions))
+ }
+}
+
+// gatedEC2 answers every describe with out once release is closed, and
+// counts the calls. entered gets a value each time a describe starts.
+type gatedEC2 struct {
+ out *ec2.DescribeInstancesOutput
+ calls atomic.Int32
+ entered chan string
+ release chan struct{}
+}
+
+func (g *gatedEC2) DescribeInstances(_ context.Context, in *ec2.DescribeInstancesInput, _ ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error) {
+ g.calls.Add(1)
+ g.entered <- in.InstanceIds[0]
+ <-g.release
+ out := *g.out
+ out.Reservations = []types.Reservation{{OwnerId: g.out.Reservations[0].OwnerId,
+ Instances: []types.Instance{{InstanceId: aws.String(in.InstanceIds[0]), State: g.out.Reservations[0].Instances[0].State}}}}
+ return &out, nil
+}
+
+func (c *Confirmer) waitersFor(iid string) int {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if f, ok := c.inflight[iid]; ok {
+ return f.waiters
+ }
+ return -1
+}
+
+func TestConfirmConcurrentCallersShareOneDescribe(t *testing.T) {
+ const n = 8
+ g := &gatedEC2{out: describe("111122223333", "i-b", types.InstanceStateNameTerminated),
+ entered: make(chan string, n), release: make(chan struct{})}
+ r := newConfirmRig(&fakeEC2{})
+ r.c.API = func(context.Context, string) (EC2, error) { return g, nil }
+ var wg sync.WaitGroup
+ got := make([]bool, n)
+ errs := make([]error, n)
+ for i := 0; i < n; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ got[i], errs[i] = r.c.Terminated(context.Background(), "i-b")
+ }()
+ }
+ <-g.entered // the one describe is in flight; the rest must queue behind it
+ for r.c.waitersFor("i-b") != n-1 {
+ time.Sleep(time.Millisecond)
+ }
+ close(g.release)
+ wg.Wait()
+ for i := range got {
+ if !got[i] || errs[i] != nil {
+ t.Fatalf("caller %d: %v, %v", i, got[i], errs[i])
+ }
+ }
+ if g.calls.Load() != 1 || r.count("termfence: describe i-b") != 1 || r.count("termfence: i-b confirmed") != 1 {
+ t.Fatalf("describes %d, logs %q", g.calls.Load(), r.logs)
+ }
+ // The answer was cached before the waiters left.
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); !ok || err != nil || g.calls.Load() != 1 {
+ t.Fatalf("after: %v, %v, %d describes", ok, err, g.calls.Load())
+ }
+}
+
+func TestConfirmWaiterLeavesWhenItsContextEnds(t *testing.T) {
+ g := &gatedEC2{out: describe("111122223333", "i-b", types.InstanceStateNameTerminated),
+ entered: make(chan string, 2), release: make(chan struct{})}
+ r := newConfirmRig(&fakeEC2{})
+ r.c.API = func(context.Context, string) (EC2, error) { return g, nil }
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ r.c.Terminated(context.Background(), "i-b")
+ }()
+ <-g.entered
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ if ok, err := r.c.Terminated(ctx, "i-b"); ok || !errors.Is(err, context.Canceled) {
+ t.Fatalf("got %v, %v", ok, err)
+ }
+ close(g.release)
+ <-done
+}
+
+// ctxEC2 blocks its first describe until that describe's own context ends and
+// fails with the context's error; later describes answer out.
+type ctxEC2 struct {
+ out *ec2.DescribeInstancesOutput
+ calls atomic.Int32
+ entered chan struct{}
+}
+
+func (g *ctxEC2) DescribeInstances(ctx context.Context, _ *ec2.DescribeInstancesInput, _ ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error) {
+ if g.calls.Add(1) == 1 {
+ g.entered <- struct{}{}
+ <-ctx.Done()
+ return nil, ctx.Err()
+ }
+ return g.out, nil
+}
+
+// The caller performing the describe is the leader. When its context ends,
+// the waiters already joined get the leader's error, the error is cached
+// for the negative TTL like any other, and the next describe is a fresh one
+// made after it expires.
+func TestConfirmLeaderCancellation(t *testing.T) {
+ g := &ctxEC2{out: describe("111122223333", "i-b", types.InstanceStateNameTerminated), entered: make(chan struct{}, 1)}
+ r := newConfirmRig(&fakeEC2{})
+ r.c.API = func(context.Context, string) (EC2, error) { return g, nil }
+ t0 := r.at
+ const waiters = 3
+ type answer struct {
+ yes bool
+ err error
+ }
+ lctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ leader := make(chan answer, 1)
+ go func() {
+ yes, err := r.c.Terminated(lctx, "i-b")
+ leader <- answer{yes, err}
+ }()
+ <-g.entered // the leader's describe is in flight
+ joined := make(chan answer, waiters)
+ for i := 0; i < waiters; i++ {
+ go func() {
+ yes, err := r.c.Terminated(context.Background(), "i-b")
+ joined <- answer{yes, err}
+ }()
+ }
+ for r.c.waitersFor("i-b") != waiters {
+ time.Sleep(time.Millisecond)
+ }
+ cancel()
+ if a := <-leader; a.yes || !errors.Is(a.err, context.Canceled) {
+ t.Fatalf("leader: %+v", a)
+ }
+ for i := 0; i < waiters; i++ {
+ if a := <-joined; a.yes || !errors.Is(a.err, context.Canceled) {
+ t.Fatalf("waiter: %+v", a)
+ }
+ }
+ // Inside the negative TTL: no describe, the cached error.
+ r.at = t0.Add(ConfirmNegativeTTL - time.Second)
+ if yes, err := r.c.Terminated(context.Background(), "i-b"); yes || !errors.Is(err, context.Canceled) || g.calls.Load() != 1 {
+ t.Fatalf("within the TTL: %v, %v, %d describes", yes, err, g.calls.Load())
+ }
+ // After it: a fresh describe, which succeeds.
+ r.at = t0.Add(ConfirmNegativeTTL + time.Second)
+ if yes, err := r.c.Terminated(context.Background(), "i-b"); !yes || err != nil || g.calls.Load() != 2 {
+ t.Fatalf("after the TTL: %v, %v, %d describes", yes, err, g.calls.Load())
+ }
+}
+
+func TestConfirmPositiveIsNeverOverwrittenByANegative(t *testing.T) {
+ r := newConfirmRig(&fakeEC2{out: describe("111122223333", "i-b", types.InstanceStateNameTerminated)})
+ t0 := r.at
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); !ok || err != nil {
+ t.Fatalf("got %v, %v", ok, err)
+ }
+ // A later reply that says running, or fails, is not even asked for.
+ r.f.out = describe("111122223333", "i-b", types.InstanceStateNameRunning)
+ for _, d := range []time.Duration{11 * time.Second, time.Hour, 23 * time.Hour} {
+ r.at = t0.Add(d)
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); !ok || err != nil {
+ t.Fatalf("at %v: %v, %v", d, ok, err)
+ }
+ }
+ if len(r.f.regions) != 1 {
+ t.Fatalf("describes %d", len(r.f.regions))
+ }
+ // And a negative that finishes late, publishing over an unexpired
+ // positive, leaves the positive in place and answers with it.
+ late := &flight{done: make(chan struct{}), res: confirmed{}}
+ r.c.mu.Lock()
+ r.c.inflight["i-b"] = late
+ r.c.mu.Unlock()
+ r.c.publish("i-b", late)
+ if !late.res.yes {
+ t.Fatalf("late negative answered %+v", late.res)
+ }
+ r.at = t0.Add(23*time.Hour + 30*time.Minute)
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); !ok || err != nil || len(r.f.regions) != 1 {
+ t.Fatalf("after late negative: %v, %v, %d describes", ok, err, len(r.f.regions))
+ }
+}
+
+func TestConfirmConcurrentFirstCallsBuildOneClient(t *testing.T) {
+ const n = 6
+ f := &fakeEC2{}
+ r := newConfirmRig(f)
+ var built atomic.Int32
+ r.c.API = func(context.Context, string) (EC2, error) {
+ built.Add(1)
+ time.Sleep(20 * time.Millisecond) // long enough for every caller to arrive
+ return &safeEC2{out: describe("111122223333", "i-x", types.InstanceStateNameRunning)}, nil
+ }
+ var wg sync.WaitGroup
+ for i := 0; i < n; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if _, err := r.c.Terminated(context.Background(), "i-"+string(rune('b'+i))); err != nil {
+ t.Error(err)
+ }
+ }()
+ }
+ wg.Wait()
+ if built.Load() != 1 {
+ t.Fatalf("API called %d times", built.Load())
+ }
+}
+
+// safeEC2 answers any instance id with out's state, safe for concurrent use.
+type safeEC2 struct{ out *ec2.DescribeInstancesOutput }
+
+func (s *safeEC2) DescribeInstances(_ context.Context, in *ec2.DescribeInstancesInput, _ ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error) {
+ return describe(aws.ToString(s.out.Reservations[0].OwnerId), in.InstanceIds[0], s.out.Reservations[0].Instances[0].State.Name), nil
+}
+
+func TestConfirmClientConstructionFailureIsRetried(t *testing.T) {
+ r := newConfirmRig(&fakeEC2{})
+ boom := errors.New("no credentials")
+ calls := 0
+ r.c.API = func(context.Context, string) (EC2, error) {
+ calls++
+ if calls == 1 {
+ return nil, boom
+ }
+ return &safeEC2{out: describe("111122223333", "i-x", types.InstanceStateNameTerminated)}, nil
+ }
+ t0 := r.at
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); ok || !errors.Is(err, boom) {
+ t.Fatalf("first: %v, %v", ok, err)
+ }
+ // A different instance is not held back by the failure.
+ if ok, err := r.c.Terminated(context.Background(), "i-c"); !ok || err != nil {
+ t.Fatalf("i-c: %v, %v", ok, err)
+ }
+ r.at = t0.Add(11 * time.Second)
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); !ok || err != nil {
+ t.Fatalf("retry: %v, %v", ok, err)
+ }
+ if calls != 2 {
+ t.Fatalf("API called %d times", calls)
+ }
+}