Plan region HA G2 drill-4 fixes
1 file changed,
+958
−0
docs/superpowers/plans/2026-11-06-region-ha-g2-fixes.md+958 −0
diff --git a/docs/superpowers/plans/2026-11-06-region-ha-g2-fixes.md b/docs/superpowers/plans/2026-11-06-region-ha-g2-fixes.md| new file mode 100644 |
| index 000000000..c3d229f7b |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-06-region-ha-g2-fixes.md |
| @@ -0,0 +1,958 @@ |
| +# Region HA G2 drill-4 fixes: implementation plan |
| + |
| +> For agentic workers: execute one task at a time, with the named tests before |
| +> the implementation. The controller dispatches each implementation task to |
| +> **Astra (`gpt-6-astra`) via Codex**, with the model named explicitly. This |
| +> document is a plan, not approval to run infrastructure operations. |
| + |
| +**Goal:** An out-of-pool box forwards a pooled host without ever acquiring, |
| +waking or serving it locally; a holder that loses its lease refuses promptly; |
| +peers stop trusting silent holders; suspect-holder pages use lease expiry and |
| +have an explicit, scoped SNS permission. I-Pool: no ineligible box starts new |
| +lease ownership, wakes or serves a pooled host. A previously acquired handle |
| +may remain only to finish a proven stop/release; withdrawal never drops it |
| +early to satisfy the wording. I-Loss: after local loss is latched, every new |
| +request on that box answers within one second until legitimate recovery. |
| +I-Forward: cancellation/silence cannot confirm ownership or replay a request. |
| +I-Page: the observed expired lease, not request arrival, dates suspicion. |
| + |
| +**Architecture:** Use the parsed `ReconcileConfig.Pools` as local configuration |
| +and `edgesfile.PoolEvidence.Serves` as the single membership predicate. Apply |
| +that predicate at authority boundaries as well as routing decisions. Keep an |
| +in-memory ingress projection separate from installable registry rows, so |
| +removing a stale row cannot remove the US ingress's ability to forward. Pool |
| +withdrawal is a separate, conservative cleanup operation. Lease-loss refusals |
| +are independent of slow stop completion. Forward silence is evidence for the |
| +existing bounded cache revalidation, never permission to acquire or replay. |
| + |
| +**Tech Stack:** Go, SQLite registry, conditional S3 leases, existing Litestream |
| +replication, signed edge backhaul, Linux systemd/cgroup v2, Terraform modules, |
| +Python witness drivers, MinIO-compatible S3 on the disposable runner. |
| + |
| +**Spec:** `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md`, |
| +§3/I1, §6.1–6.7, §7, §9.4–9.6 and §20; existing N-HA7, N-HA9, N-HA12 and |
| +N-HA15 rulings. Base: `25ca6faf` on `region-ha-g2-fixes`. All existing-code |
| +references below were relocated in this tree, not copied from v0.34.7. |
| + |
| +## Global Constraints |
| + |
| +- One platform branch. First merge includes the observable F-B and F-A fixes, |
| + their witnesses and census approval. No scaffolding-only merge or new off |
| + switch. These repair already-enabled behavior; release/switch-on scheduling |
| + belongs to the controller. Planning finishes with this file committed, no |
| + push. Implementation finishes at the reviewed branch handoff, not a release. |
| +- In: all F-B enforcement points, pool-withdrawal cleanup, termination error |
| + classification, the bounded F-A fixes, F-D code/module IAM, and follow-up |
| + notes. Out: F-C/write fencing or durability promises, F-E code, T1 terminate |
| + drill, S3 cancel-and-join implementation, release/apply/drill and dev changes. |
| +- No AWS calls or box operations during implementation. Root witnesses are |
| + run later by the controller on a throwaway root runner and disposable peer, |
| + under the scoped approval |
| + described in Tasks 10–11. A dev-account profile is not approval to use dev |
| + boxes. Root/pinfra edits are a separate branch + PR, left unmerged/unapplied. |
| +- Preserve expiry **and** termination for foreign takeovers, cgroup-empty |
| + proof for same-box recovery, conditional writes, lifetime checks, and the |
| + existing stop-before-release order. A routing hint is never authority. |
| +- Pool membership is a hard tenancy boundary. A20's low-headroom fallback |
| + stays within that boundary. N-HA7's switch-off fallback stays available only |
| + to a box eligible for the pool. The clarification does not alter either |
| + ruling. Never add `ha` to the old US box's pools to make ingress work. |
| +- Wire changes are additive. Prefer no new wire fields: the ingress projection |
| + below uses existing instance records and name-resolution evidence. Never |
| + write a forwarding-only row as a normal route or advertise it as `home`. |
| +- Keep one signed hop. §6.5 automatic retry is still deferred by N-HA8. Do not |
| + implement it here. An uncertain forward is never replayed, including a GET. |
| +- Local verification is touched packages with `-run` and `-count=1` only; |
| + expect `ok` and no skips in required cases. CI on amadan runs the full |
| + build/vet/test/format gate and cross-builds. Use default Go caches. |
| +- Socket tests use `TMPDIR=/tmp/g`, as this commission explicitly requires; |
| + treat it as the exception for those test subprocesses only. Keep binaries, |
| + logs and other scratch under the normal on-disk `$TMPDIR`. Remove only this |
| + run's scratch. Bind listeners to loopback, never all interfaces. No sudo. |
| +- Cross-compile affected CLI dependencies with `CGO_ENABLED=0` for |
| + darwin/amd64, windows/amd64 and linux/arm64. Use `go build` on package paths, |
| + or explicit `-o "$TMPDIR/..."` for binaries; no binary in the checkout. |
| +- Test child CLI commands use `carlosTestEnv` and a scratch `cmd.Dir`. Scripts |
| + fail closed if pointed at a deployed machine or an unowned resource. |
| +- The copy table is a draft deck for **one Luna pass**, applied verbatim by |
| + implementers before final tests. No em dashes in new visible text. Region |
| + names use labels such as `Dublin (IE)`. Logs and error codes are not copy. |
| +- Commit subjects are at most 79 characters. Each task stages only its files. |
| + Never push or merge to GitHub. Future implementation landing uses the |
| + described amadan branch, green CI on its exact tip and squash merge. |
| + |
| +## Evidence and review budget |
| + |
| +Read `~/.cache/region-ha-next/{G2-FINDINGS.md,G2-RESULTS.md,g2-log.md}` together. |
| +The findings are a causal analysis, not proof of every timing hypothesis: |
| +renewal retry timing and the blocked final sync are inferred because the |
| +holder journal was lost. Do not claim this branch fixes all causes of the |
| +32-minute outage. The cleanup already returned the host to an eligible box; |
| +the findings' “dev cleanup now” is historical, not an instruction to act. |
| + |
| +Earlier P1b-3 placement plan review closed at round 2 with no P1; N-HA12 |
| +settled the repeated recovery family. Spec, P1b-1, P1b-2 and dead-holder |
| +backoff used three rounds and remain closed. Do not reopen them. G2's RCA had |
| +one independent Astra read, recorded at the end of G2-FINDINGS; it returned |
| +PARTLY and its corrections were incorporated. No formal review of this new |
| +implementation plan has been run in this planning commission. The controller |
| +must carry any additional existing G2-fix review history into each brief, |
| +never reset a round count by renaming/splitting tasks. |
| + |
| +F-B gets one grouped **Opus** review after Tasks 1–4 and its witness. F-A gets |
| +one grouped **Opus** review after Tasks 5–7 and its witness. F-D and IAM receive |
| +security/root scrutiny in the single whole-branch **Opus or Fable** review, |
| +including the census. Use `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`. |
| +Stop each review at the first round without P1; fix P2s without reopening; |
| +record P3s for follow-up. At most three rounds for a change; a fourth requires |
| +Paul's decision. Two consecutive rounds in one fault family stop further |
| +fixes: offer refusal, feature cut, or one invariant plus a seeded simulation. |
| +The census and any newly changed security/root/termination/storage behavior |
| +still need approval within that budget. This is not permission for unlimited |
| +“verification” rounds. |
| + |
| +## Review Focus |
| + |
| +| Input most likely to escape ordinary tests | Owning task and required test | |
| +|---|---| |
| +| Own edges file missing/stale, switch off, or stale awake entry while configured pool membership says no | T1/T2 `TestPoolGateCannotFallBackLocal` covers each path, including clean and unclean markers. | |
| +| The old US ingress has no registry row, or a row is removed between lookup and dispatch | T2/T10 `TestHAIngressWithoutLocalRow` and `TestRootG2PoolIngress` cover held/free/unknown/no-peer and a verified hop. | |
| +| Withdrawal races a wake, route lifetime change, failed marker PUT or pending duties | T3 `TestPoolWithdrawalRequiresCompleteProof` checks exact-row deletion and preservation on every failure. | |
| +| Lost entry is forgotten while release is blocked; a late renewal/forward completion arrives | T5/T6 `TestHALostLatchSurvivesEntryRemoval`, `TestRenewAttemptLateSuccessCannotRestoreHealth`; T7 generation-race cases. | |
| +| First takeover refusal arrives well after expiry, under a different lease generation; alert permissions exist on the wrong topic | T8 `TestSuspectHolderUsesObservedExpiry`; T9 `TestHAAlertPublishScope` checks exact actions/resources in both deployment shapes. | |
| + |
| +## Task 1: F-B, one pool predicate and acquire authority |
| + |
| +**Correction to findings:** `edgesFileServedPools` is now at |
| +`internal/host/edgesfile.go:1406`; `PoolEvidence.Serves` already exists at |
| +`internal/edgesfile/servedpools.go:42`. `poolServed` is at |
| +`internal/provision/reconcile.go:3471`; the source is |
| +`provisionTickConfig` at `internal/host/agent.go:3761`, not the asynchronously |
| +published edges file. `hafresh.DecideAcquire:72` still accepts any marker. |
| + |
| +**Files:** `internal/provision/reconcile.go`, new `internal/provision/pools_test.go`; |
| +`internal/host/{edgesfile.go,agent.go}`; `internal/activator/{backend_exec.go, |
| +hawake.go,haadopt.go,backend_unit.go}`; `internal/hafresh/{acquire.go,acquire_test.go}`; |
| +`internal/lease/ha.go`; targeted pool/acquire tests beside them. |
| + |
| +**Interfaces:** |
| + |
| +- Add `func (cfg ReconcileConfig) ServedPools() edgesfile.PoolEvidence`. |
| + Move the normalization from `edgesFileServedPools` here. Unconfigured local |
| + pools mean exactly `[""]`; explicit invalid-only configuration means `[]`, |
| + not shared. `@shared` is parsed to `""` by `ParseBoxPools` as today. |
| +- Keep `PoolEvidence.Serves(pool string) bool` as the **one membership rule**. |
| + `poolServed`, publication and all new gates call it, not another contains |
| + implementation. Missing/malformed **remote** evidence denies membership; |
| + never apply the local default to a missing remote field. |
| +- Add `ExecBackend.ServedPools func() edgesfile.PoolEvidence`, wired before |
| + service startup from `provisionTickConfig(os.Getenv).ServedPools()`; tests |
| + supply explicit evidence. Add `func (b *ExecBackend) poolEligible(rt |
| + registry.Route) bool` and a SplitBackend dispatcher. No request-time S3. |
| +- Add `hafresh.Proofs.LocalEligible func() bool`. Nil/false refuses with |
| + `ReasonPoolIneligible = "ha_pool_ineligible"` before every acquire-table |
| + arm. This is a Go API change, not a lock-format change. Update every |
| + production constructor and explicit eligible test fixture; do not add a |
| + nil-means-allow compatibility bypass. |
| + |
| +**Steps:** |
| + |
| +- [ ] Write `TestConfiguredAndPublishedPoolsAgree`: unset, `@shared`, named, |
| + mixed, duplicates, invalid-only, invalid alongside valid. Publication and |
| + reconcile agree for every valid route pool. Missing/null/malformed remote |
| + evidence and `[]` never serve a named pool. |
| +- [ ] Write `TestAcquireHAPoolEligibility`: ineligible self with absent lock, |
| + clean marker, unclean marker, lifted tombstone, own expired lock, foreign |
| + terminated owner, and unexpired owner. Zero acquire PUTs, prefix LISTs, |
| + termination calls, restore/spawn and duty imports on refused paths. |
| +- [ ] Check eligibility in the backend **before** legacy/HA selection, so a |
| + stale non-HA registry stamp cannot enter legacy acquire first. Check |
| + `AdoptHost` before import/phase writes. Bind the same callback into visitor, |
| + duty and adoption HA proofs. `acquireHARestricted` checks it before owed |
| + settlement/client work and each CAS round; `DecideAcquire` checks it too. |
| + Existing release obligations still settle through their own retry path. |
| +- [ ] Recheck at spawn and existing-awake duty admission. In `DecideDuty`, a |
| + local denial must precede `OwnedAwake`; do not let an old awake entry confer |
| + new duties after withdrawal. This adds no rule permitting adoption or take. |
| +- [ ] Narrow the spec's §3 “every tenant host” to hosts in pools the box serves; |
| + §6.1 states that ineligible ingress forwards/refuses and never hosts. Add |
| + the pool precondition to I1's acquire authority, with §6.2/§6.3 interpreted |
| + inside it. Do not edit F-C or any durability ruling. |
| +- [ ] Run `go test ./internal/hafresh ./internal/lease ./internal/provision -run 'TestConfiguredAndPublishedPoolsAgree|TestAcquireHAPoolEligibility|Test.*Pool' -count=1`. |
| + Run `TMPDIR=/tmp/g go test ./internal/activator ./internal/host -run 'TestAcquireHAPoolEligibility|Test.*Pool|Test.*Adopt|Test.*Duty' -count=1`. |
| + Expect all named new tests to execute and pass; first observe their failure |
| + with the membership guard removed, then restore it. |
| +- [ ] Commit: `ha: enforce configured pool membership at acquisition`. |
| + |
| +## Task 2: F-B, forwarding survives loss of the local row |
| + |
| +**Correction to findings:** `forwardTarget` still bypasses decisions for |
| +**any** entry at `internal/activator/haforward.go:134`; awake serve is |
| +`activator.go:1843`. `wakeplacement.go:185` checks ordinary peers' host/account/ |
| +app, while only sidecars check pool membership. `edge.go:2129`'s lookup miss |
| +uses ordinary backhaul; `frontForwardHA` is later, at `edge.go:2168`. The |
| +current per-host edges shape does not carry enough HA/pool route information |
| +to reconstruct that decision. A removed row therefore cannot be handled by |
| +“just use ForwardTarget”. Regional names have their own gate before this. |
| + |
| +**Files:** `internal/edge/{edge.go,forwardha.go,wakeplacement.go, |
| +haingress.go,haingress_test.go}`; `internal/activator/{activator.go,haforward.go, |
| +haplacement.go,ha_pool_test.go}`; new `internal/provision/haingress.go` and |
| +`internal/host/haingress.go`, their tests, host wiring; the spec from T1. |
| + |
| +**Interfaces:** |
| + |
| +- Add `func (sn *ViewSnapshot) HAIngressRoutes(region string) |
| + (map[string]registry.Route, error)` in provision, using the already cached |
| + record bodies and manifests. It returns routing metadata only: primary |
| + host, account, app, pool, placement, HA, incarnation and serving sequence. |
| + Reject retired, invalid, conflicting, sidecar, replica, fleet, import/hold, |
| + platform and unit/non-hibernating records. No disk paths, proxy or spawn |
| + authority is synthesized. A partial snapshot returns an error, not absence. |
| +- Add `Edge.SetHAIngressLookup(func(host string) (registry.Route, bool))`. |
| + Host builds an immutable projection after the existing record-view refresh |
| + and passes it to the same edge/service. Lookup is memory-only. Reuse the |
| + existing change-index refresh/backstop; do not add an independent poll. |
| + If the index is disabled, build from the existing successful instance-pass |
| + record scan, before its pool filter. Do not silently require a new switch. |
| +- Add `func (e *Edge) frontForwardHAIngress(w http.ResponseWriter, |
| + r *http.Request, host string, rt registry.Route) bool`: a terminal |
| + forwarding/refusal path, never a local upstream. Use the existing holder |
| + cache/ForwardTarget and signed transport. Add an explicit local-eligibility |
| + input to `DecidePlacement(..., localEligible bool, ...)`, independent of |
| + `WakeSnapshot.Enabled` and whether the own edges file was found. |
| + |
| +**Steps:** |
| + |
| +- [ ] `TestHAIngressWithoutLocalRow` drives `Edge.ServeHTTP`, a real service, |
| + registry and record-view publication. Own pools exclude `ha`. Test both no |
| + row and a stale row, then remove the stale row between requests. Cover: |
| + |
| + | Evidence | Required result | |
| + |---|---| |
| + | Valid holder B in the host region's existing holder view | Forward directly to B; never wake or acquire locally. Holder lookup is distinct from cold-candidate headroom. | |
| + | Absent/released lease, usable eligible B | Choose eligible clean releaser or roomiest B; forward once; B performs its own acquire. | |
| + | Expired unreleased lease | An eligible selected receiver may attempt recovery; only existing proof + expiry permits its acquire. No ingress takeover. | |
| + | No eligible peer, missing key, unusable view, read error or out-of-view target | 503, Retry-After 10, holder none. No Base-to-local fallthrough. | |
| + | Verified hop arriving at the ineligible ingress | Immediate 503, Retry-After 10, holder none; no onward hop or acquisition. | |
| + | Unknown host absent from records and accepted name evidence | Existing unknown-host behavior; no arbitrary lock GET for attacker-chosen names. | |
| + |
| +- [ ] Insert ingress routing after existing admission/name/region decisions |
| + and before lookup-miss asset/backhaul dispatch. Invoke it for a miss and |
| + for a local hit that fails pool eligibility; use the current projection |
| + to resolve a stale non-HA row for a now-HA record, never that stale stamp |
| + as permission to serve. A local hit with no trustworthy projection refuses. Respect exact/alias/catchall |
| + precedence via the existing name resolver; map a proven alias to its primary |
| + only when account/app/target/lifetime agree. Never infer a route from a |
| + hostname suffix. A foreign-region name stays on existing regional routing; |
| + do not read its lock through this box's local data bucket. A regional name |
| + targeting this region gets the same pool refusal/forwarding boundary. |
| +- [ ] A known host from the last successful projection remains **known but |
| + unavailable** on a failed refresh. Do not keep serving a stale projection |
| + as current evidence. Complete deletion removes it; ambiguous ownership |
| + refuses. Existing held-name/import/retirement gates outrank forwarding. |
| + `TestHAIngressMetadataCannotGrantLocalAuthority` checks these cases, custom |
| + aliases, cross-account conflict, a verified hop, and index-disabled wiring. |
| +- [ ] In `forwardTarget`, bypass acquisition/forwarding only for an eligible |
| + healthy awake/waking entry. Ineligible entries continue to a remote decision |
| + (or refuse); `begin` independently denies before registering inflight or |
| + starting a wake, including existing awake entries. A selected peer falling |
| + out of view must not fall through to local service. Check entry/route |
| + identity again after races; no I/O while holding service locks. |
| +- [ ] In `wakeSnapshot`, pool-check self and every ordinary cold candidate |
| + with `ServedPools.Serves(rt.Pool)`. Preserve sidecar placement checks and |
| + ordinary host/account/app/replica checks. Missing own evidence cannot |
| + overwrite authoritative `localEligible=false`. Keep holder-view parsing |
| + separate: membership does not grant or revoke the lease itself. |
| +- [ ] `TestPoolGateCannotFallBackLocal` covers switch off, nil/malformed/stale |
| + snapshot, no holder reader, failed lock read, memory-only held-stream path, |
| + stale awake/waking entries, lost placement generation, no mesh key and |
| + `ForwardNotInView`. Every denied local branch has zero acquisition/spawn/ |
| + tenant calls. Include low-headroom **eligible** peer: A20 still forwards. |
| +- [ ] `TestWakePlacementFiltersEveryPool` covers ordinary and sidecar peers, |
| + shared versus named pools and malformed/absent evidence. `TestHAIngressNoHopReplay` |
| + asserts one hop, one billing/request-accounting owner and one POST delivery. |
| +- [ ] Run `go test ./internal/provision -run 'TestHAIngress' -count=1` and |
| + `TMPDIR=/tmp/g go test ./internal/edge ./internal/activator ./internal/host -run 'TestHAIngress|TestPoolGate|TestWakePlacementFiltersEveryPool|Test.*Placement|Test.*Forward' -count=1`. |
| + Expect pass. Compile affected packages on all three target platforms. |
| +- [ ] Commit: `ha: forward pooled hosts through ineligible ingress boxes`. |
| + |
| +## Task 3: F-B, retire stale rows only after safe pool withdrawal |
| + |
| +**Correction to findings:** `retirable` is at `reconcile.go:2372–2384` and |
| +still calls the pool-first `inScope:516`. `claimRetire` in |
| +`internal/provision/claimassembly.go:40` directly deletes when claims are off; |
| +it is not a process-stop proof. `finishStop` at `activator.go:5152` can forget |
| +an entry after a failed final checkpoint. Entry absence is not clean release. |
| +The departure scanner (`host/hadepartures_scan.go:77`) requires termination |
| +work; do not pretend a live box leaving one pool is an EC2 departure. |
| + |
| +**Files:** new `internal/provision/poolwithdrawal.go` and tests; |
| +`internal/provision/{reconcile.go,sidecar_reconcile.go}`; new |
| +`internal/activator/poolwithdrawal.go` and tests; new |
| +`internal/host/poolwithdrawal.go`, host wiring; registry exact-delete helper |
| +and tests in new `internal/registry/poolwithdrawal.go` if no existing helper |
| +can compare the full expected row identity. |
| + |
| +**Interfaces:** |
| + |
| +- `ReconcileConfig.WithdrawPool func(context.Context, registry.Route) error`. |
| + Nil means pending/refused, never permission to delete. |
| +- `func (a *Service) PreparePoolWithdrawal(ctx context.Context, |
| + rt registry.Route) error`: closes local admission for this exact row, |
| + initiates/joins its normal clean sleep, proves all processes stopped, and |
| + checks clean release plus duty disposition. It owns no registry deletion. |
| +- `func (r *Registry) DeleteWithdrawnRoute(ctx context.Context, |
| + expected Route) (bool, error)`: transactionally compare host, account/app, |
| + pool, region, kind, incarnation/serving sequence and ownership columns; |
| + delete only the unchanged row and its normal dependent data. A mismatch |
| + retries from observation. This is not a general bypass of claim retirement. |
| + |
| +**Steps:** |
| + |
| +- [ ] Add a separate withdrawal phase. Select only Provisioned rows whose |
| + pool is no longer served, while preserving the **non-pool** region/fleet, |
| + own-kind and authority restrictions. Do not widen `inScope` or make every |
| + out-of-scope row removable. Instance pass excludes sidecars/forward rows; |
| + sidecar pass owns its own kind. Hand-added, platform, canary, demo, |
| + foreign-fleet, replica-assignment, import-journal/hold and claim-owned rows |
| + keep their existing owners; report unsupported withdrawals explicitly. |
| +- [ ] Fence local requests/duties first with T1/T2. Under the service's |
| + existing per-host serialization, re-read the row and current membership; |
| + a concurrent wake must see the fence. For an awake/waking host initiate or |
| + join its real stop, including commands/workers and whole-host cgroup proof. |
| + Reconcile polls completion on later ticks instead of holding its pass or |
| + mutex through S3 work. Repeated calls coalesce, including after restart. |
| +- [ ] For HA require a successful **clean** release for this lifetime and |
| + completed file/wake-state publication, not merely expired lease, `stopped` |
| + channel, or owed unclean marker. If the lock already names a successor, |
| + verify the local completed clean-release evidence and local stop; do not |
| + release that successor's lease. If this agent never held the host, use the |
| + existing startup sweep + per-host emptiness proof, and verify it owes no |
| + release. Never acquire just to clean up an ineligible row. |
| +- [ ] Keep duties safe. Delete when there are no outstanding locally owned |
| + duties, or existing authoritative adoption/import evidence proves that the |
| + same lifetime's wake state is owned elsewhere. A marker naming this live |
| + withdrawn box alone is **not** evidence of transfer. Otherwise retain the |
| + fenced row and log `ha_pool_withdrawal_pending code=duties`. No synthetic |
| + termination, new duty-transfer file or forced timer deletion. This narrow |
| + refusal is deliberate; see controller question Q2 and the follow-up task. |
| +- [ ] For ordinary non-HA managed rows require the normal proven stop; for |
| + static rows prove no process ownership is attached. Unsupported shapes |
| + stay fenced/pending. Never delete local DB/files in this task. |
| +- [ ] With a complete proof, compare-and-delete, then refresh edge and edges |
| + publication. T2 continues ingress without the local row. While pending, |
| + suppress the stale row's home advertisement (including aliases) using the |
| + same pool predicate. Do not claim the box still hosts that pool. |
| +- [ ] `TestPoolWithdrawalRequiresCompleteProof`: awake and asleep success; |
| + populated cgroup, failed sync, unclean/owed marker, failed publication, |
| + pending duty, changed lifetime/pool, in-flight wake, restart, missing hook |
| + and record-read failure all keep the row. Assert stop before marker before |
| + delete, zero writes to the instance record, zero successor lease writes, |
| + and surviving timers when removal is refused. |
| +- [ ] `TestPoolWithdrawalScopeAndIngress`: sibling kind, hand-added, foreign |
| + region/fleet and special ownership rows stay; eligible managed rows stay; |
| + a safe withdrawn ordinary row disappears; subsequent HTTP still forwards. |
| +- [ ] Run `go test ./internal/provision ./internal/registry -run 'TestPoolWithdrawal' -count=1` and |
| + `TMPDIR=/tmp/g go test ./internal/activator ./internal/host -run 'TestPoolWithdrawal|Test.*Stop.*Lease|Test.*Release' -count=1`. |
| + Expect pass. Mutation “delete before proof” must fail the new tests. |
| +- [ ] Commit: `ha: require stop and release proof before pool row removal`. |
| + |
| +## Task 4: F-B, distinguish a live owner from an unreadable proof |
| + |
| +**Correction to findings:** `termfence/termination_proof.go:321` still maps a |
| +successful non-terminated observation to `ErrTerminationProof`; |
| +`activator/hatakeover.go:47–53,105` conflates it with an EC2 read failure. |
| + |
| +**Files:** `internal/termfence/{termination_proof.go,termination_proof_test.go}`; |
| +`internal/activator/{hatakeover.go,hatakeover_test.go}`; |
| +`internal/lease/termination_proof_test.go`. |
| + |
| +**Interfaces / steps:** |
| + |
| +- [ ] Add `ErrOwnerNotTerminated = errors.New("ha_owner_not_terminated")` and |
| + a typed error carrying IID and the successfully observed EC2 state. Emit it |
| + only for a valid same-account/region matching instance observation that is |
| + not terminated. Keep absent, mismatched and malformed identity/proof errors |
| + distinct. Never call `shutting-down`, `stopped`, or an unknown result dead. |
| +- [ ] Preserve the code through `errors.Join` and proof-cache negative TTLs. |
| + If the legacy bool callback says false without state, use a neutral “not |
| + terminated” diagnostic, not a fabricated running state. |
| +- [ ] Log `ha_owner_not_terminated`; for a known running state the text is |
| + `EC2 says <iid> is still running`. API failures retain their actual error. |
| + Do not return these low-level errors as new HTTP copy. |
| +- [ ] `TestTerminationProofDistinguishesLiveOwner` checks running/stopped/ |
| + shutting-down, mismatch, missing instance, API error and terminated. All |
| + refusals write zero proofs/leases. `TestTakeoverLiveOwnerDiagnostic` checks |
| + the distinct log and existing throttle, plus cache re-observation. |
| +- [ ] Run `go test ./internal/termfence ./internal/lease -run 'TestTerminationProof|Test.*Termination.*Binding' -count=1` and |
| + `TMPDIR=/tmp/g go test ./internal/activator -run 'TestTakeoverLiveOwnerDiagnostic|TestTakeoverDescribeFailureKeepsHostDown' -count=1`. |
| +- [ ] Commit: `ha: report when EC2 confirms an owner is still running`. |
| + |
| +## Task 5: F-A, immediate refusal through loss, stop and re-wake |
| + |
| +**Correction to findings:** `actAwake` at `activator.go:1843` still continues |
| +into stopping after `servingError`; `actStopping:1884` waits. `finishStop:5233` |
| +can remove the entry despite a failed release. A fix confined to the stopping |
| +switch would therefore miss the later re-wake hang. The local refusal must |
| +also precede `forwardTarget`'s healthy-entry shortcut. |
| + |
| +**Files:** `internal/activator/{activator.go,haforward.go,harelease.go, |
| +haleaseloss.go,haleaseloss_test.go}` and service/backend wiring as needed. |
| + |
| +**Interfaces:** add `ErrHALeaseUnavailable`; a private per-host/lifetime |
| +loss record on Service; `func (a *Service) haLeaseRefusalLocked(rt |
| +registry.Route) error`; `func (a *Service) retryHALostHost(rt registry.Route)`; |
| +one response helper `answerHALeaseUnavailable(w, r)`. |
| + |
| +**Steps:** |
| + |
| +- [ ] `TestHALostLeaseAnswersImmediately` holds the real stop-completion |
| + seam open, with both awake-detected loss and already stopping entries. |
| + Ordinary and verified-hop requests answer within **1 second**, status 503, |
| + `Retry-After: 10`, `X-Carlos-Holder: none`, body C1. No re-wake, proxy or |
| + request-accounting entry. Pure unit timing can use channels/fake clocks; |
| + T11 measures the production wall time. |
| +- [ ] Latch loss before beginning stop whenever HA serving health is lost, |
| + including locally relinquished/spent handles. The fast answer performs no |
| + I/O and waits for no stop or S3 work. Stop work continues under its existing |
| + safety rules. Normal idle/version-change stops keep their current behavior. |
| +- [ ] `TestHALostLatchSurvivesEntryRemoval`: remove the stopped entry while an |
| + owed marker is still blocked; subsequent requests still refuse promptly. |
| + Key the latch by host and lifetime/generation so old stop callbacks cannot |
| + poison a successor. Retain pending latches until resolved; never evict an |
| + unresolved latch to permit a wake. Bound recovery workers, not safety state. |
| +- [ ] Recovery is detached from the request: one retry worker per host at |
| + most once per **10 seconds**, using the service lifetime and a **2-second |
| + attempt context** for ownership discovery/acquire. Do not enter it until |
| + all prior local work is proven stopped and ordinary release obligations |
| + permit acquisition. It uses the normal gated acquire path with T1; no |
| + direct lock write, no reuse of a lost Held. Keep the latch until a fresh |
| + healthy acquisition succeeds; wake waiters continue to get 503 meanwhile. |
| + If another holder is observed, allow future forwarding while local hosting |
| + remains denied. Shutdown joins these workers. No abandoned sync goroutine. |
| +- [ ] `TestHALostLeaseRecoversOnlyAfterFreshAcquire` unblocks cleanup/S3, |
| + produces a legitimate marker/conditional acquisition and proves a new |
| + healthy handle serves. Late renewal success, old stop completion, unchanged |
| + foreign expired lease, and pool withdrawal never clear the gate. Include |
| + temporary S3 failure, new record lifetime and agent restart with owed state. |
| +- [ ] Add the refusal at both Service HTTP error mapping and ForwardTarget |
| + (including memory-only). Direct local and forwarded paths get the same |
| + headers; preserve `Retry-After: 1` for an ordinary live-holder redirect. |
| +- [ ] Run `TMPDIR=/tmp/g go test ./internal/activator -run 'TestHALost|Test.*LeaseLoss|TestSuspectClearedByTakingTheLease' -count=1`. |
| + Expect pass; restoring the old stopping wait must fail the latency witness. |
| +- [ ] Commit: `ha: refuse promptly while lost lease cleanup is pending`. |
| + |
| +## Task 6: F-A, bound each renewal without undoing pause protection |
| + |
| +**Correction to findings:** main includes `855651cf`. Renewal now calls the |
| +local `renewLease` at `internal/lease/health.go:231`, anchored at `rn.seen`, |
| +with a 30-second pause detector and a SafeUntil watcher. Do not revert to |
| +`leaser.RenewLease`, change its expiry anchor, or remove pause checks. |
| + |
| +**Files:** `internal/lease/{health.go,renew_attempt_test.go}`; existing pause |
| +and health tests updated only where their expectations need the new deadline. |
| + |
| +**Interfaces / steps:** |
| + |
| +- [ ] Add `func renewAttemptDeadline(started, safeUntil time.Time, |
| + ttl time.Duration) time.Time`. Deadline is |
| + `min(started + min(30*time.Second, ttl/3), safeUntil)`; floor a nonpositive |
| + tiny test budget at one nanosecond, and refuse if already spent. |
| + Production TTL is 15 minutes: attempt cap 30 seconds, cadence 5 minutes, |
| + safety margin unchanged at 5 seconds. This caps SDK retry time far below |
| + the drill's inferred 93 seconds, without allowing a write past SafeUntil. |
| +- [ ] Capture `until` and `started` under the renewer mutex after the health |
| + check. Construct the child deadline before the pre-write test seam; recheck |
| + cancellation/health immediately before the write. Pass the child context |
| + through `renewLease` and cancel it promptly. Keep the post-write check and |
| + late-success ETag retention solely for conditional cleanup. |
| +- [ ] `TestRenewAttemptDeadline` checks 15m TTL => 30s, short TTL => TTL/3, |
| + smaller SafeUntil, exact boundary and spent deadline. `TestRenewAttemptStall` |
| + holds the S3 request until context cancellation and proves loss is latched, |
| + Lost closes once and no next renewal is sent. `TestRenewAttemptLateSuccessCannotRestoreHealth` |
| + proves the ETag updates but SafeUntil/health never recover. |
| +- [ ] Run `go test ./internal/lease -run 'TestRenewAttempt|TestPausedHolderDoesNotRenewOnResume|Test.*Pause|Test.*SafeUntil' -count=1`. |
| + Preserve the real SIGSTOP/SIGCONT test's existing platform/build conditions. |
| +- [ ] Commit: `lease: bound renewal attempts by budget and safe deadline`. |
| + |
| +## Task 7: F-A, canceled and silent forwards cannot confirm a holder |
| + |
| +**Correction to findings:** `forwardha.go:272` starts with ForwardDone and |
| +only changes cancellation to ForwardCanceled for non-Holder kinds. However, |
| +`hacache.go:436–468` does **not** refresh a positive entry on Status 0; it |
| +leaves it untouched. Fix the outcome and lack of invalidation, rather than |
| +claiming each cancellation currently extends the hour. A 503/holder-none |
| +already drops the cache; retain that behavior and prove the real wiring. |
| + |
| +**Files:** `internal/edge/{forwardha.go,forwardha_test.go}`; |
| +`internal/activator/{hacache.go,haforward.go,hasuspect_test.go}`. |
| + |
| +**Interfaces / steps:** |
| + |
| +- [ ] Apply `ForwardCanceled` to **every** kind when the client cancels or |
| + the request never reaches the target because it waits out a dial queue. |
| + Neither confirms a holder nor changes an unrelated/newer cache generation. |
| + After-header disconnects retain the separately observed valid response; |
| + do not manufacture Status 0 success from an error callback. |
| +- [ ] Add `ForwardSilent` and `const holderHeaderSuspectAfter = 3*time.Second`. |
| + Start a nonblocking observation timer for a Holder attempt at dispatch; |
| + three seconds without **final** response headers reports suspicion once |
| + with host/ref/cache generation. 100/103 are not final headers. A request |
| + canceled before the threshold gives no reachability evidence. Cancel and |
| + join the timer callback at headers/completion; no callback races after |
| + the request's observations are disposed. |
| +- [ ] Three seconds fits inside drill 4's five-second client timeout. It is |
| + **not an app timeout**: do not cancel the transport, close an upgrade, |
| + interrupt an upload/stream, or replay anything. A slow app can still return |
| + its original result at 20 seconds. Suspicion only makes subsequent |
| + requests share the existing N-HA15 re-read: one bounded 2-second lock read |
| + per 10-second suspect window; still-held/error answers refuse during that |
| + window. Legitimate final headers from the same holder can clear its |
| + suspicion under the existing generation rules; newer ownership wins. |
| +- [ ] Map ForwardSilent to holder suspicion and the placement-peer exclusion |
| + used for unreachable holders, but **not** to confirmed departure or EC2 |
| + termination. Keep cache bounds (50,000), dial gate and epochs. Holder-none |
| + or headerless 503 drops the entry. No response status may grant a lease. |
| +- [ ] `TestCanceledHolderDoesNotConfirm` covers cancellation before dial, |
| + during queue and after connect, with an existing suspect entry. Verify no |
| + positive cache resurrection and no synthetic target-failure evidence. |
| +- [ ] `TestSilentHolderRevalidatesOnce` holds a connected server's headers, |
| + waits for the timer, then sends 50 concurrent arrivals: one bounded lock |
| + read, no local acquisition from silence, no replay of the original POST. |
| + Absent/released lock permits a **later** request's eligible placement; |
| + foreign expired lock still requires proof. |
| +- [ ] `TestSlowHolderResponseIsNotAborted` returns final headers after the |
| + threshold and a streaming body later, delivers exactly one write, and |
| + clears only the same-holder suspicion. Add 103 then stall, client cancel |
| + near the threshold, newer holder/acquire during timer firing, and 503 with |
| + `X-Carlos-Holder: none` through the actual edge-to-service callback. |
| +- [ ] Run `TMPDIR=/tmp/g go test ./internal/edge ./internal/activator -run 'TestCanceledHolder|TestSilentHolder|TestSlowHolder|TestDeadHolderCostsOneReadAndDialPerWindow|TestSuspect|TestStaleUnreachable' -count=1`. |
| +- [ ] Commit: `ha: revalidate silent holders without replaying requests`. |
| + |
| +## Task 8: F-D, date suspicion from the observed lease and log page failures |
| + |
| +**Correction to findings:** `hatakeover.go:53` and `hasamebox.go:71` call |
| +`note` with the current time, not the observed view. The termination-proof |
| +adapter's Observe callback (`lease/termination_proof.go:39`) has no expiry. |
| +Adding an expiry argument at the log call alone would invent unavailable |
| +information. `hadepartures.go:452,468,530` still discard page errors. |
| + |
| +**Files:** `internal/hafresh/acquire.go`, `internal/lease/ha.go`; |
| +`internal/activator/{hawake.go,haadopt.go,hatakeover.go,hasamebox.go, |
| +hasuspectholder.go,hasuspectholder_test.go}`; |
| +`internal/host/{hadepartures.go,hadepartures_page_followups_test.go}`. |
| + |
| +**Interfaces / steps:** |
| + |
| +- [ ] Add `Proofs.ObserveRefusal func(View, Decision)`, called after the real |
| + acquire classification for each refused round, with that round's immutable |
| + view. Visitor wiring calls `note(host, ownerIID string, sameBox bool, |
| + expiresAt time.Time, generation int64, now time.Time)`. Adoption finalizers |
| + keep their existing immediate paging and do not enter this visitor tracker. |
| + Remove the old duplicate note calls; logging and the proof observer remain. |
| +- [ ] Track the observed owner **and generation/expiry**, not IID alone. |
| + Valid past ExpiresAt starts the clock. Later evidence of renewal/new |
| + generation resets to that lease's expiry; do not preserve an earlier, |
| + shorter deadline for the same IID. Missing/zero/future expiry never creates |
| + an already-overdue page. Only refused expired HA-owner classifications that |
| + reached a real termination/same-box proof participate; no pool-refusal, |
| + malformed marker, old owner or capacity refusal page. |
| +- [ ] Keep ten-minute threshold, five-minute freshness, thirty-minute idle |
| + eviction, hourly per-IID page throttle, sorted ten-host body limit, successful |
| + acquire/confirmed-termination clearing and the fresh five-second page |
| + context. No additional lock/EC2 reads. If first refusal is at L+14, page |
| + immediately then; this cannot backdate a page to L+10 without observations. |
| + Card targets are L+10 log/page under continuous probes, L+12 alarm target. |
| +- [ ] `TestSuspectHolderUsesObservedExpiry`: first refusal L+4m13s, no page |
| + at L+9m59s, page/count at L+10m; first observation at L+14m pages then; |
| + owner/generation change, renewal by same IID, absent expiry, same-box proof, |
| + finalizer exclusion and successful reacquire all behave as above. |
| +- [ ] At all three departure page failures log |
| + `ha_departure_page code=failed ... error=%v`, adding the known IID/departure |
| + ID and actual error. `TestDeparturePageFailureIncludesCause` injects an SNS |
| + AuthorizationError at each site and checks the cause and identity survive. |
| + No change to retry/page cadence or termination authority. |
| +- [ ] Update page body C2 to avoid claiming ten minutes of observed downtime |
| + when the first request arrived late. Existing log text can be corrected |
| + separately; log codes remain stable. |
| +- [ ] Run `go test ./internal/lease ./internal/hafresh -run 'Test.*ObserveRefusal|TestAcquireHAPoolEligibility' -count=1` and |
| + `TMPDIR=/tmp/g go test ./internal/activator ./internal/host -run 'TestSuspectHolder|TestDeparturePageFailureIncludesCause' -count=1`. |
| +- [ ] Commit: `ha: measure suspect owners from lease expiry and expose page errors`. |
| + |
| +## Task 9: F-D, scoped SNS policy code and separate infrastructure proposal |
| + |
| +**Correction to findings:** the common role is |
| +`infra/modules/region-host/main.tf:141`, shared by fixed and group modes. |
| +The topic is `main.tf:639`, conditional on `alerts_email`; the topic policy is |
| +`group_alarms.tf:159–202`. Its SourceOwner statement is not the role grant |
| +seen missing in G2. Do not remove its condition or widen its Principal. |
| +The requested pinfra checkout is on `dev-store-backend`; current group code |
| +was located read-only in its **local `origin/main` at `9558adea`**, not in the |
| +checked-out files. No fetch or cloud read is needed to establish that fact. |
| + |
| +**Files, platform:** new `infra/modules/region-host/alert_publish.tf`; |
| +`variables.tf` and `outputs.tf` for topic input/output; new |
| +`infra/modules/region-host/tests/alert_publish.tftest.hcl`; update |
| +`tests/group_iam.tftest.hcl`, `scripts/region_group_contract_test.py`, |
| +`scripts/check-region-group-plan.py` and |
| +`scripts/check_region_group_plan_test.py` for exact policy inventories. |
| + |
| +**Interfaces / steps:** |
| + |
| +- [ ] Add optional `alert_publish_topic_arns` (`set(string)`, default empty). |
| + Define `aws_iam_role_policy.alert_publish` on `aws_iam_role.host.id`, one |
| + Allow statement, `Action = ["sns:Publish"]`, resources the distinct union |
| + of the module's own alerts topic when enabled and explicitly supplied |
| + topic ARNs. No `*`, subscription, topic-management or KMS grant. Validate |
| + supplied ARNs as concrete SNS topics. Expose `alerts_topic_arn`, null when |
| + absent. Policy count is zero when neither source supplies a topic. |
| +- [ ] This gives group members their own topic permission and lets a fixed |
| + HA module explicitly name the group topic. Do not change the topic policy, |
| + trust policy, queue permissions, ASG, listener or launch template. A policy |
| + grant does not configure `CARLOS_ALERT_SNS_TOPIC_ARN`; check sink and grant |
| + together in each root proposal. |
| +- [ ] `TestHAAlertPublishScope` (mock-provider run |
| + `ha_alert_publish_scope` in `tests/alert_publish.tftest.hcl`) checks group own-topic, fixed |
| + explicit-group-topic, both, none and invalid/wildcard ARN. Assert exact |
| + role/action/resource sets and no effect on nonconfigured module consumers. |
| +- [ ] Add the new module policy address to `GROUP_DISPOSABLE` in |
| + `scripts/check-region-group-plan.py:47–69`; test its create/destroy |
| + classification only inside the reviewed group module. Extend the exact |
| + role-policy-name/action/resource inventories in |
| + `scripts/region_group_contract_test.py:71` and |
| + `tests/group_iam.tftest.hcl:109`. Keep the three existing topic-policy |
| + statements pinned by `tests/group_alarms.tftest.hcl:250`. Existing fixed |
| + fixtures with no configured topic stay byte-identical; a fixed fixture |
| + with an explicitly configured topic gains only this reviewed policy. |
| + Fixed-role policies |
| + outside the group remain refused without exact reviewed card allowances; |
| + never broaden IAM-resource allowlists. This is a gate-code change, not an |
| + approved apply. |
| +- [ ] Run `tofu fmt -check infra/modules/region-host` and offline module tests |
| + with an already available provider, backend disabled; no init that reaches |
| + an account. Run `tofu -chdir=infra/modules/region-host test -filter=tests/alert_publish.tftest.hcl` |
| + and the existing group IAM/alarm mock tests. Add gate tests |
| + `GateTests.test_alert_publish_disposable` and |
| + `GateTests.test_alert_publish_cannot_modify_fixed_role`; run |
| + `python3 -m unittest scripts.check_region_group_plan_test.GateTests.test_alert_publish_disposable scripts.check_region_group_plan_test.GateTests.test_alert_publish_cannot_modify_fixed_role`. |
| + Feed captured `tofu test -json -verbose` mock events to |
| + `python3 scripts/region_group_contract_test.py <event-file>` as its |
| + existing harness requires. Expected: exact scope passes, wildcard or |
| + unrelated-role mutations fail. Record unavailable local tooling; amadan's |
| + relevant checks must still run before landing. |
| +- [ ] Commit platform code: `infra: scope HA alert publishing to configured topics`. |
| + |
| +**Separate pinfra branch + PR task (controller-owned; do not merge/apply):** |
| + |
| +1. In `/home/paulca/amadan.net/carlos/platform-infrastructure`, branch from |
| + its actual main after reading that repo's rules. Add |
| + `dev/region-ha-alert-publish.tf`: inline policy on |
| + `module.host_ie_group.role_name`, action `sns:Publish`, only |
| + `arn:aws:sns:eu-west-1:640012953448:carlos-dev-ie-group-alerts`. |
| + `origin/main:dev/region-ha-group.tf:13,19,27` names the module/role/topic |
| + inputs. A standalone attachment avoids repinning the running module and |
| + accidentally changing its launch template. Name the attachment as |
| + temporary duplication to retire when the root adopts the module fix. |
| +2. In the same new file, add two equally narrow policies for |
| + `module.host_ie.role_name` (`carlos-dev-host`, sophie-knitting; |
| + `origin/main:dev/region-ie.tf:5,9`) and |
| + `module.host_ie_b.role_name` (`carlos-dev-host-b`, leo-climbing; |
| + `origin/main:dev/region-ie-b.tf:9,13`). All three proposed roles receive |
| + only `sns:Publish` on that exact IE group topic. The module/name mapping |
| + is explicit in `dev/region-ha-ingress.tf:3`. Neither fixed module sets |
| + `alerts_email`, and no tracked dev root config establishes their current |
| + `CARLOS_ALERT_SNS_TOPIC_ARN`. Therefore include an unapplied deployment |
| + instruction/readback requirement to configure both fixed sinks to the |
| + group ARN; do not claim that they already use it. No blanket account grant, |
| + host.env edit, source repin or restart is performed by this task. |
| +3. G3 is a different root/account. The US draft is |
| + `~/.cache/region-ha-next/g3-drafts/region-ha-us-group-draft.tf`, not merged |
| + design authority. It names `module.host_us_group`, role |
| + `carlos-flagship-us-ha`, provider `aws.us`, account `271376211898`, |
| + `us-east-1`. The fixed role is `module.host_us.role_name`, |
| + `carlos-flagship-host-us`, in the flagship root |
| + `/home/paulca/github.com/carlosframework/carloku-infrastructure/region-us.tf:47–83`. |
| + Prepare a separate **unmerged/unapplied** proposal in that owning repo |
| + when the controller owns its G3 slice; do not write flagship changes into |
| + pinfra or depend on an unmerged US module interface. |
| +4. Exact G3-card item text to carry forward: “Before G3, grant |
| + `sns:Publish` on the US group alerts topic |
| + `arn:aws:sns:us-east-1:271376211898:carlos-flagship-us-ha-alerts` to the US |
| + group role `carlos-flagship-us-ha` and adi-knitting's fixed role |
| + `carlos-flagship-host-us`. Configure and verify both page sinks against |
| + that same topic. Record the two identity-policy grants, preserve the |
| + CloudWatch/EventBridge topic statements, and verify page delivery under |
| + the separately approved G3 scope. Target the suspect log/page at L+10 |
| + under continuous probes and the alarm at L+12. Do not add `ha` to adi's |
| + CARLOS_POOLS.” Adi's existing fixed-topic ARN is different; leaving its |
| + sink pointed there does not satisfy the group-topic item. |
| +5. No live plan/apply/page test in this task. The PR records code validation, |
| + exact accounts/regions/roles/topics, no traffic changes, and the later |
| + approval/verification needed. Module infra is root-census-pinned (T13); |
| + pinfra policies also need their repo's plan-gate/card treatment. |
| + |
| +## Task 10: F-B production-wired witness on a throwaway root runner |
| + |
| +**Files:** `scripts/region-ha-g2-pool-witness.py` (controller driver); |
| +`internal/host/region_ha_g2_pool_root_linux_test.go` with |
| +`//go:build linux && rootrunner`; reuse a small shared root fixture in |
| +`internal/host/region_ha_g2_root_fixture_test.go` (same build tag) for T11. |
| + |
| +**Interface:** driver flags `--worktree`, `--evidence-dir`, `--runner-id`, |
| +`--peer-id`, `--expected-tip`, `--cleanup`; exact test `TestRootG2PoolIngress`. |
| +Both instance IDs are mandatory and must match the controller's ownership |
| +manifest. The driver |
| +never chooses a dev box. Build branch binaries and record SHA-256 before |
| +upload; run the real `carlos agent`, edge, activator and root instance-control |
| +service, not a fake Backend or in-process imitation of their constructor. |
| + |
| +**Steps / acceptance:** |
| + |
| +- [ ] Reuse the runner contract and lifecycle at |
| + `/home/paulca/.cache/tmp/claude-1001/own/after236/root-runner.py` (and its |
| + contract): profile `kass`, dev account `640012953448`, `eu-west-1`, existing |
| + `carlos-root-runner` profile, two `t4g.small` instances (root runner A and |
| + peer B), each with a 30-GiB delete-on-termination disk and no public ingress. B is test apparatus, not |
| + a dev box. Both identities must be real and distinct. Controller confirms |
| + current image/subnet/SG/profile IDs and the expanded two-instance scope |
| + before launch; historical single-runner approval alone is insufficient. |
| + The historical script terminates in `finally` but does not verify terminal |
| + EC2 state; the new driver/controller must wait and read back `terminated`. |
| +- [ ] A and B run the real branch agent/edge/root-control binaries with |
| + separate real registries, actual IMDS instance identities and nested |
| + tenant cgroups. `otherHolder` compares IID as well as reference, so two |
| + processes on one EC2 instance are **not** a valid two-box witness. Bind |
| + local fixture services to loopback; cross-runner listeners use only |
| + controller-approved Tailscale addresses, never all interfaces. Include |
| + the temporary tailnet enrollment and removal in the controller scope. |
| + Run a real MinIO-compatible server on the runner for isolated deployment |
| + and data buckets, conditional operations and fault injection; wire it with |
| + the existing `CARLOS_S3_ENDPOINT` configuration (`lease/endpoint.go`). |
| + Use only fixture keys/records and no production bucket prefixes. Real |
| + self/configuration must flow through startup; do not override `lease.SetSelf` |
| + or use a fake Backend. No EC2 termination-proof claim is made by MinIO. |
| +- [ ] Run A as the only ingress with `CARLOS_POOLS=other`, B eligible for |
| + `ha`. Seed the same current records a real reconciler reads; A starts with |
| + an old Provisioned row. Through HTTP to A, prove held B is reached, clean |
| + and unclean release markers wake only B, absent lock wakes only B, |
| + and the no-eligible-peer case produces 503/Retry-After 10/holder none. Hash each binary and |
| + record actual PIDs, cgroups, lock owner/generation and registry rows. |
| +- [ ] Seed a previously awake local host using an initial eligible config, |
| + then withdraw the pool via the supported startup/config path. Prove A |
| + never serves again after the new membership is effective, sleeps cleanly, |
| + proves stop and releases before row removal. Repeat with blocked stop and |
| + pending duties: row remains fenced, zero acquire. Remove A's row entirely; |
| + the same ingress HTTP cases still work through T2's production projection. |
| +- [ ] Send a valid signed hop to ineligible A: immediate refusal, zero onward |
| + hop. Send concurrent POSTs with unique IDs: no duplicate delivery, no local |
| + PID/lease on A, one writer on an eligible box. Test low-headroom eligible B |
| + and a peer advertising the host but not the pool. Include alias and current |
| + region ingress cases from T2. No fixture-only override of pool membership. |
| +- [ ] Pass only with all assertions, no skips, captured headers/latencies, |
| + S3 request counts and unit journals. Temporarily remove the acquire/local |
| + guard in a separate build on this runner: the witness must fail. Restore |
| + the exact branch build and pass; mutation build is never committed. |
| +- [ ] Offline check: `python3 -m py_compile scripts/region-ha-g2-pool-witness.py` |
| + with `PYTHONPYCACHEPREFIX` under `$TMPDIR`; compile tagged host test binary |
| + with `CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go test -c -tags rootrunner -o "$TMPDIR/g2-pool-root.test" ./internal/host`. |
| + Controller command after approved launch: |
| + `python3 scripts/region-ha-g2-pool-witness.py --worktree "$PWD" --expected-tip <full-sha> --runner-id <owned-A> --peer-id <owned-B> --evidence-dir <owned-evidence-dir> --cleanup`. |
| + Expected final evidence `PASS TestRootG2PoolIngress`, plus verified cleanup. |
| +- [ ] Stop every test unit/server; delete only created objects/artifacts; |
| + controller terminates both instances and verifies them terminated, owned |
| + disks gone and temporary tailnet enrollments removed. |
| + Retain evidence/checksums, remove uploaded executable and local scratch. |
| + This approval scope permits runner infrastructure and local test networking, |
| + not deployments, live tenant traffic or changes to dev boxes. Cost is two |
| + small instances plus two 30-GiB disks for at most **90 minutes**, with an expiry |
| + watchdog; controller records the estimate before approval/launch. |
| +- [ ] Commit witness: `test: witness pool isolation through the real HA ingress`. |
| + Then perform the grouped F-B Opus review, including T1–4 authority changes, |
| + census proposal to date and the witness report. No review is claimed here. |
| + |
| +## Task 11: F-A production-wired loss and forward witness |
| + |
| +**Files:** `scripts/region-ha-g2-loss-witness.py`; |
| +`internal/host/region_ha_g2_loss_root_linux_test.go`; shared fixture from T10. |
| +**Interface:** same driver flags/ownership rules, including both owned instance IDs; exact test |
| +`TestRootG2LostLeaseResponses`. Controller launches a fresh root-runner/peer pair |
| +under T10's scoped process; terminate both and verify gone afterward. |
| + |
| +- [ ] Use real binaries, registry, lease renewal and object server. Block |
| + only the holder's S3 path through a runner-local proxy/network rule while |
| + retaining its inbound HTTP and peer connectivity. Keep the actual |
| + 15-minute lease TTL/5-minute renewal cadence; budget the witness at |
| + **45 minutes** within the runner's 90-minute expiry. Do not inject ErrLost |
| + or substitute a fake renewer. Record renewal-start and cancellation times. |
| +- [ ] After the first failed/budget-expired renewal latches loss, direct and |
| + forwarded requests must each return 503 within **1 second**, Retry-After |
| + 10, holder none. Confirm the renew attempt used at most 30 seconds and |
| + did not exceed SafeUntil. LB health remains 200. Prove refusal while stop |
| + is still pending, not only after cleanup eventually completes. |
| +- [ ] Keep the old entry stopping/cleanup blocked, then let entry removal |
| + occur with outstanding release work if that real path permits it. All |
| + re-wake requests still refuse; zero second writer. After restoring S3, |
| + observe real stop completion/marker, a legitimate new conditional acquire |
| + and successful HTTP recovery. If the existing out-of-scope sync defect |
| + prevents cleanup, report that boundary as blocked; do not claim recovery |
| + from a fixture bypass or quietly add the G5 fix. The targeted T5 test must |
| + still prove recovery when cleanup is legitimately complete. |
| +- [ ] With an independent slow fixture app, delay response headers 20 seconds |
| + and record one POST commit. At 3 seconds the peer marks suspicion; later |
| + callers cause one N-HA15 lock reread per window, never replay the POST. |
| + The original request completes once at 20 seconds. Cancel another client |
| + at 1 second: it cannot confirm/reset a suspect holder. Capture a real |
| + holder-none refusal and cache-drop/discovery sequence. |
| +- [ ] Capture journals off the runner before cleanup, headers, timings, |
| + process/cgroup state, lock versions and callback/cache counters. The witness |
| + is not a production S3-fault drill and makes no data-loss-window claim. |
| +- [ ] Offline compile driver and tagged test binary as T10. Controller command: |
| + `python3 scripts/region-ha-g2-loss-witness.py --worktree "$PWD" --expected-tip <full-sha> --runner-id <owned-A> --peer-id <owned-B> --evidence-dir <owned-evidence-dir> --cleanup`. |
| + The run must report `PASS TestRootG2LostLeaseResponses`, no skips and cleanup |
| + readback. Mutation builds restoring the old stopping wait or cancellation |
| + classification must fail the corresponding cases, then restore/pass tip. |
| +- [ ] Commit: `test: witness prompt HA refusals and bounded holder revalidation`. |
| + Then the grouped F-A Opus review covers T5–7, current census and witness. |
| + |
| +## Task 12: copy pass and one follow-up note |
| + |
| +**Files:** `docs/superpowers/notes/2026-11-06-region-ha-g2-follow-ups.md`; |
| +implementation copy constants in T2/T5/T8; controller ledger for the Luna |
| +verdict. **Interfaces:** C1–C3 response/page constants and the four-entry |
| +follow-up note; no new API. No CLI command is added. If a command becomes necessary, stop scope |
| +expansion and name its CLI-doc requirement before implementation. |
| + |
| +**Draft copy table (HTTP bodies include http.Error's trailing newline):** |
| + |
| +| ID | Use | Text | |
| +|---|---|---| |
| +| C1 | Lost/relinquished local HA lease, pool refusal, known ingress with no eligible target; 503/Retry-After 10/holder none | `This instance cannot wake right now. Please try again shortly.` | |
| +| C2 | Suspect-holder page body, replacing inaccurate downtime claim | `Instance %s has an expired lease and is not confirmed terminated. These hosts have leases that expired at least 10 minutes ago: %s. If the instance is in an Auto Scaling group, terminate it in its group. If it is a fixed box, check its storage access and agent first. This page repeats every hour while the hosts remain refused. (ha_suspect_holder)` | |
| +| C3 | Same-box page body after expiry-based tracking | `This box could not prove that its earlier processes for these hosts have stopped: %s. Their leases expired at least 10 minutes ago. No other box may take them without proof. If this box is in an Auto Scaling group, terminate it in its group. If it is a fixed box, check the agent's startup sweep and cgroup delegation. This page repeats every hour while recovery remains refused. (ha_suspect_holder_same_box)` | |
| + |
| +C1 reuses an existing sentence from `edge/forwardha.go`; existing |
| +“instance is waking elsewhere; retry shortly” and live-holder Retry-After 1 |
| +remain unchanged. Page subjects remain unchanged. New logs/error codes, |
| +including `ha_owner_not_terminated`, are excluded from this copy deck. Extract |
| +any additional visible sentence introduced during implementation into this |
| +same pass; do not leak raw SNS/S3/EC2 errors into HTTP. Region-dependent |
| +sentences use existing label helpers, never bare region codes. |
| + |
| +- [ ] One controller-dispatched **Luna** pass over the complete copy table; |
| + apply its accepted wording verbatim and update exact-body tests. This is |
| + the brief's delegated copy workflow, not a second browser-approval gate. |
| +- [ ] Write one follow-up note with four entries, each with owner, trigger, |
| + evidence pointer and finish condition: F-A cancel-and-join S3 work on stop |
| + (G5 gate; `lease/release.go` SyncAndWait, Litestream `syncMu`, `hafiles.go` |
| + stopFiles; never abandon publishers); F-E restart amazon-ssm-agent at |
| + harness expiry and ship carlos-edge journals off-box; F-B unsupported |
| + withdrawal shapes/duty-transfer blockers deliberately retained by T3; |
| + T1 instrumented terminate pointer, requiring retained journals before |
| + changing stop order/timeout. No F-E/T1 code or live drill here. |
| +- [ ] Record explicitly that F-C remains outside this branch, with its |
| + existing findings pointer, not a new write-fence design. Do not rewrite |
| + the 300-second durability promise in passing. |
| +- [ ] Seeded escalation locations: extend |
| + `internal/sim/regionha/invariants_test.go` and `actions_test.go` for the |
| + pool/wake/withdrawal family, calling the real predicate/acquire/placement |
| + decisions; `internal/activator/hasuspect_test.go` for cache epoch sequences; |
| + new `internal/lease/renew_attempt_test.go` for renew/pause/late-ack order; |
| + `hasuspectholder_test.go` for expiry/owner/generation sequences. Fixed seeds |
| + and a failing mutation are required if stopping rule 2 selects simulation. |
| + Do not use a new simulation as an excuse for another closed review round. |
| +- [ ] Check copy IDs against new response sites, links and all four follow-up |
| + entries; run only the exact response/page tests changed by accepted words. |
| +- [ ] Commit: `docs: record G2 follow-ups and reviewed refusal copy`. |
| + |
| +## Task 13: census, integration and the one whole-branch review |
| + |
| +**Files:** generated overlay/card/chain in the locations printed by the |
| +census tools; affected `*_census_test.go` record-write inventories; controller |
| +review ledger and branch description. **Interfaces:** CLAIMS TSV, generated |
| +census overlay/card, per-unit reviewer verdict and exact-tip CI status. |
| +No archive edits. |
| + |
| +- [ ] Run `make census-card`. Write claims under `$TMPDIR` as |
| + `<file>:<unit><TAB><what changed; new read or no new read>`. Run |
| + `make census-propose NAME=region-ha-g2-fixes CLAIMS="$TMPDIR/g2-claims.tsv"`. |
| + Run it again under the same name after any further changes, not a new |
| + overlay per review round. Include all root-source envelopes, new imports, |
| + embedded files and **every changed infra file**, not only new read sites. |
| +- [ ] Existing infra pins include `internal/provision/testdata/plan14-root-reads-region-ha-p3b.tsv` |
| + for `main.tf`/`group_iam.tf`, and `plan14-root-reads-region-ha-g2-t3.tsv` |
| + for `group_alarms.tf`. New `alert_publish.tf` also enters the infra envelope. |
| + Do not overwrite old freezes or blindly replace hashes. Inspect record- |
| + writer/key-site inventories for Reconcile, registry deletion/import and |
| + new source units; give new writes their actual disposition. |
| +- [ ] Run `go test ./internal/provision -run 'TestPlan14RootReadCensus|TestCensusScopeIsTheRootBinary|TestCensusRebaseCarriesDispositions|TestPlan14RootInputInventoryCoverage|Test.*Census' -count=1`. |
| + Expect clean scope, proposals and record-write inventories. Remove own |
| + claims scratch after the proposal is recorded. |
| +- [ ] Independent **Opus/Fable**, other family than the Codex implementer, |
| + reviews each changed unit and envelope against amadan main, with cited |
| + lines and a verdict. Record reviewer, exact tip and per-card verdict on |
| + #280 through the authorized controller. No census decision escalates to |
| + Paul. Newly changed root/termination/storage/security behavior from P2 |
| + fixes still receives this check within the current budget. |
| +- [ ] Run targeted package tests listed by their owning tasks once after |
| + integration, plus the cross-compiles. Do not run local full suites. Obtain |
| + F-B/F-A witness artifacts against the actual final binaries, or state |
| + precisely which later diff requires a narrow witness rerun. No stale-binary |
| + “verified” report. Required witness failures block the implementation |
| + acceptance, not this planning commit. |
| +- [ ] One whole-branch review covers the complete platform diff, F-D/IAM, |
| + ingress name/region boundaries, conservative withdrawal limits, census, |
| + tests, copy and witnesses. Its brief carries previous round history and |
| + the five Review Focus inputs. P1 blocks; P2 fixes close without a new |
| + round; P3 stays in the follow-up note. Do not commission separate reviews |
| + for low-risk helper/doc tasks. |
| +- [ ] Controller pushes/describes the implementation branch on amadan, reads |
| + green CI on the full 40-character tip, and lands only when its gates and |
| + stated scope questions are resolved. Use `amadan branch merge ... -squash |
| + -expect <tip>` with a short subject/body; read main CI afterward. Nothing |
| + here authorizes merging/applying the pinfra/flagship proposals or deploying |
| + the platform. This planner does not push. |
| +- [ ] Commit generated approval material with a short subject, e.g. |
| + `ha: record G2 census and branch verification`. |
| + |
| +## Questions for the controller |
| + |
| +**Q1, ingress source.** Removing stale rows requires routing metadata for |
| +ineligible ingress. Recommend T2's read-only projection from the existing |
| +record scan/view, with no new record, poll or hosting permission. This is a |
| +new internal routing capability and needs explicit review. If the controller |
| +chooses an edges-file projection instead, specify additive HA/pool/primary/ |
| +lifetime metadata, all parsers and unknown-host behavior before dispatch; |
| +do not retain stale ordinary rows as the forwarding mechanism. |
| + |
| +**Q2, pending duties and special rows at pool withdrawal.** Recommend T3's |
| +narrow refusal: stop/fence promptly but retain a row whose duties have no |
| +proven successor or whose ownership belongs to another subsystem. Deleting |
| +it loses I3 coverage; pretending its live owner terminated changes a ruling. |
| +Automatic visitor-free transfer of a live box's remaining duties is a separate |
| +capability and must be designed before expanding this task. The ordinary |
| +safe-row removal is in this branch; the pending cases are explicit operator |
| +findings/follow-ups, not silent “cleanup complete”. |
| + |
| +**Q3, fixed-topic versus group-topic.** Recommend the explicit group-topic |
| +sink + grant for both US roles in the G3 card, while keeping IE root proposals |
| +scoped to their actual sinks. The US group is still a draft and belongs to |
| +carloku-infrastructure, not pinfra. Prepare that repo's separate unmerged PR |
| +when the controller owns the root; do not mislabel it as a pinfra change. |
| +The exact IE role pairs are in T9; their runtime sinks remain unverified. |
| +Treat setting/readback of those sinks as part of the later deployment scope, |
| +not a claim that the grant alone proves page delivery. |
| + |
| +**Q4, witness authorization.** Recommend a controller-owned, expiring root |
| +runner plus one disposable peer per witness, using the existing dev-account |
| +runner role and no dev boxes. Distinct real instance IDs are necessary to |
| +exercise holder routing without replacing the production identity path. The planner/implementers may write and compile the scripts now. The |
| +controller records account, region, exact resources, role permissions, |
| +network effects, cost, duration and cleanup before obtaining/confirming the |
| +scoped launch approval. A failed cleanup readback remains a blocker. |
| + |
| +**Q5, release timing and review ledger.** These fixes protect currently active |
| +HA code and should ride the next controller-scheduled release before G3. |
| +No release date or new approval is invented here. Carry the RCA and all prior |
| +G2-fix review history into the first execution brief. Keep this branch if an |
| +unmerged dependency is proposed; do not review against that dependency. |