plans: P1b-3a plan rev 3, final (N-HA12)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+51
−28
docs/superpowers/plans/2026-11-01-region-ha-p1b3-placement.md+51 −28
CI passed — run details
Intent
Attributed to this commit: 43.0 g CO₂e (5,633,517 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-p1b3-placement, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/docs/superpowers/plans/2026-11-01-region-ha-p1b3-placement.md b/docs/superpowers/plans/2026-11-01-region-ha-p1b3-placement.md| index 694ede1c9..143f5ab94 100644 |
| --- a/docs/superpowers/plans/2026-11-01-region-ha-p1b3-placement.md |
| +++ b/docs/superpowers/plans/2026-11-01-region-ha-p1b3-placement.md |
| @@ -1,4 +1,4 @@ |
| -# Region HA P1b-3a: cold-wake placement implementation plan — rev 2 |
| +# Region HA P1b-3a: cold-wake placement implementation plan — rev 3 |
| > **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. This commission is planning only; do not start implementation or dispatch reviewers from this session. |
| @@ -10,7 +10,9 @@ |
| **Spec:** `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md`, rev 6.1, §3.1, §4, §6.3, §7, §9, §11, §18, §19 and §21. Code citations are against **44d810d0**, the amadan `origin/main` base of `region-ha-p1b3-placement`. Use current interfaces, not those in earlier plans. |
| -**Status:** Rev 2 answers Opus round 1 (NOT READY: 3 P1, 4 P2). This revision has not had independent review. No production code or deployment authorized; local planning commit only. All code citations below were re-read against 44d810d0; proposed files have no invented line numbers. |
| +**Status:** rev 3, final. Opus round 2 READY AFTER FIXES; P2s closed by N-HA12. Review closed. |
| + |
| +No production code or deployment authorized; local planning commit only. Code citations use 44d810d0; proposed files have no invented line numbers. |
| ## Rulings |
| @@ -18,6 +20,7 @@ |
| - **N-HA10:** Forward at the front, after route lookup, before gates/assets/guards/records/limits/usage/analytics. Preserve P1b-2's insertion point and exclusions. |
| - **N-HA7 / §19:** `rt.HA` selects the HA acquire regardless of `CARLOS_REGION_HA`. The box switch gates placement only; turning it off preserves P1b-2 holder probing and local HA wake. |
| - **N-HA11, Paul, 2026-11-01:** P1b-3b uses a small SQS consumer on the existing EC2 termination queue, about **180 receives/hour/box**, with **no new S3 polling**. The view-age check is the fallback for lost events. This settles the trigger choice, not approval to mutate infrastructure. |
| +- **N-HA12, Paul, 2026-11-01 (stopping rule 2, I4 family “placement must preserve main's recovery”):** “a placement target that has not woken the host is excluded for 10 s”. Enforce this only in the per-box suspect list; only a success or an answer naming a holder clears suspicion. Placement none, headerless 503, 502, Status 0 and out-of-view mark the target suspect under the existing epoch rules. Snapshot peers require the mirrored signing key checked by forwardHA. Task 4 models refusal/hang/out-of-view with fresh published evidence, and mutation **placement-refusal-clears-suspect** is checked by I5. This central-invariant ruling closes round 2 P2-A/P2-B. |
| - **I1 / N-HA9:** Only `lease.AcquireHA` authorizes a writer. Another box's expired lease still needs confirmed termination; a terminated owner's unexpired lease still waits. Placement supplies neither proof. |
| - **I2:** Clean releaser is a routing preference. Only `hafresh.DecideKeep` proves local DB/files reusable after acquire; marker alone cannot prove files still match. |
| - **H4 / astra-1.17:** HRW (highest random weight, rendezvous hashing) does not precede capacity. Order: eligible clean releaser, then `ChooseRoomiest`: soft app spread, free memory, greatest SHA-256 of `host + "\x00" + ref`, smallest reference. A10's HRW starter for never-woken duties belongs to 3b. |
| @@ -44,8 +47,9 @@ Switch-on: first dev release immediately after 3a merges, fixed sophie/leo in `h |
| | Round | Brief / findings | Verdict | Fault families / disposition | |
| |---|---|---|---| |
| | 1 | `REVIEW-BRIEF-REGION-HA-P1B3-R1.md` at 0cd04be9; `REVIEW-REGION-HA-P1B3-R1.md`, Opus (other model family), code 44d810d0 | **NOT READY: 3 P1, 4 P2, 6 P3** | P1-1/2/3: placement must preserve main's recovery (same-box / switch / reachability); P2-1: adoption lag; P2-2: bounded lock reads; P2-3: executable wiring; P2-4: complete copy contract. Rev 2 dispositions below; not a new review verdict. | |
| +| 2 | `REVIEW-BRIEF-REGION-HA-P1B3-R2.md`, rev 2 at a905f09c; `REVIEW-REGION-HA-P1B3-R2.md`, Opus, recorded at 2cb0b5f7, code 44d810d0 | **READY AFTER FIXES: no P1, 2 P2, 6 P3** | P2-A/P2-B: I4 recovery family, second consecutive round after R1 P1-3. Paul chose the central-invariant option in N-HA12; rev 3 closes both P2s and takes the cheap P3s below. Review closed. | |
| -One of three P1b-3 rounds is spent; rounds 2–3 remain. Stop at the first round with no P1, fix its P2s without reopening, and list P3s as follow-ups. If a second consecutive round finds the same invariant broken, stop fixing and offer the refuse/cut/central-invariant choice before a third fix. A fourth round needs Paul's go. No reviewer is dispatched in this session. Spec, P1b-1, P1b-2 and dead-holder backoff each spent three rounds; all remain closed. I3 duty-file transfer was cut after three P1 rounds: do not recreate it. Carry this history into briefs/handoffs. Splits/renames do not reset rounds spent on the same design/change. |
| +Two P1b-3 plan rounds were spent. Round 2 has no P1: stopping rule 1 closes review, with no further round. The repeated I4 family triggered stopping rule 2; Paul settled it with N-HA12 before these final fixes. N-HA12 supplies the central invariant for these final fixes; review remains closed. No reviewer is dispatched in this session. Spec, P1b-1, P1b-2 and dead-holder backoff each spent three rounds; all remain closed. I3 duty-file transfer was cut after three P1 rounds: do not recreate it. Carry this history into briefs/handoffs. Splits/renames do not reset rounds spent on the same design/change. |
| ## Global Constraints |
| @@ -94,29 +98,29 @@ All paths in this table are relative to the module root. These are existing inse |
| **H4, only in ChooseColdWake.** Inputs: canonical host, account/app key, optional clean releaser and scoped WakeSnapshot. Prefer clean releaser in `Placeable(Serving,nil,now)`. Otherwise ChooseRoomiest on eligible candidates with app loads. None eligible: ChooseRoomiest on remaining serving candidates without spread, return OverCapacity. Missing headroom contributes zero, never guessed totals. Only V==1, Clean, non-empty Box on a valid HA release marker supplies affinity; DecideKeep still proves reuse after acquire. Thresholds remain in existing policy helpers. |
| -**§4.3 scope, only in edge wakeSnapshot.** From one immutable homeSnapshot require same region/placement, non-empty data bucket/key fingerprint, hibernation_configured:true, region-ha-1 and fresh generation; peers also need a dialable address. Candidate.BoxID and Running keys use published **box**, never box_id (which may be an EC2 iid). A peer must publish primary role:home for rt.Host with matching account/app; alias/wildcard/cert-only/replica never qualifies. **Self adopts through the request's local route**, even before its hosts entry is folded. Missing/stale own file returns unusable evidence and applicability chooses Base; add no publisher→edge freshness bridge. Reject non-serving candidates; absent role means serve. ServesSharedPool is not required (leo legitimately serves hapair). Holder view remains independent of this policy and age. |
| +**§4.3 scope, only in edge wakeSnapshot.** From one immutable homeSnapshot require same region/placement, non-empty data bucket/key fingerprint, hibernation_configured:true, region-ha-1 and fresh generation; peers also need a dialable address and `len(signingKey(m.meshKeys())) > 0`, the same mirrored value forwardHA checks (`internal/edge/forwardha.go:191`; `internal/edge/homemap.go:1173`). No key excludes peers, not self; a free host on ordinary serving ingress can still wake locally. No request-time key read. Candidate.BoxID and Running keys use published **box**, never box_id (which may be an EC2 iid). A peer must publish primary role:home for rt.Host with matching account/app; alias/wildcard/cert-only/replica never qualifies. **Self adopts through the request's local route**, even before its hosts entry is folded. Missing/stale own file returns unusable evidence and applicability chooses Base; add no publisher→edge freshness bridge. Reject non-serving candidates; absent role means serve. ServesSharedPool is not required (leo legitimately serves hapair). Holder view remains independent of this policy and age. |
| **Additive decode boundary.** Keep the existing holder fields' decoder unchanged. New placement fields live in RawMessage/secondary decode, including host Replica. A bad required placement type excludes that candidate from placement only; it cannot reject the whole file or remove a P1b-2 holder target. Decode Apps separately: missing/bad/stale map or negative counts mean zero spread, never invalidate core headroom/holder fields. A malformed own role/draining field sets LocalDenied rather than permitting local placement. No new tolerance in existing identity/lease parsers. |
| **Counts, only in AwakeApps.** Key `release.RouteAccount(rt)+"/"+rt.App`: owned awake hosts once, standalone workers included, co-spawn no second host. Exclude waking/stopping/fenced/lease-lost/shutdown. Missing callback omits map. No store/registry call; Hibernate is policy, not an awake count. |
| -**Placement reachability, only in placementPeers.** Bounded per-ref suspicion lasts 10s after failed dial, renewed only by a subsequent admitted failed dial; any answer from that ref clears it. Filter before releaser/H4. The failed request still gets 503, no second choice in that request; the next request (including a different host) can choose a survivor immediately. Suspect placement never becomes a per-host holder-suspect refusal. Re-admit after 10s; retain per-address dial gate. A true holder is never replaced by H4 because it is suspect. A failed expired-owner Recovery hint uses this ref suspicion to return Base on the next request, preserving main's termination check; it cannot set a positive-holder suspect entry. Stale results cannot poison a newer answer/acquire. |
| +**Placement reachability / N-HA12, only in placementPeers.** Bounded per-ref suspicion lasts 10s after a target fails to wake the host. Placement none, headerless 503, 502, Status 0, failed dial and out-of-view all mark that target suspect; only a success or an answer naming a holder clears suspicion. Renew only after a subsequent admitted failed attempt, under the existing epoch rules. Filter before releaser/H4. The failed request retains its existing 503 or 502 answer, no second choice in that request; the next request (including a different host) can choose a survivor immediately. Suspect placement never becomes a per-host holder-suspect refusal. Re-admit after 10s; retain per-address dial gate. A true holder is never replaced by H4 because it is suspect. A failed expired-owner Recovery hint uses this ref suspicion to return Base on the next request, preserving main's termination check; it cannot set a positive-holder suspect entry. Stale results cannot poison a newer answer/acquire. |
| -**N-HA10, only in frontForwardHA.** Chosen placement peer disappearing/no mesh key/dial failure answers existing 503 Retry-After:10, zero ingress begin/second hop/accounting. Ordinary holder/recovery ForwardNotInView keeps Base behavior. Verified hop never rechooses; receiver acquires or returns P1b-2 diagnostics. C1 is only for prohibited local service with no usable route; missing snapshot/read alone is not C1. |
| +**N-HA10, only in frontForwardHA.** Chosen placement peer disappearing/key lost after projection/dial failure answers existing 503 Retry-After:10, zero ingress begin/second hop/accounting. Ordinary holder/recovery ForwardNotInView keeps Base behavior. Verified hop never rechooses; receiver acquires or returns P1b-2 diagnostics. C1 is only for prohibited local service with no usable route; missing snapshot/read alone is not C1. |
| **Races.** Equal evidence yields equal preference; differing folds may choose differently. Conditional acquire is still the one writer gate. Without §6.5 retry a loser may return 503. A headerless successful placement answer is reachable, not proof of a holder. |
| ## Round 1 dispositions |
| -Evidence names existing code; tasks name proposed changes. All P1/P2 findings are addressed in rev 2, awaiting independent review. Fault-family names are invariants, not affected files. |
| +Evidence names existing code; tasks name proposed changes. Opus round 2 confirmed the rev 2 fixes below, with the reachability gaps carried as P2-A/P2-B and closed by N-HA12 in rev 3. Fault-family names are invariants, not affected files. |
| | Finding / invariant | Verified evidence | Rev 2 disposition, witness and mutation | |
| |---|---|---| |
| | **P1-1 — §9.6/I4, preserve main's recovery** | `internal/hafresh/acquire.go:72,93,99`; `internal/activator/haforward.go:146,193,207`; `internal/activator/activator.go:6145` | **Take.** Tasks 2–4: DecidePlacement excludes owner-bearing locks from H4; self local, expired peer recovery hint. TestPlacementExpiredOwner / TestColdPlacementExpiredOwnerRecovery (crash/restart, roomiest peer, requests at both), mutation **placement-ignores-expired-owner**. | |
| | **P1-2 — N-HA7/§19, preserve main's recovery** | `internal/host/edgesfile.go:196`; `internal/host/headroom.go:13`; `internal/edge/homemap.go:362`; `internal/edge/forwardha.go:147` | **Take.** Tasks 2–4: Enabled input, off returns Base after holder probe, born-HA still acquires HA. TestPlacementSwitchOff / TestColdPlacementSwitchOff; mutation **placement-ignores-switch**. | |
| -| **P1-3 — I4, preserve main's recovery** | `internal/boxchoice/policy.go:27`; `internal/host/edgesfile.go:974`; `internal/edge/forwardha.go:204,299` | **Take.** Tasks 3–4: per-ref placementPeers, 10s, filter before H4/affinity, any answer clears. TestPlacementSuspectBox / TestColdPlacementDeadChoice: listener dies, next request within 10s wakes on survivor, cross-host exclusion; mutation **placement-ignores-suspect-box**. | |
| +| **P1-3 — I4, preserve main's recovery** | `internal/boxchoice/policy.go:27`; `internal/host/edgesfile.go:974`; `internal/edge/forwardha.go:204,299` | **Take.** Tasks 3–4: per-ref placementPeers, 10s, filter before H4/affinity. Rev 3 replaces the original any-answer clear rule with N-HA12; see round 2 dispositions. TestPlacementSuspectBox / TestColdPlacementDeadChoice: listener dies, next request within 10s wakes on survivor, cross-host exclusion; mutation **placement-ignores-suspect-box**. | |
| | **P2-1 — A20/I4, local adoption precedes fold** | `internal/edge/forwardha.go:147`; `internal/host/edgesfile.go:1202,1252`; `internal/edge/homemap.go:123,392` | **Take.** Tasks 2–4: self adoption from local route, peers from publication. TestWakeSnapshotSelfAdoptsBeforePublication / TestColdPlacementNewHostNoFold; mutation **placement-requires-published-self-host**. Missing own file uses Base. | |
| -| **P2-2 — budget, bounded ingress GETs** | `internal/activator/haforward.go:170,178`; `internal/activator/hacache.go:31,271` | **Take.** Tasks 3–4: keep original negative observation/deadline on placement none/headerless 503; no sliding TTL or guessed holder. TestPlacementRefusalKeepsObservation / TestColdPlacementRequestBudget; mutation **placement-drops-negative-on-refusal**, ingress/receiver counters. | |
| +| **P2-2 — budget, bounded ingress GETs** | `internal/activator/haforward.go:170,178`; `internal/activator/hacache.go:33,271` | **Take.** Tasks 3–4: keep original negative observation/deadline on placement none/headerless 503; no sliding TTL or guessed holder. TestPlacementRefusalKeepsObservation / TestColdPlacementRequestBudget; mutation **placement-drops-negative-on-refusal**, ingress/receiver counters. | |
| | **P2-3 — executable production wiring** | `internal/host/agent.go:576,744,944`; `internal/host/haforward_wiring_test.go:15,21`; `internal/host/hatakeover_wiring_test.go:20` | **Take.** Tasks 1/3/4/5A: one armHAPlacement helper wires both callbacks, called once by runAgent and executable witness. Accept single-call/order syntactic check only for uncallable agent entry; helper behavior executes. Read Apps from both live files. TestAgentArmsHAPlacement / TestHAPlacementPageWiring / TestColdPlacementProductionWiring; integration mutation **placement-skips-arm** suppresses the common helper's invocation. | |
| | **P2-4 — complete copy/interface contract** | `internal/host/alertsink.go:137`; `internal/edge/forwardha.go:147` | **Take.** Task 3/deck: C2 subject/body, C1 destination forwardha.go, C2 host/haplacement.go. TestHAPlacementPageWiring asserts both accepted strings, warning level/deadline; **placement-drops-page-subject** rejects loss of subject at that sink. Wording stays draft pending controller approval. | |
| | **P3-1 — avoid unused census surface** | `internal/edgesfile/snapshot.go:72,280` | **Take:** no console decoder/converter Apps change or test. Only writer, edge placement decoder and boxchoice.Headroom need it. Cheap removal. | |
| @@ -128,6 +132,21 @@ Evidence names existing code; tasks name proposed changes. All P1/P2 findings ar |
| No P3 is left as a reason to reopen review. Publisher freshness plumbing and live API telemetry stay outside this slice; the cheaper remedies above remove the acceptance gaps. |
| +## Round 2 dispositions |
| + |
| +Review is closed at **READY AFTER FIXES**, no P1. N-HA12 settles the repeated I4 family; these final changes do not start another round. |
| + |
| +| Finding / invariant | Rev 3 disposition, witness and mutation | |
| +|---|---| |
| +| **P2-A — I4 / sim I5, preserve main's recovery** | **Closed by N-HA12.** Task 3 placementPeers alone classifies unsuccessful Placement outcomes and owns the 10s exclusion/clear rule. TestPlacementRefusalMarksSuspect and TestColdPlacementUnusableChoice cover none/headerless 503/502/Status 0 while the peer keeps publishing. Task 4 action peerWakeFault and mutation **placement-refusal-clears-suspect** must fail I5 if refusals clear or fail to establish suspicion. | |
| +| **P2-B — I4, preserve main's recovery** | **Closed by N-HA12.** Task 2 requires the same mirrored signing key as forwardHA; TestWakeSnapshotRequiresSigningKey proves a free host still wakes locally with no key. A peer lost after projection returns out-of-view and enters the same Task 3 suspect list. TestFrontPlacementNeverFallsBack / TestColdPlacementUnusableChoice prove the next request uses a survivor within 10s. No second fallback policy. | |
| +| **P3-1 — request-path cost** | **Take.** Task 3 passes a lazy snapshot callback and invokes it only after existing bypass/holder handling. TestPlacementSnapshotIsLazy counts callback calls. | |
| +| **P3-2 — cache tag rule** | **Take.** Task 3 tags only the attempt's ref/kind/generation for result correlation. The tag never pins the next target; recompute from the current fold and suspect set within the original observation deadline. Headerless success clears suspicion without installing a positive holder; a changed fold may choose differently and encounter an ordinary held refusal. TestPlacementCachesObservationNotChoice pins this contract. | |
| +| **P3-3 — simulation shape** | **Take.** Task 4 imports activator for the pure DecidePlacement. Each protocol mutation changes model inputs or how the model applies an answer; no production mutation switch or copied applicability table. I5 checks bounded request-path recovery. | |
| +| **P3-4 — §20 page throttle** | **Take / accepted deviation.** Task 3 throttles once/region/hour/process. With N boxes there may be N pages per region/hour, exceeding §20's region-wide cap. Cross-process deduplication is a recorded follow-up; no coordination service or extra polling in 3a. | |
| +| **P3-5 — drill fault method** | **Take.** Task 5A pauses the approved chosen edge with SIGSTOP for at least 10s, keeps its publication fresh and resumes with SIGCONT in cleanup. It tests free hosts without a rapid service restart or an owner-lease change. | |
| +| **P3-6 — citations** | **Take.** Negative TTL constant is `internal/activator/hacache.go:33`; home-map interval is `internal/edge/homemap.go:123` (126 is a closing parenthesis). Signing-key check/mirror anchors are `internal/edge/forwardha.go:191` and `internal/edge/homemap.go:1173`. | |
| + |
| ## S3 request budget |
| Logical API attempts, failed conditional calls included. SDK transport retries and unchanged config/plan/replication calls counted separately, not zero. G/P/L/D = GET/PUT/LIST/DELETE. R = existing restore: up to 5 Litestream LISTs + one per extra 1,000 L0 files and object GETs, one files-manifest GET plus referenced app/platform GETs (§18). Existing baseline/changed-secret publication remains; placement adds no restore/escrow read. |
| @@ -143,11 +162,11 @@ Logical API attempts, failed conditional calls included. SDK transport retries a |
| | No usable placement snapshot/candidate on ordinary serving ingress | Base: 1G front on miss + local acquire (1G+1P if taken), plus R; absent +1L. No placement-induced 503 | |
| | Explicit non-serving ingress, no usable permitted route | 0 if observation cached, else 1G; 0P/0L; C1/503 | |
| | Probe error/malformed | Base: 1 attempted front G + local acquire read; persistent fault/refusal 0P/0L. If second read succeeds, ordinary acquire costs; never cached as free | |
| -| Choice gone/no mesh key/unreachable | Probe as above; no ingress acquire; dial costs 0 S3 | |
| +| Choice gone/key lost after projection/unreachable | Probe as above; no ingress acquire; dial costs 0 S3; mark ref suspect via N-HA12. No key at projection excludes peers and uses self/Base | |
| | True holder suspect window | **0 S3**, 0 dials for that host for 10s; existing holder backoff | |
| | Placement ref suspect, free observation cached | **0 ingress G**, 0 dials to suspect ref for 10s; next request chooses survivor/Base, whose acquire costs 1G (+1P if taken), plus R | |
| | First refused placement target acquire (none/headerless 503) | **2G, 0P** = 1G ingress observation + 1G receiver refusal; no LIST unless absent-prefix check | |
| -| Repeated refused placement within original 10s | **1G/request, 0P** at receiver; **0 ingress G**, no expiry extension. After deadline next request returns to 2G; legacy/leftover locks use Base with 1G local refusal per cached observation | |
| +| Requests after placement refusal within original 10s | **0 ingress G**, no expiry extension or retry to suspect ref. Survivor/Base acquire costs **1G/request** (+1P if taken), plus R; if it also refuses, 0P. At deadline ingress re-reads. Legacy/leftover locks keep Base with 1G local refusal per cached observation | |
| | Expired owner recovery hop | Miss 1G ingress + 1G owner acquire (+1P if proven empty), plus R; cached observation removes ingress G. Failed Recovery dial: next request Base, 1G local acquire (+1P after confirmed termination), no ingress GET before original deadline; at most 1 EC2 describe/10s/iid | |
| | Projection/awake-count pass | **0G+0P+0L+0D** | |
| | Existing 2s edges check, only counts change | **0 new calls**, headroom outside gate | |
| @@ -167,11 +186,11 @@ Quiet: **0 incremental S3 requests/box/pass and /day**. §18 baseline about 3,30 |
| 3. Hint becomes hour-long holder: Task 3 TestPlacementHintIsNotAHolder. |
| 4. Counts create polling bill: Task 1 TestAwakeAppsRideTimedPublication; Task 4 budget witness. |
| 5. Different choices/sealed restore: Task 4 TestColdPlacementCompetingViews/TestColdPlacementSealedWake. |
| -6. Applicability/recovery: round-1 disposition witnesses and mutations; switch off, expired-owner restart, lost target, route before fold, stalled index without extra reads. |
| +6. Applicability/recovery: round-1/2 disposition witnesses and mutations; N-HA12 refusal/hang/out-of-view, no signing key, switch off, expired-owner restart, lost target, route before fold, stalled index without extra reads. |
| --- |
| -Tasks 2/3 **[own review]** for routing/cache; Task 4 production wiring, census, whole-branch review. Task 1 no separate review unless publication authority changes beyond additive inputs. Follow `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`. Stop at first no-P1 round; P2 fix without reopening, P3 follow-up. Same fault family twice running: stop fixing, offer Paul's refuse/cut/central-invariant choice. Round 4 requires approval. No review dispatched in drafting session. |
| +Tasks 2/3 **[own review]** for routing/cache; Task 4 production wiring, census, whole-branch review. Task 1 no separate review unless publication authority changes beyond additive inputs. Follow `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`. Stop at first no-P1 round; P2 fix without reopening, P3 follow-up. Same fault family twice running: stop fixing, offer Paul's refuse/cut/central-invariant choice. Round 4 requires approval. These are later implementation review gates; this plan review is closed after round 2, with P2s settled by N-HA12. No review dispatched in this session. |
| ### Task 1: Live app counts and pure cold-wake choice |
| @@ -216,11 +235,11 @@ func TestColdWakeCleanEligibleReleaser(t *testing.T) { |
| **Files:** Create `internal/edge/wakeplacement.go`, `internal/edge/wakeplacement_test.go`. Modify the extension decode beside `internal/edge/homemap.go:134,169,730`. Leave holderview.go's age-independent compatibility rules unchanged. |
| **Interfaces:** |
| -- `func (m *homeMap) wakeSnapshot(rt registry.Route, now time.Time) boxchoice.WakeSnapshot`: read one immutable snapshot, copy slices/maps; canonical rt.Host/account/app. Set Enabled from the existing parsed box switch (`internal/edge/homemap.go:362`). No homes means zero/unusable snapshot and Base, not a mandatory placement refusal. |
| +- `func (m *homeMap) wakeSnapshot(rt registry.Route, now time.Time) boxchoice.WakeSnapshot`: read one immutable snapshot, copy slices/maps; canonical rt.Host/account/app. Set Enabled from the existing parsed box switch (`internal/edge/homemap.go:362`). Peer candidates additionally require a non-empty `signingKey(m.meshKeys())`, exactly as forwardHA does; self does not require a signing key. No homes means zero/unusable snapshot and Base, not a mandatory placement refusal. |
| - Capture placement-only fields as RawMessage, then decode Generation, Capabilities, HibernationConfigured, Draining, Role, Drained, headroom scalars/Apps, and host Replica separately. Keep existing holder fields strict. Invalid required additions exclude placement only; bad Apps means empty spread. Track LocalDenied from own non-serving/malformed safety fields even if generation is stale. Missing fields use established defaults (absent role serve, absent capability/config not placement evidence). |
| - Usable requires a compatible fresh own file with identity matching self; it need not be in Serving if explicitly non-serving. Self membership for this host comes from the local route, not own Hosts. Peer membership still requires exact primary role:home/account/app and compatible published evidence. Map Candidate.BoxID/Running by f.Box, never f.BoxID. Reuse one freshness predicate from boxchoice (export the existing `headroomFresh` as `HeadroomFresh`, with callers updated), not duplicate constants/comparisons. |
| -- [ ] **Step 1: Write failing tests.** TestWakeSnapshotCompatibility: store/key/region/placement/capability/config/dial. TestWakeSnapshotRequiresThePrimaryHost: leo shared-pool false + hapair host in; peer no primary, alias/cert/wildcard/replica/account/app mismatch out. TestWakeSnapshotSelfAdoptsBeforePublication: own fresh compatible file lacks new host, local route qualifies self; same absence on peer does not. TestWakeSnapshotUsesBoxReference: box!=box_id and choice passes boxInView. TestWakeSnapshotFreshness: 15m in, +1ns out; future 1m in, +1ns out; absent/bad generation unusable; original generation for carried-forward files; explicit non-serving self LocalDenied independent of age. TestWakeSnapshotMalformedAdditionsPreserveHolder: wrong type in each new field/Replica leaves file/holder forwarding intact, candidate excluded; bad Apps alone keeps headroom/candidate with zero spread. TestWakeSnapshotHeadroomAndApps: missing headroom in Serving but ineligible, negative count zero, copies immutable. TestWakeSnapshotNoIO: 100 projections zero calls. |
| +- [ ] **Step 1: Write failing tests.** TestWakeSnapshotCompatibility: store/key/region/placement/capability/config/dial. TestWakeSnapshotRequiresSigningKey: nil/empty mirrored signing key excludes every peer but preserves self; a free host still wakes locally under HA; cached usable key admits compatible peers, no key-store read. TestWakeSnapshotRequiresThePrimaryHost: leo shared-pool false + hapair host in; peer no primary, alias/cert/wildcard/replica/account/app mismatch out. TestWakeSnapshotSelfAdoptsBeforePublication: own fresh compatible file lacks new host, local route qualifies self; same absence on peer does not. TestWakeSnapshotUsesBoxReference: box!=box_id and choice passes boxInView. TestWakeSnapshotFreshness: 15m in, +1ns out; future 1m in, +1ns out; absent/bad generation unusable; original generation for carried-forward files; explicit non-serving self LocalDenied independent of age. TestWakeSnapshotMalformedAdditionsPreserveHolder: wrong type in each new field/Replica leaves file/holder forwarding intact, candidate excluded; bad Apps alone keeps headroom/candidate with zero spread. TestWakeSnapshotHeadroomAndApps: missing headroom in Serving but ineligible, negative count zero, copies immutable. TestWakeSnapshotNoIO: 100 projections zero calls. |
| - [ ] **Step 2: Run** `nice -n 19 go test ./internal/edge -run 'TestWakeSnapshot' -count=1`. Expected FAIL. |
| - [ ] **Step 3: Implement** projection/extension decoder; refuse incomplete placement cases at this boundary instead of adding stale-self tolerances or request refreshes. No roster, publisher bridge or global holder-view change. |
| - [ ] **Step 4: Run** Step 2 plus `nice -n 19 go test ./internal/edge ./internal/boxchoice -run 'TestHolderView|TestForwardHANotInView|TestHome|Fresh|Placeable' -count=1`. Expected PASS. |
| @@ -232,15 +251,15 @@ func TestColdWakeCleanEligibleReleaser(t *testing.T) { |
| **Interfaces / invariant ownership:** |
| - **Applicability / I4/N-HA7:** `func DecidePlacement(rt registry.Route, self hafresh.Self, view *hafresh.View, s boxchoice.WakeSnapshot, peers PlacementPeerView, now time.Time) PlacementDecision`, pure and callable by simulation. `PlacementDecision` has `Kind` (Base, Recovery, Place, Refuse), `Ref`, `OverCapacity`, `Reason`. Implement only the contract table above here; call ChooseColdWake after filtering suspects. Never call DecideAcquire/proofs here or grant authority. A valid release for placement requires HAOn and marker V==1 with non-empty Box; unclean valid marker has no affinity. Unknown markers/legacy owner/read failure use Base. Expiry equal to now is not proof of freedom. LocalDenied blocks Base only when Enabled. An expired peer is Recovery only while present in fresh Serving and not suspect; otherwise Base preserves termination recovery. Peer saturation declines placement in this same table (Base or explicit LocalDenied refusal), before any forwarding; reserve peer tracking as part of the bounded snapshot used for this decision. |
| -- **Front boundary / N-HA10:** `ForwardTarget(ctx context.Context, rt registry.Route, s boxchoice.WakeSnapshot) edge.ForwardDecision`; update all callers/doubles (`rg 'ForwardTarget'`). Add `ForwardKind` enum to Decision/Result: Holder (zero), Recovery, Placement; copy through result. Add Unavailable only for the rule's Refuse/C1. Existing Refuse remains true-holder suspicion. Base returns zero decision. Recovery routes owner with Kind Recovery; Place self returns local, Place peer forwards with Kind Placement. Edge checks Unavailable/Refuse before all accounting; only Placement changes ForwardNotInView to 503. Holder/Recovery preserve local fallback. Hops skip the whole front decision. |
| +- **Front boundary / N-HA10:** `ForwardTarget(ctx context.Context, rt registry.Route, snapshot func() boxchoice.WakeSnapshot) edge.ForwardDecision`; update all callers/doubles (`rg 'ForwardTarget'`). Add `ForwardKind` enum to Decision/Result: Holder (zero), Recovery, Placement; copy through result. Add Unavailable only for the rule's Refuse/C1. Existing Refuse remains true-holder suspicion. Base returns zero decision. Recovery routes owner with Kind Recovery; Place self returns local, Place peer forwards with Kind Placement. Edge checks Unavailable/Refuse before all accounting; only Placement changes ForwardNotInView to 503. Holder/Recovery preserve local fallback. Hops skip the whole front decision. Edge passes a lazy closure over wakeSnapshot, never an eagerly projected value. Service invokes it only after existing non-HA/unmanaged/live-entry and positive-holder/suspect handling. The projected Enabled still comes from the existing parsed switch; do not add a second switch policy. |
| - **Observation budget:** `holderRead { Ref string; View *hafresh.View; Err error }`, `holderResolution { Ref string; Refuse bool; Gen uint64; View *hafresh.View }`; resolve retains immutable negative View for original 10s. Include detached bounded single-flight, generations, canceled waiter behavior, failed re-probe of true suspect remaining refused. Nil View never means absent. ForwardTarget keeps existing non-HA/unmanaged/live-entry bypass and positive holder/suspect behavior, then calls DecidePlacement even on zero View/snapshot. |
| -- **Preference is not holder:** `holderCache.placement(host,ref)` tags choice under the observation's generation without resetting expiry. Recovery hints also use original negative deadline. NoteForward branches once by Kind. For Placement/Recovery, none or headerless 503 retains View/deadline; headerless 200 only clears reachability, never a 1h positive. A platform holder header can install positive; self header invalidates for local acquire. NotInView retains negative observation for these hints; Placement refuses this request, Recovery serves Base. True Holder retains P1b-2 drop semantics. No expired owner is installed positive without a fresh platform holder header. |
| -- **Reachability / I4:** one Service-owned `placementPeers` keyed by ref, max 50,000 tracked refs, 10s failure deadline. `snapshot(now)` supplies suspect set and saturation state to DecidePlacement; add `PlacementPeerView { Suspect map[string]bool; Saturated bool }` as that argument instead of an unbounded caller map. `begin(ref)` reserves a ref epoch token, copied as PeerGen in Decision/Result; `note(result)` records failed Placement/Recovery dials and clears on any real answer from ref (any Kind). Epoch advances on new answer/failure; stale failure cannot overwrite later success, nor a superseded host generation/acquire. Track tokens before dial, reuse during concurrent choices, never sliding-renew from a filtered request. At bound, decline new placement attempts until expired/idle entries can be reclaimed; do not evict an active suspect early or grow unbounded. Keep true Holder per-host suspicion separate; Recovery never installs it. No new S3 or background probe. |
| +- **Preference is not holder:** `holderCache.placement(host,ref)` tags only the attempt ref/kind for result correlation under the observation's generation without resetting expiry. It never pins the target: each subsequent request recomputes from the current fold/suspect set, including after headerless success. A changed fold may then choose local and get an ordinary held refusal; this does not authorize a writer or require an extra ingress GET. Recovery hints also use original negative deadline. NoteForward branches once by Kind. For Placement/Recovery, unsuccessful hints retain View/deadline; placementPeers alone applies N-HA12 to their outcomes. A headerless success clears suspicion, never installs a 1h positive. A platform holder header can install positive; self header invalidates for local acquire. NotInView retains negative observation for these hints; Placement refuses this request, Recovery serves Base. True Holder retains P1b-2 drop semantics. No expired owner is installed positive without a fresh platform holder header. |
| +- **Reachability / I4:** one Service-owned `placementPeers` keyed by ref, max 50,000 tracked refs, 10s failure deadline. `snapshot(now)` supplies suspect set and saturation state to DecidePlacement; add `PlacementPeerView { Suspect map[string]bool; Saturated bool }` as that argument instead of an unbounded caller map. `begin(ref)` reserves a ref epoch token, copied as PeerGen in Decision/Result; `note(result)` is the sole owner of N-HA12 outcome classification and suspect state: Placement none/headerless 503/502/Status 0/out-of-view and failed dials mark ref suspect for 10s; Recovery dial failures use this same list. Only a success or an answer naming a holder clears suspicion, including answers of other Kinds; none never clears it. Edge and holderCache pass outcomes without a second classification or exclusion policy. Epoch advances on an admitted failure or a qualifying clear; stale failure cannot overwrite later success, nor a superseded host generation/acquire. Track tokens before dial, reuse during concurrent choices, never sliding-renew from a filtered request. At bound, decline new placement attempts until expired/idle entries can be reclaimed; do not evict an active suspect early or grow unbounded. Keep true Holder per-host suspicion separate; Recovery never installs it. No new S3 or background probe. |
| - **One arming function / P2-3:** `func armHAPlacement(svc *activator.Service, page func(context.Context,string,string,string) error)` in host/haplacement.go calls setHAAwakeApps(svc.AwakeApps) and installs `Service.OnHAOverCapacity func(region,host,ref string)`. runAgent calls it exactly once with PageOperator after creation and before the startup coordinator invokes svc.Start (`internal/host/agent.go:744`) and before edgesFileLoop. The witness identifies the actual startup coordinator in agent.go, not an invented startupWork variable. Executable witnesses invoke this exact helper and clean up the atomic source. The only allowed syntactic witness checks call count, Service identity and order in agent.go; it is not evidence for callback behavior. |
| -- **Operator notice / P2-4:** Service throttles over-capacity callback once/region/hour/process. armHAPlacement sends accepted **C2 subject and body** with snapshot.Region, host, ref, warning level via PageOperator (`internal/host/alertsink.go:137`), detached with 5s timeout. Never block request/read S3. Cross-process page deduplication outside scope. |
| +- **Operator notice / P2-4:** Service throttles over-capacity callback once/region/hour/process. armHAPlacement sends accepted **C2 subject and body** with snapshot.Region, host, ref, warning level via PageOperator (`internal/host/alertsink.go:137`), detached with 5s timeout. Never block request/read S3. Accepted deviation from spec §20: with N boxes, this can send N pages/region/hour instead of the region-wide maximum of one. Cross-process page deduplication is a follow-up outside 3a; no new coordination or polling. |
| - **Drill evidence / P3-5:** throttled decision log includes host, decision Kind, ref, stable Reason (base-switch-off, base-no-snapshot, owner-recovery, clean-releaser, roomiest, over-capacity, peer-suspect) and evidence generation. At most once/host/minute, within bounded host state, no S3. Wrapped diagnostic fields are not product copy. Reason selection is part of DecidePlacement, not a second policy. |
| -- [ ] **Step 1: Write failing tests.** TestPlacementExpiredOwner: self expired/equality local despite roomiest peer; expired serving peer recovery despite low headroom; owner outside fresh Serving/out of holder view or ref-suspect uses Base, never H4; failed Recovery dial followed by confirmed termination recovers locally, no repeated-hop blackout; no termination proof invented. TestPlacementSwitchOff: born-HA empty fold/zero snapshot, first local HA wake, held peer still forwarded, no H4/page. TestPlacementStaleSelfUsesBase / TestPlacementNoSnapshotUsesBase / TestPlacementProbeFailureUsesBase: no new C1, local acquire still validates; explicit LocalDenied instead refuses before begin when no peer. TestPlacementSuspectBox: marker-affinity and roomiest ref excluded across hosts; next request picks survivor within 10s; no repeated dial; expiry re-admits, any response clears, late failure cannot poison newer success/acquire; bound declines new placement safely. TestPlacementRefusalKeepsObservation: none/headerless 503 repeated through original t+10s uses one ingress GET, one receiver GET/request, no sliding expiry. TestPlacementCachesObservationNotChoice: fold change within 10s recomputes, no GET; expiry one GET. TestPlacementHintIsNotAHolder covers Placement and Recovery headerless answers. TestPlacementSingleFlight: 20 misses one GET/full view, one canceled waiter cannot cancel others. TestPlacementHeldOwnerWins / TestPlacementPrefersCleanReleaser / TestPlacementChoosesRoomiest / TestPlacementNoCapacityStillWakes: ordinary holder, H4, one warning callback/region/hour, zero extra calls. TestFrontPlacementNeverFallsBack: disappeared choice/no mesh key → 503 RA10, zero ingress begin. TestPlacementHopNeverRechooses: differing receiver view, no onward hop. TestAgentArmsHAPlacement checks the one agent call; TestHAPlacementPageWiring executes helper and asserts Apps, callback, accepted subject/body, warning/deadline/throttle. TestPlacementDecisionLogIsBounded: reason/ref, no visitor log flood/store calls. |
| +- [ ] **Step 1: Write failing tests.** TestPlacementExpiredOwner: self expired/equality local despite roomiest peer; expired serving peer recovery despite low headroom; owner outside fresh Serving/out of holder view or ref-suspect uses Base, never H4; failed Recovery dial followed by confirmed termination recovers locally, no repeated-hop blackout; no termination proof invented. TestPlacementSwitchOff: born-HA empty fold/zero snapshot, first local HA wake, held peer still forwarded, no H4/page. TestPlacementStaleSelfUsesBase / TestPlacementNoSnapshotUsesBase / TestPlacementProbeFailureUsesBase: no new C1, local acquire still validates; explicit LocalDenied instead refuses before begin when no peer. TestPlacementSuspectBox: marker-affinity and roomiest ref excluded across hosts; next request picks survivor within 10s; no repeated dial; expiry re-admits, only success/holder-naming answer clears, none/headerless 503/502/Status 0/out-of-view remain suspect, late failure cannot poison newer success/acquire; bound declines new placement safely. TestPlacementRefusalMarksSuspect: each N-HA12 failure excludes clean-releaser/roomiest peer for 10s while its fold stays fresh; success or a holder-naming answer alone clears under epoch guards. TestPlacementRefusalKeepsObservation: after none/headerless 503, requests through original t+10s use one ingress GET total, no repeat attempt to suspect, one survivor/Base acquire GET/request (+1P if taken), no sliding expiry. TestPlacementCachesObservationNotChoice: attempt tag never pins target; fold change within 10s recomputes even after headerless success, no GET; a real holder header installs positive, expiry one GET. TestPlacementSnapshotIsLazy: zero projections for awake/waking, positive-holder and true-suspect hits; one projection after the bypass/holder checks for a cold wake. Switch-off still returns Base through DecidePlacement. TestPlacementHintIsNotAHolder covers Placement and Recovery headerless answers. TestPlacementSingleFlight: 20 misses one GET/full view, one canceled waiter cannot cancel others. TestPlacementHeldOwnerWins / TestPlacementPrefersCleanReleaser / TestPlacementChoosesRoomiest / TestPlacementNoCapacityStillWakes: ordinary holder, H4, one warning callback/region/hour, zero extra calls. TestFrontPlacementNeverFallsBack: disappeared choice/key lost after projection → 503 RA10, zero ingress begin; pass NotInView to placementPeers, next request within 10s avoids ref; no key at projection instead excludes peers and permits local HA wake. TestPlacementHopNeverRechooses: differing receiver view, no onward hop. TestAgentArmsHAPlacement checks the one agent call; TestHAPlacementPageWiring executes helper and asserts Apps, callback, accepted subject/body, warning/deadline/throttle. TestPlacementDecisionLogIsBounded: reason/ref, no visitor log flood/store calls. |
| - [ ] **Step 2: Run** `nice -n 19 go test ./internal/activator ./internal/edge ./internal/host -run 'TestPlacement|TestFrontPlacement|TestAgentActivatorForwards|TestAgentArmsHAPlacement|TestHAPlacementPageWiring' -count=1`. Expected FAIL. |
| - [ ] **Step 3: Implement** the interfaces and one applicability table. Cache/edge only carry decisions; no duplicate switch/owner/reachability policy. Cached observations never authorize AcquireHA. |
| - [ ] **Step 4: Run** Step 2 plus `nice -n 19 go test ./internal/activator ./internal/edge -run 'TestForwardTarget|TestHolderCache|TestFrontForward|TestForwardHA|TestHopped|TestScheduledTickNeverForwards|TestLegacyHop|TestTakingTheLease' -count=1`. Expected PASS; update only assertions for free wakes where placement applies, preserve off/owner/Base cases. |
| @@ -252,23 +271,26 @@ func TestColdWakeCleanEligibleReleaser(t *testing.T) { |
| **Interfaces:** Real activator.New→SplitBackend→edge.New, writer/decoder/fold/ForwardTarget. Run each logical box in its own child process: lease identity/obligation state are process globals, so two Services in one process are not a two-box authority witness. Low-level S3/EC2/dial seams inject faults; chooser/acquire/restore/launch/accounting cannot be replaced. Fake forwarders/AST-presence checks are not behavioral acceptance. The sole exception is Task 3's one-call/order syntactic check of the uncallable runAgent entry, following `internal/host/haforward_wiring_test.go:15`; the common arming function and every callback must execute in this witness. Root acceptance uses isolated designated runner, real ensureSystemUnits/guard-armed edge dependencies, never sleep-service stand-ins or sudo. Any CLI-shelling witness must use the root package's carlosTestEnv and scratch cmd.Dir; do not inherit operator credentials/config. |
| -Simulation interfaces: add `func (w *world) coldSnapshot(b *box, h string) boxchoice.WakeSnapshot` in world_test.go and `func (w *world) requestPlaced(b *box, h string, hopped bool)` in actions_test.go. Model each ingress's switch, local route versus published host membership, aged fold, typed lock observation with original deadline, ref suspicion/answer epoch, and ingress/receiver read counters. Call production DecidePlacement→ChooseColdWake then existing modeled acquire/keep; a hopped receiver skips the decision. Existing `internal/sim/regionha/invariants_test.go:10` checks I1/I2/I5; add bounded recovery assertions that require actual requests through this action. A direct finalTakeovers call must not mask a stranded placement path. |
| +Simulation interfaces: add `func (w *world) coldSnapshot(b *box, h string) boxchoice.WakeSnapshot` in world_test.go and `func (w *world) requestPlaced(b *box, h string, hopped bool)` in actions_test.go. Model each ingress's switch, local route versus published host membership, aged fold, mirrored signing key, typed lock observation with original deadline, ref suspicion/answer epoch, and ingress/receiver read counters. Import `internal/activator` to call its pure DecidePlacement→ChooseColdWake, then existing modeled acquire/keep; a hopped receiver skips the decision. Existing `internal/sim/regionha/invariants_test.go:10` checks I1/I2/I5; add bounded recovery assertions that require actual requests through this action. A direct finalTakeovers call must not mask a stranded placement path. |
| + |
| +Add model action `peerWakeFault(ref, mode)` with refuse (none/headerless 503), hang (502/Status 0), and out-of-view modes. Keep the peer alive and its published generation/headroom fresh: out-of-view removes it only from forwarding view after the decision, reproducing that race. Request the affected free host again through the survivor before 10s; I5 requires a wake there, without a repeat attempt to the suspect peer. Exercise both clean-releaser and roomiest choices and another host. The model applies outcomes to its per-box suspicion/epochs using N-HA12; only DecidePlacement owns applicability. Every protocol mutation below changes what this model hands the production pure rule, or how it applies the rule/forward answer (`internal/sim/regionha/rules_test.go:36`); no production code mutation switches or duplicate placement table. |
| | Mutation (one at a time) | Deterministic witness / invariant | |
| |---|---| |
| | placement-ignores-expired-owner | Restart expired owner with a roomier peer, direct request at owner and request via peer both recover only at owner, emptiness proof still required; then terminate that owner/fail Recovery dial and prove next survivor request takes only after confirmation. **P1-1, §9.6/I4/sim I5.** | |
| | placement-ignores-switch | Born-HA route, flag off, no capable files: request still wakes through HA; held peer still followed. **P1-2, N-HA7.** | |
| -| placement-ignores-suspect-box | Both clean-releaser and roomiest variants: fail target dial, next request before 10s goes to survivor, second host cannot redial suspect; response clears, old failure cannot re-poison. **P1-3, I4.** | |
| +| placement-ignores-suspect-box | Both clean-releaser and roomiest variants: fail target dial, next request before 10s goes to survivor, second host cannot redial suspect; success/holder-naming answer clears, old failure cannot re-poison. **P1-3, I4.** | |
| +| placement-refusal-clears-suspect | peerWakeFault keeps publication fresh while peer refuses/hangs or leaves forwarding view after selection. Mutation clears or omits suspicion on the unsuccessful answer, so the next request repeats the unusable choice rather than waking on the survivor within 10s. **N-HA12, P2-A/P2-B, I4 / sim I5.** | |
| | placement-requires-published-self-host | Route exists locally before either file lists new host; self may wake, unadopted peer cannot be selected. **P2-1, A20.** | |
| -| placement-drops-negative-on-refusal | Ingress reads free marker, store changes before receiver acquire to another unconfirmed expired owner; none/headerless 503, repeat within original 10s: one receiver GET/request and zero ingress re-reads, then one re-read at deadline. **P2-2, bounded reads.** | |
| +| placement-drops-negative-on-refusal | Ingress reads free marker, store changes before receiver acquire to another unconfirmed expired owner; none/headerless 503 marks target suspect; next request uses survivor/Base within original 10s: one acquire GET/request and zero ingress re-reads, then one re-read at deadline. **P2-2, bounded reads.** | |
| | placement-ignores-releaser / placement-ignores-room | Shared views check affinity/thresholds/spread/hash ordering against public properties. **H4.** | |
| | placement-local-fallback / placement-onward-hop | Remove chosen peer after decision; no ingress begin on that request; receiver with different view never forwards onward. **N-HA10 / one accounting owner.** | |
| **Wiring/copy mutation boundary (P2-3/4).** The protocol simulation cannot prove Go agent registration or accepted words. Use test-only integration mutations `placement-skips-arm` and `placement-drops-page-subject` in TestHAPlacementPageWiring/TestColdPlacementProductionWiring instead; each must fail alone when the production helper is omitted or its subject is lost. First compares published owned Apps and observes the capacity page; second asserts the exact accepted subject/body at the supplied sink. No duplicate simulated arming/copy implementation can substitute for that witness. |
| -- [ ] **Step 1: Write failing witnesses.** TestColdPlacementProductionWiring: real provisioned HA record, production publication/fold, non-choice request → one peer acquire/start, no ingress begin, one gate/usage/analytics/guard owner. TestColdPlacementSealedWake: real clean release with sealed trio; non-releaser request keeps local/same key/token; make releaser ineligible and repeat → real restoreFilesClean/sealed restore/stageEscrowReads, no raw publish/second mint. TestColdPlacementCompetingViews: differing choices race real conditional store → one start, retryable loser, at most one hop. TestColdPlacementExpiredOwnerRecovery: child leo acquires, crashes/restarts after expiry; sophie has more room; requests at each ingress both recover on leo after real empty proof, no sophie start while leo lives; equality/pre-expiry refuses, missing proof refuses. Separate expired terminated-owner case fails Recovery dial then takes on survivor through real confirmation, never strands behind stale file. TestColdPlacementSwitchOff: born-HA record with flag off and no capable files still wakes locally under AcquireHA; existing held peer path intact. TestColdPlacementDeadChoice: kill chosen listener with file still fresh, first request 503/zero fallback; next within 10s wakes survivor for marker and absent-lock variants, cross-host failed dials at most one/ref/10s, lease not bypassed. TestColdPlacementNewHostNoFold: real local route ahead of publication; first request serves, peers not yet advertising host excluded; repeat with stale own generation/lost index bump, no forced GET/refresh. TestColdPlacementRequestBudget: separate ingress/receiver low-level S3 counting transports, each budget row including first/repeated none/headerless 503, original deadline, absent LIST/errors/conflicts/no-op passes, true-holder versus Placement/Recovery suspicion. No production counter added to pass this test. Add TestColdPlacementRootRunner: actual nested host on selected box, failed wake/crash stop-and-prove before marker, restart one writer. Designated Linux root runner must execute; local privilege skip is not acceptance. |
| +- [ ] **Step 1: Write failing witnesses.** TestColdPlacementProductionWiring: real provisioned HA record, production publication/fold, non-choice request → one peer acquire/start, no ingress begin, one gate/usage/analytics/guard owner. TestColdPlacementSealedWake: real clean release with sealed trio; non-releaser request keeps local/same key/token; make releaser ineligible and repeat → real restoreFilesClean/sealed restore/stageEscrowReads, no raw publish/second mint. TestColdPlacementCompetingViews: differing choices race real conditional store → one start, retryable loser, at most one hop. TestColdPlacementExpiredOwnerRecovery: child leo acquires, crashes/restarts after expiry; sophie has more room; requests at each ingress both recover on leo after real empty proof, no sophie start while leo lives; equality/pre-expiry refuses, missing proof refuses. Separate expired terminated-owner case fails Recovery dial then takes on survivor through real confirmation, never strands behind stale file. TestColdPlacementSwitchOff: born-HA record with flag off and no capable files still wakes locally under AcquireHA; existing held peer path intact. TestColdPlacementDeadChoice: kill chosen listener with file still fresh, first request 503/zero fallback; next within 10s wakes survivor for marker and absent-lock variants, cross-host failed dials at most one/ref/10s, lease not bypassed. TestColdPlacementUnusableChoice: while publication stays fresh, inject none/headerless 503, hang after connection (502/Status 0), and out-of-view after projection. First request returns its existing error without fallback; next before 10s wakes on survivor, including cross-host exclusion. Repeat with no mirrored signing key at projection: free host wakes locally with no failed peer attempt. TestColdPlacementNewHostNoFold: real local route ahead of publication; first request serves, peers not yet advertising host excluded; repeat with stale own generation/lost index bump, no forced GET/refresh. TestColdPlacementRequestBudget: separate ingress/receiver low-level S3 counting transports, each budget row including initial none/headerless 503 and subsequent survivor/Base attempts, original deadline, absent LIST/errors/conflicts/no-op passes, true-holder versus Placement/Recovery suspicion. No production counter added to pass this test. Add TestColdPlacementRootRunner: actual nested host on selected box, failed wake/crash stop-and-prove before marker, restart one writer. Designated Linux root runner must execute; local privilege skip is not acceptance. |
| - [ ] **Step 2: Run** `nice -n 19 go test ./internal/host -run 'TestColdPlacement' -count=1`. Expected FAIL before integration; execute root witness on designated runner as well. |
| -- [ ] **Step 3: Extend simulation.** Implement the interfaces/mutation table above, register each protocol mutation in rules_test.go and its isolated witness in witness_test.go. Preserve I1/I2/I5; extend I5 with request-path recovery for live recovered owners and free hosts whose preferred listener fails. H4 oracle asserts ordering properties, no duplicate chooser/applicability table. Pin divergent-view CAS race. No I3-duty claim/new expected miss. |
| +- [ ] **Step 3: Extend simulation.** Implement the interfaces/mutation table above, register each protocol mutation in rules_test.go and its isolated witness in witness_test.go. Preserve I1/I2/I5; extend I5 with request-path recovery for live recovered owners and free hosts whose preferred peer fails, refuses, hangs or leaves forwarding view while its publication stays fresh. The **placement-refusal-clears-suspect** mutation must be caught by I5 alone, without finalTakeovers repairing the path. H4 oracle asserts ordering properties, no duplicate chooser/applicability table. Pin divergent-view CAS race. No I3-duty claim/new expected miss. |
| - [ ] **Step 4: Run** Step 2/root witness, then `nice -n 19 go test ./internal/sim/regionha -run 'TestWitnesses|TestSeedDeterministic' -count=1`. Once/revision build test binary in owned disk scratch; `RHASIM_PAR=1 nice -n 19 internal/sim/regionha/mutate.sh <binary> 3000`; remove scratch. Expect clean baseline/every protocol rule caught alone. Separately run `RHASIM_MUTATE=placement-skips-arm nice -n 19 go test ./internal/host -run 'TestHAPlacementPageWiring|TestColdPlacementProductionWiring' -count=1`, then the same command with `RHASIM_MUTATE=placement-drops-page-subject`. Only test fixtures read this variable for these mutations; clean baseline passes, each mutation fails its named assertion. Never add mutation switches to production code. |
| - [ ] **Step 5: Census/review.** Census below, all named witnesses, task/whole-branch reviews within budget against actual amadan-main diff. Record invariant/verdict/tip; do not claim 3b built. |
| - [ ] **Step 6: Implementation landing only.** `go build ./...`, `go vet ./...`, `make test` once; cross-build `CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build ./...`, windows/amd64 likewise; linux/arm64 with explicit binary output in owned scratch, check 64MB ceiling, remove. Commit evidence/follow-ups. Later authorized session pushes/describes implementation branch, requires exact-tip green CI before amadan squash merge, checks main CI. This drafting session runs none of those suites/pushes/merges. |
| @@ -282,7 +304,7 @@ Simulation interfaces: add `func (w *world) coldSnapshot(b *box, h string) boxch |
| - [ ] **Step 1: Release/pre-check.** README dev recipe, boxes before console; UTC log, built version and behavior. Matching non-empty bucket/key fingerprint, CARLOS_REGION_HA, fresh compatible files, born-HA nested host adopted on both in hapair, healthy startup sweep, no obligation. Read Apps from **both live edges files** (not only svc fixtures) and compare to the owned-awake hosts. Before clean reuse assert releaser fresh, compatible, at least 15% memory and 10% disk; otherwise choose another eligible setup or stop the drill. hapair-a1 only if approved. |
| - [ ] **Step 2: Clean reuse.** Wake on one box, write sentinel/timer, real idle sleep, confirm clean marker. Twenty requests through other box, TLS SNI/Host via `curl --resolve`. All from choice; first kept local; one generation advance/start; no ingress acquire/start/accounting. Record body/version/owner plus throttled placement Kind/ref/Reason/generation from ingress journal; reuse log from selected box. Exact API-call evidence is Task 4 counting-transport output for the built revision, linked in the drill report. Dev journals establish starts/acquires, not a claim to count every AWS API call. |
| - [ ] **Step 3: Capacity/spread.** Fresh never-woken born-HA host avoids affinity. Read snapshots and production decision log (offline ChooseColdWake result as cross-check), request non-choice; one chosen acquire/start. Repeat with app spread. No-eligible/missing/stale cases in local fixtures; do not exhaust dev memory/disk or withhold files without scoped approval. |
| -- [ ] **Step 4: Race/backoff.** Asleep host, simultaneous pair requests: journals/live units show one writer, no fallback/onward hop. Loser may see 503. Approved choice-listener fault → first failure within 2s/503, next request within 10s serves on survivor, no second choice in first request, no further suspect-ref dials during its 10s window. Repeat across hosts; no ingress re-read within original observation TTL. Held-owner refusal/backoff remains separate. Edge kill is not EC2 termination evidence. |
| +- [ ] **Step 4: Race/backoff.** Asleep host, simultaneous pair requests: journals/live units show one writer, no fallback/onward hop. Loser may see 503. For a free host and the approved chosen edge only, send **SIGSTOP**, leave it paused for **at least 10s**, then send **SIGCONT** in guaranteed cleanup; keep the host-agent edges publisher running and verify the file stays fresh. A rapid KILL/restart is not this fault. Paused listener → bounded failure (dial failure within 2s/503, or connected hang with existing 502/Status 0), next request within 10s of that failure serves on survivor, no second choice in first request, no further suspect-ref dials during its 10s window. Repeat across hosts; no ingress re-read within original observation TTL. Held-owner refusal/backoff remains separate. Edge kill is not EC2 termination evidence. |
| - [ ] **Step 5: Report/clean.** Timelines/counts/binaries/pass-fail to implementation branch and #421 through controller. Remove approved temporary hosts/artifacts/faults; no leftover process. Retained hosts asleep/clean. Pass before claiming switch-on; no flagship roll. |
| **5B: 3b outline.** After executable plan/trigger exist, scoped approval for disposable third hapair box or explicit pair-member removal. IE pair observes; never infer permission to terminate sophie/leo. Departing box holds one host and released another, synced once-timer/next_due, standalone sidecar included. Terminate EC2 or real P3 drain. **No visitor requests.** Record trigger/evidence/import/adopted mark/delivery/deletion. Kill scanner after one import; repeat on another survivor. Pass: every durable duty delivered, only unsynced final ~1s lost, no pre-expiry take/early delete, H7 duplicate tick only. Restore pair/remove disposable resources under approval. Visitor restore alone does not pass. |
| @@ -316,7 +338,7 @@ Draft only. No Luna invocation or approval in this session. Inventory destinatio |
| | ID | Slice / destination | Draft text | Context / constraints | |
| |---|---|---|---| |
| | HA3-C1 | 3a front refusal, `internal/edge/forwardha.go:147` | This instance cannot wake right now. Please try again shortly. | 503 RA10 only for explicitly prohibited local service with no usable permitted route. Missing placement snapshot/read falls Base; no box/account leakage. | |
| -| HA3-C2-body | 3a operator-page body, new `internal/host/haplacement.go` | No box in region %s has enough spare capacity. Instance %s is waking on %s. Add capacity to this region. | Host still wakes; once/region/hour, preserve three placeholders. | |
| +| HA3-C2-body | 3a operator-page body, new `internal/host/haplacement.go` | No box in region %s has enough spare capacity. Instance %s is waking on %s. Add capacity to this region. | Host still wakes; once/region/hour/process (accepted §20 deviation), preserve three placeholders. | |
| | HA3-C2-subject | 3a operator-page subject, new `internal/host/haplacement.go` | Region %s needs more capacity | Paired with C2-body in PageOperator, warning level; preserve region placeholder. | |
| | HA3-C3 | 3b scan-failure operator notice | Duties from box %s have not been recovered. The scan will retry. Check the box's wake state before removing its records. | Incomplete scan/no deletion; actionable cause appended separately. | |
| | HA3-C4 | 3b completion notice | Recovered duties for %d instances from box %s. | Durable import/completion only; count hosts including sidecars. | |
| @@ -332,10 +354,11 @@ Run `make census-card`; tab-separated CLAIMS per changed unit (new read or none) |
| ## Open decisions and follow-ups |
| - **Paul, before implementation landing:** schedule/approve dev-only 3a drill scope. Recommend next dev release after 3a; flagship activation unchanged. |
| +- **Accepted §20 deviation (round 2 P3-4):** process-local capacity-page throttling can yield N pages/region/hour for N boxes. Region-wide deduplication remains a follow-up; no review reopening. |
| - **Settled N-HA11:** 3b uses existing termination SQS consumer plus lost-event view-age fallback. Complete its separate executable plan after 3a merges; no further trigger choice requested. |
| - Drain acceptance waits for P3's merged drained producer; no mocked flag to hide dependency or early G1/G3 claim. |
| - §6.5 retry, regional/cross-region non-holder handling, storage fencing (#501), existing-host migration (#502), roles/latch/hook/hairpin and G5 replacement stay separate. |
| ## Self-review record |
| -§6.3/§11 → Tasks 1–3; I1/I2/front accounting → Task 4; visible drill → 5A. §7/I3/removal drill → explicitly deferred 3b/5B. §18 counts new paths/passes/mutations/fan-out. §19 has first visible result/release gate. §21 has production witnesses/mutations. Every Review Focus item and round-1 P1/P2 has an owning witness; protocol mutations exercise the common applicability rule, wiring/copy mutations run at the real helper boundary. Citation/file-path and diff checks only in this revision; no tests, drills, reviewer dispatch, production edits or push. Rev 2 does not claim READY. |
| +§6.3/§11 → Tasks 1–3; I1/I2/front accounting → Task 4; visible drill → 5A. §7/I3/removal drill → explicitly deferred 3b/5B. §18 counts new paths/passes/mutations/fan-out. §19 has first visible result/release gate. §21 has production witnesses/mutations. Every Review Focus item and round-1/2 P1/P2 has an owning witness; N-HA12 is enforced only in placementPeers, with signing-key projection and refusal/hang/out-of-view I5 witnesses; protocol mutations exercise the common applicability rule, wiring/copy mutations run at the real helper boundary. Citation/file-path and diff checks only in this revision; no tests, drills, reviewer dispatch, production edits or push. Rev 3 is final: Opus round 2 READY AFTER FIXES, P2-A/P2-B closed by Paul's N-HA12, review closed. No further round. |