carlos / platform Public

Region HA P1b-1 plan rev 3: N-HA9 (takeover only after expiry; early rows and settle cut), round 2 P2 fixes, round 3 brief

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 1f187aeaf13ec5dac292629d0dcbcff99d18a7cb parent c98b239
3 files changed, +231 −114
  • docs/superpowers/plans/2026-10-27-region-ha-p1b1-takeover.md +106 −114
  • docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-BRIEF-3.md +72 −0
  • docs/superpowers/plans/CODEX-PLAN-REGION-HA-P1B1-R2.md +53 −0

CI passed — run details

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
index b38ae0b1e..661d8cc02 100644
--- a/docs/superpowers/plans/2026-10-27-region-ha-p1b1-takeover.md
+++ b/docs/superpowers/plans/2026-10-27-region-ha-p1b1-takeover.md
@@ -1,53 +1,57 @@
-# Region HA P1b-1: takeover and fast re-take Implementation Plan
+# 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 within minutes, and a host whose agent crashed comes back on the same box within seconds of the agent's restart, instead of after the 15-minute lease.
+**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 two rows: a lock owned by another box whose instance EC2 confirms `terminated` is taken, expired or not; and this box's own lock is taken before expiry with the existing same-box proof.
+- **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 both proofs to `lease.AcquireHA`. Every takeover is request-driven: the first request for the host at a survivor runs the acquire.
+- **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, §9.6, and Paul's ruling N-HA8 below. P1a's plan, `docs/superpowers/plans/2026-10-26-region-ha-p1a-first-slice.md`, is the base this slice changes.
+**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 2, for Astra round 2 of 3. Round limit: three Astra rounds (stopping rule); a P1 in round three goes to Paul as a cut.**
+**Status: rev 3, for Astra round 3 of 3 (final). A P1 in round 3 goes to Paul as a cut; no fourth round.**
-## Round 1 dispositions (`CODEX-PLAN-REGION-HA-P1B1-R1.md`)
+## Rulings
-| Finding | Disposition |
-|---|---|
-| r1.1 P1: a dead process's already-sent upload can land after the takeover's restore | **Accepted, by a settle rule, not storage fencing.** Every take of a lock that a dead process held (the terminated owner's, and this box's own) waits `hafresh.SettleAfterDeath`, 60 s, after the death is first known: for a termination, after this box first saw `terminated`; for the same box, after this agent process started (the old process died before it). A request a dead sender already put on the wire either completes or is abandoned by S3 well inside that (the kernel flushes or resets within seconds, S3 drops an idle request after about 20 s, and a fully received PUT commits in seconds). This is a time margin of the same kind P1a's expiry gives; generation-isolated replica and manifest fencing is a later design (follow-ups). Task 5 models the late upload and a `no-settle` mutation. |
-| r1.2 P1: a partial initial identity never retries | Accepted. `hafresh.Self.Complete()` is the one predicate; `agent.go:232` starts the retry on `!Complete()`, the retry ends on `Complete()`. Task 3 adds a production-entry test and updates the existing fixture. |
-| r1.3 P1: `early-retake-own-process` cannot be caught | Accepted. Replaced by `early-retake-live-process` with a racing duplicate-wake action and an acquire-time oracle (Task 5). |
-| r1.4 P2: I5 fairness | Accepted. Termination visibility is world truth, independent of the confirmer; I5 needs an eligible survivor and is checked after a fault-free, post-settle wake attempt by each one. |
-| r1.5 P2: graceful stop/terminate writes a marker | Accepted. The drill uses `--skip-os-shutdown`, checks C's lock is a non-marker lock before and after, observes the stop through expiry, and records confirmation and restore separately. |
+**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).
-## Ruling N-HA8 (Paul, 2026-10-27)
+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.
-P1b is cut into slices. This slice, P1b-1, is two things only:
-1. **Takeover on confirmed termination** (§9.2, §9.4), request-driven. No SQS consumer, no scan, no duties.
-2. **Same-box re-take before expiry.** §9.6's "later improvement" moves forward. Evidence: in the 2026-10-27 kill drill on dev, the nested unit stopped 4 ms after the agent died (`BindsTo=carlos-edge.service`), and the restarted agent's sweep proved it gone at once, yet the host stayed down 13m54s waiting for its own lease to expire.
+Task 1 writes both rulings into the spec.
-Why now: under P1a, a born-HA host on a dead box never comes back, which is worse than a legacy host.
+## Round history
-Deferred to later slices: 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.
+| 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 |
-Task 1 writes this ruling into the spec (§2's rulings, §9.6's last bullet, §19's plan table).
+| 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.
-- **Cache:** a confirmed termination is kept 24 h; a "not terminated" answer, or an error, 10 s, per instance id. At most one describe per instance id per 10 s per box.
+- **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 instance id, account or region is unknown (`lease.ErrNoSelf`). A lock without `iid=` can never be confirmed terminated or re-taken.
-- **Settle:** `hafresh.SettleAfterDeath = 60 * time.Second`. A terminated owner's lock is taken only once this box first saw `terminated` at least that long ago; this box's own lock (expired or not) only once this agent process has run at least that long. Until then the wake answers held (unexpired) or refused (expired), as without proof.
-- **Same-box before expiry** needs exactly P1a's proof (`sameBoxProven`): nested containment, this agent's startup sweep, the host never acquired by this process, the host slice and flat cgroup empty. Nothing weaker.
+- **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 refused or held wake against a live other box adds at most one describe per 10 s per owner instance id. Non-HA hosts: unchanged.
+- **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.
@@ -57,59 +61,57 @@ Task 1 writes this ruling into the spec (§2's rulings, §9.6's last bullet, §1
## 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 held or refused, the failure is cached 10 s, and the next request tries again. Task 2: `TestConfirmErrorIsCachedBriefly`; Task 4: `TestTakeoverDescribeFailureKeepsHostDown`.
+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. **This process's own live lock** (a second wake for a host this process already holds). The proof's "acquired here" check keeps it held, never re-taken. Task 4: `TestOwnLiveLockIsNeverRetaken`.
+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`.
-6. **An upload the dead process already sent** lands after the take. The settle rule keeps the take behind it. Task 5: the `late-upload` action and the `no-settle` witness; Task 2: `TestConfirmWaitsTheSettle`; Task 4: `TestSameBoxWaitsTheSettle`.
---
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 lock, and this box's own lock before expiry [own review]
+### 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:13` (`Self`)
-- Test: `internal/hafresh/acquire_test.go`
-- Modify: `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` (§2, §9.4, §9.6, §19: N-HA8)
+- 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 SettleAfterDeath = 60 * time.Second` (the settle rule; the proofs apply it, `DecideAcquire` does not).
- - `const ReasonTerminated = "holder terminated"`, `const ReasonSameBoxEarly = "same box, proven empty, before expiry"`. The existing `"same box, proven empty"` reason becomes `const ReasonSameBox`.
+ - `const ReasonTerminated = "holder terminated"`. The existing take reason `"same box, proven empty"` becomes `const ReasonSameBox`.
-The new table, in this order:
+The table, in this order. Only the bold row is new:
| Lock | Proof | Decision |
|---|---|---|
-| absent | | create (unchanged) |
-| not HA-format | | refuse, leftover lock (unchanged) |
-| release marker | | take (unchanged) |
-| HA owner, unparseable | | refuse, malformed marker (unchanged) |
-| owner IID is self.IID (non-empty), expired | SameBoxEmpty true | take, `ReasonSameBox` |
-| owner IID is self.IID, expired | missing, false or error | refuse, `ReasonSameBoxUnsure` (unchanged) |
-| owner IID is self.IID, unexpired | SameBoxEmpty true | take, `ReasonSameBoxEarly` |
-| owner IID is self.IID, unexpired | missing, false or error | held by the owner |
-| owner IID is another non-empty IID, expired or not | OwnerTerminated(o.IID) true | take, `ReasonTerminated` |
-| owner IID another, unexpired | missing, false or error | held by the owner |
-| owner IID another or empty, expired | missing, false or error | refuse, `ReasonOtherExpired` (plus `": " + err` on an error) |
-
-`OwnerTerminated` is never called for this box's own IID or for an empty one. `SameBoxEmpty` is never called for another box's lock.
-
-- [ ] **Step 1: Write the failing tests** in `acquire_test.go`:
- - `TestDecideAcquireTable`: the row `{unexpired, mine, yes}` changes from `ActHeld` to `ActTake`. Add rows: `{unexpired, other, terminated}` → `ActTake`; `{expired, other, terminated}` → `ActTake`; `{unexpired, other, notTerminated}` → `ActHeld`; `{expired, other, terminatedErr}` → `ActRefuse`; `{unexpired, mine, no}` → `ActHeld`; `{unexpired, mine, broken}` → `ActHeld`.
- - `TestDecideAcquireReasons`: the three take reasons are `ReasonSameBox`, `ReasonSameBoxEarly`, `ReasonTerminated`; an error from `OwnerTerminated` on an expired lock gives a reason starting `ReasonOtherExpired + ": "`.
- - `TestDecideAcquireProofScope`: with proofs that record their calls, `OwnerTerminated` is called once with `"i-b"` for another box's lock and never for this box's or an `iid`-less owner's; `SameBoxEmpty` is never called for another box's lock.
- - `TestDecideAcquireStoppedOwnerIsNotTaken`: `OwnerTerminated` answering false, on an unexpired and on an expired lock of `i-b`: `ActHeld`, then `ActRefuse`.
-- [ ] **Step 2: Run** `nice -n 19 go test ./internal/hafresh -run 'TestDecideAcquire' -count=1`. Expected: FAIL (the new fields and constants are undefined).
-- [ ] **Step 3: Implement** the table above in `DecideAcquire(v View, self Self, now time.Time, p Proofs) Decision`, and the `Self` fields. Update the doc comment's bullet list to the new table.
+| 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 into the spec:** add it under §2's rulings; in §9.4's table, the row "Expired, owner is this box's instance id" becomes "Expired or unexpired, owner is this box's instance id"; §9.6's last bullet becomes "Same-box takeover before expiry: P1b-1 (N-HA8)"; §19's table gains a P1b-1 row above P1b. Two sentences each, no more; §9.4 also gains the settle rule (r1.1) as one sentence.
-- [ ] **Step 6: Commit** `region-ha p1b-1: the acquire table takes a terminated owner's lock and this box's own before expiry`.
+- [ ] **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]
@@ -121,18 +123,18 @@ The new table, in this order:
- 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; Settle time.Duration; /* unexported cache, mutex */ }`. The agent sets `Settle` to `hafresh.SettleAfterDeath`; zero means no wait (tests only).
- - `func (c *Confirmer) Terminated(ctx context.Context, iid string) (bool, error)`: one describe per miss through `DescribeInstance(ctx, api, boxid.Cloud{Provider: "aws", Account: self.Account, Region: self.Region, InstanceID: iid})`; evidence when `SameAccountTerminated` is nil. The first evidence for an iid records `firstSeen`; `Terminated` answers true only once `now - firstSeen >= Settle`, and until then `(false, nil)` with no further describe. `ErrNotEvidence` answers `(false, nil)`; any other error `(false, err)`. A true answer is cached `24 * time.Hour`; false and errors `10 * time.Second`. `API` is called lazily, once, and its client kept.
+ - `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):
- - `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.
+- [ ] **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; a call at 24 h + 1 s makes a second.
+ - `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.
- - `TestConfirmWaitsTheSettle`: `Settle` 60 s; `terminated` at t0 → `(false, nil)`; at t0 + 59 s → false with no second describe; at t0 + 60 s → true, still one describe in all.
- `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.
@@ -144,12 +146,11 @@ The new table, in this order:
**Files:**
- Modify: `internal/host/haself.go` (`haSelfNow`, `haSelfRetry`, `readInstanceID` → `readIdentity`)
- Modify: `internal/host/agent.go:232` (the retry starts on `!self.Complete()`)
-- Modify: `internal/hafresh/owner.go` (`func (s Self) Complete() bool`: `Ref`, `IID`, `Account`, `Region` all non-empty)
- 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` (Task 1).
+- 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).
@@ -161,82 +162,73 @@ The new table, in this order:
- `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' -count=1` and `nice -n 19 go test ./internal/lease -run 'TestAcquireHARefusesWithout' -count=1`. Expected: FAIL.
-- [ ] **Step 3: Implement** the three 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 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 both proofs to the HA acquire; the agent wires the confirmer [own review]
+### 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/hasamebox.go` (`sameBoxEmpty`'s log and the alarm wording)
- 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/hasamebox_test.go`, `internal/activator/hatakeover_test.go` (create), `internal/lease/ha_test.go`, `internal/host/agent_layout_test.go` or the nearest existing agent-wiring test
+- 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 (another box's lock stays held or refused, 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); taking the host over`. On an error it logs at most once a minute per host, through the existing `sameBoxState.alarm` throttle or a twin of it.
- - `lease`: the acquire's log word comes from the decision's reason: `first wake`, `clean marker`, `unclean marker`, `same-box takeover`, `same-box takeover before expiry`, `holder terminated`. `classifyAndTake`'s callback keeps the last `hafresh.Decision` it saw so the log names the round that won.
- - `ExecBackend.ProcessStarted time.Time`, set by the agent when it builds the backend. `sameBoxProven` gains a last check: `time.Since(b.ProcessStarted) >= hafresh.SettleAfterDeath` (through the backend's clock seam), else `"this agent process has run %s; a same-box take waits %s after the old process's death"`. A zero `ProcessStarted` refuses. This applies to both same-box rows. The settle refusal is not an alarm: it logs once per host, not through `sameBoxState.alarm`.
- - The agent builds one `termfence.Confirmer` (with `Settle: hafresh.SettleAfterDeath`) 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`.
+ - `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`, unexpired; `OwnerTerminated` answers true for `i-b`. The wake acquires, the lock's new owner names this box with generation + 1, and the wake restores (`haWake.view` has no marker, the keep reason is `no-marker`).
- - `TestTakeoverDescribeFailureKeepsHostDown`: `OwnerTerminated` answers an error. The wake fails with `errLeaseHeld` (unexpired) or `errLeaseRefused` (expired); the lock is unchanged.
- - `TestNoTakeoverWithoutTheOracle`: `OwnerTerminated` nil; an unexpired lock of `i-b` is held, an expired one refused, nothing written.
- - `hasamebox_test.go`, `TestSameBoxRetakeBeforeExpiry`: `sameBoxReady(b)`; the lock is this box's (`iid` equal to self's), another pid, unexpired. The wake acquires, logging `same-box takeover before expiry`.
- - `TestSameBoxWaitsTheSettle`: as above with `ProcessStarted` 30 s ago → `errLeaseHeld`, nothing written; at 61 s → acquired. The same for an expired own lock (`errLeaseRefused`, then acquired).
- - `TestOwnLiveLockIsNeverRetaken`: as above, but `markAcquiredHere(b, host)` first. The wake fails with `errLeaseHeld`; nothing written.
- - `TestSameBoxAlarmWordingIsNotAboutExpiry`: the alarm text no longer claims the lock expired (it says "this box's HA lock").
+ - `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|TestSameBox|TestOwnLiveLock' -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 words, the alarm wording and the agent wiring.
+- [ ] **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, and its own before expiry`.
+- [ ] **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 and re-takes early [own review]
+### Task 5: The simulation terminates boxes [own review]
**Files:**
-- Modify: `internal/sim/regionha/world_test.go` (a `terminated` box state, the confirmer's view), `actions_test.go` (`terminate`, `decideAcquire`'s proofs), `invariants_test.go` (`checkLiveness`), `rules_test.go` (new rules), `witness_test.go` (one witness per new rule), `sim_test.go` (the action mix)
+- 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 both proofs (Task 1). The model drives the real decision; mutations change only what the model hands it.
+- 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, since the machine is gone), the box's disk and local copies gone, and the box never restarts. `w.terminated[b.IID] = true` becomes visible to the confirmer only after a delay of 1 to 12 ticks (EC2's lag).
- - **Termination truth** (`w.terminated[iid]`, the tick it happened) is the world's, read by the oracles; the confirmer is a separate model function that the mutations change. The confirmer answers true only `Settle` ticks (6) after its first evidence, and a seeded 10 % of its calls answer an error while faults are on.
- - `decideAcquire` passes `OwnerTerminated: w.confirmer(b)` and a `SameBoxEmpty` that also checks the process has run `Settle` ticks.
- - **`lateUpload`** (r1.1): when a process dies (crash or terminate) with an upload in flight (a replica write or a manifest write it had begun), the upload lands at a seeded tick 0 to 4 after the death (always under `Settle`). Its write goes through the existing `replicaWrite` / `manifestWrite` with the dead pid. The existing writer oracle fails I1 if it lands after another process took the lock.
- - **`duplicateWake`** (r1.3): a second wake attempt for a host that has an entry on this box, between `stopMain` and the release (the window where the slice reads empty and the lease is still this process's). It calls `acquireHA`; the acquire-time oracle fails I1 when a take's classified lock names this box's current live pid.
- - **I5 after a termination** (r1.4): at the end of a run, if a host's lock names a box that is terminated in truth and some live box of the host's pool exists, the model turns faults off, advances past `Settle`, gives each such box one wake attempt, and only then fails I5 if no box holds the host. With no eligible survivor, I5 does not apply.
+ - `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 model answers `OwnerTerminated` true for a box that is hung or alive. Expected: I1 (two holders, or a write by a box that no longer holds).
- - `"early-retake-live-process"`: the model drops the "acquired here" check from `sameBoxEmpty`. Witness: `duplicateWake` in the stop window. Expected: I1 (the acquire-time oracle).
- - `"no-settle"`: the confirmer and the same-box proof ignore `Settle`. Witness: a terminate with an upload in flight landing at tick 3, a survivor's wake at tick 2. Expected: I1 (the late write after the take).
- - `"no-takeover"`: the model never confirms. Expected: I5 (stranded host).
+ - `"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 four witnesses** (`takeover-unconfirmed`, `early-retake-live-process`, `no-settle`, `no-takeover`) in `witness_test.go` (each a short scripted run that fails only under its rule) and add the rules to `allRules`.
+- [ ] **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`, the confirmer's lag and settle, `lateUpload`, `duplicateWake`, the acquire-time oracle, the I5 phase and the action mix (terminate at about the rate of `crash`).
+- [ ] **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 and re-takes before expiry`.
+- [ ] **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.
+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; no `LEASE HELD` for hosts other than the drill's.
-- [ ] **Step 2: Agent-crash drill.** With `hapair-a1` awake on leo and probes through both boxes every 5 s: `kill -9` leo's agent. Expected: after the agent's restart, `HA lease acquired ... (same-box takeover before expiry)` on leo, `restored (no-marker)`, rows intact; sophie answers held, never takes. **Pass: kill to first 200 under 90 s** (the 60 s settle plus the restart).
-- [ ] **Step 3: 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`. 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 4: 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 (no graceful shutdown, so no marker), and read `lock.json` again: unchanged. Probe through leo and sophie every 5 s until 5 minutes past the lock's `expires_at` (about 20 minutes). Expected: held until expiry, refused after; never taken; at most one describe per 10 s per box (agent logs).
-- [ ] **Step 5: 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 EC2 reports `terminated` and the settle has passed, then `the holder ... is terminated (EC2); 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: terminate call, first `terminated` evidence on each survivor, the take, `restored`, first 200. **Pass: no write lost before the last second, no take before the settle; target terminate to first 200 under 3 minutes (§9.8's estimate). Over 3 minutes is a reported deviation with the components, not a failure.**
-- [ ] **Step 6: 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 7: Report** on the branch's amadan discussion: the three timelines, describe counts, and any deviation.
+- [ ] **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`. 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
@@ -244,8 +236,8 @@ Agent-run changes only (`internal/hafresh`, `internal/termfence`, `internal/leas
## Spec gaps and follow-ups
-- **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; the drill's pre-check reads every HA lock on dev for one.
-- **Storage fencing** (r1.1): replica and manifest writes carry no ownership generation. The settle rule is a time margin; a generation-isolated layout (or conditional publication bound to the lock's generation) is a later design, needed before any rule shortens the settle.
-- **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 5 notes whether dev sees it.
+- **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-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-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