docs: plan region HA P1b-3 placement and duty recovery
Split the first visible cold-wake placement slice from duty ownership and departure scans. Pin current forwarding interfaces, safe refusals, S3 budgets, production witnesses, census requirements and dev drills.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+278
−0
docs/superpowers/plans/2026-11-01-region-ha-p1b3-placement.md+278 −0
Intent
Human
Presumably this ha stuff will also allow us to do zero-downtime platform updates?
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| new file mode 100644 |
| index 000000000..225d2689b |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-01-region-ha-p1b3-placement.md |
| @@ -0,0 +1,278 @@ |
| +# Region HA P1b-3: cold-wake placement Implementation Plan |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. This commission is planning only; do not start implementation or dispatch reviewers from this session. |
| + |
| +**Goal:** A request for an asleep born-HA host that reaches the other box wakes the host on the chosen box through the existing signed forward, with one writer and one owner of request accounting. |
| + |
| +**Architecture:** P1b-3a adds app counts to existing edges publication and passes a cached placement snapshot into the activator's front-door decision. An eligible clean releaser wins; otherwise the shared roomiest policy chooses. The receiving peer runs the existing HA acquire/restore. P1b-3b covers local duty ownership and departure scan/import; its outline below is not executable. |
| + |
| +**Tech Stack:** Go 1.26, `internal/{boxchoice,edge,activator}`, S3 conditional leases, local SQLite registries, seeded `internal/sim/regionha`. |
| + |
| +**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:** Draft, unreviewed. No production code or deployment authorized. Planning branch committed locally only. |
| + |
| +## Rulings |
| + |
| +- **N-HA8, Paul, 2026-10-29:** §6.3 placement and §7 duties belong to P1b-3. §6.5 retry is later. Roles, serving latch, lifecycle hook and hairpin belong to P3. |
| +- **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. |
| +- **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. |
| +- **Budget:** No new per-box S3 poll, request-time membership read, claim roster or duty file. Ride existing edges publication/fold and #336 change index. |
| + |
| +## Scope and finish lines |
| + |
| +**Build P1b-3a first.** It changes a visible visitor request without changing timer ownership, registry import, EC2 evidence processing or edges deletion. Combining these puts forwarding, a cache, several duty entry points and production-storage import in one review. Drain completion also needs P3's unbuilt producer; stopping rule 4 forbids review against that unmerged interface. |
| + |
| +| Requirement | P1b-3a executable tasks | P1b-3b outline | |
| +|---|---|---| |
| +| §6.3 reuse/capacity choice; §11 app counts and missing-input answers | Tasks 1–3 | | |
| +| One writer/hop/accounting owner | Task 4 | | |
| +| §7 duties in local registries, no transfer files | Existing behavior retained | Gate ticks/due wakes/workers/run picking | |
| +| §7.4 departed-box scan/import | No scan/deletion | One adoption function, resumable scan, departure trigger | |
| +| Dev non-chosen-box request | Task 5A | | |
| +| Dev removal/import without visitor traffic | Not a 3a acceptance claim | Task 5B | |
| +| §6.5 retry; roles/latch/hook/hairpin | Deferred | Named later slices | |
| + |
| +Switch-on: first dev release immediately after 3a merges, fixed sophie/leo in `hapair`, subject to Task 5 approval. If release cannot be scheduled, keep implementation on branch; no dormant merge without date. Planning commit needs no switch-on. 3a alone completes neither G1 nor G2/G3. |
| + |
| +## Round history |
| + |
| +| Round | Brief / findings | Verdict | Fault families / disposition | |
| +|---|---|---|---| |
| + |
| +No P1b-3 review has run. 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 |
| + |
| +- Born-HA only (`rt.HA`). Legacy hosts, regional names, door calls, tunnel deliveries, static routes and verified hops retain P1b-2 behavior. |
| +- Existing switches: `CARLOS_REGION_HA` box capability, `CONSOLE_HA_REGIONS` new-record stamp. No new flag/migration. HA never falls back to legacy acquire. |
| +- Eligibility: **15% memory**, **10% disk**, generation at most **15 minutes** old and **1 minute** in future. Publication **5–6 minutes**, fold **30 seconds**. Missing/stale app counts mean **0**, soft spread (astra-3.5). |
| +- A20: low headroom never refuses an existing host if a compatible fresh serving box exists. Missing membership/configuration may refuse. |
| +- Fixed-pair staging until P3 admission. Honor explicit non-serving roles; create no role objects/hooks and claim no ASG admission here. |
| +- Additive wire fields; old files decode. No lock shape, registry schema, IAM, SQS consumer, root lifecycle or infrastructure change in 3a. |
| +- Durability 3a is base: sealed secrets, original binding, write-once escrow and `stageEscrowReads` stay on ordinary selected-box wake/publish path. |
| +- Preserve 50,000-host cache bound, positive ceiling **1h**, negative observation **10s**, suspect **10s**, **2s** read/dial bounds, generations and per-address dial gate. |
| +- Copy rows are draft controller→Luna deck. Apply accepted words verbatim at execution; no dispatch/approval claimed here. |
| +- Targeted tests `nice -n 19`/`-run`/`-count=1`, default `GOCACHE`. Owned scratch under `$TMPDIR` or `~/.cache/region-ha-p1b3`, removed; listeners loopback. |
| +- Implementation landing: repo build/vet/test/format once; darwin/amd64, windows/amd64, linux/arm64 cross-compiles, `CGO_ENABLED=0`; arm64 binary under **64,000,000 bytes**. No full suites for this planning commit. |
| + |
| +## Current code and file map |
| + |
| +| Base seam | Responsibility/change | |
| +|---|---| |
| +| `internal/boxchoice/policy.go:16,63,83` | New `coldwake.go` composes thresholds/ChooseRoomiest. Claim-era Eligible (`boxchoice.go:120`) requires roster: do not use. | |
| +| `internal/host/headroom.go:14`; `edgesfile.go:173,228,1230` | Add headroom.apps from live activator entries. Hibernate is policy (`registry/registry.go:229`); awakeCount is not new producer. | |
| +| `internal/host/edgesfile.go:945,962` | Headroom outside gate; existing HA timed writes refresh generation even if readings unchanged. No heartbeat. | |
| +| `internal/edgesfile/snapshot.go:72,280`; `boxchoice/boxchoice.go:29` | Carry additive map through shared decoder/converter. | |
| +| `internal/edge/homemap.go:134,456`; `holderview.go:35` | New wakeplacement.go projects one cached fold. Holder view deliberately ignores age; cold placement ages separately. | |
| +| `internal/edge/forwardha.go:41,173,210` | Extend real interface; disappearing placement target refuses instead of local fallback. | |
| +| `internal/activator/haforward.go:73,104`; `hacache.go:217,271` | Preserve SplitBackend dispatch; retain negative observation; distinguish preference from holder. | |
| +| `internal/activator/activator.go:3211`; `host/agent.go:576,746,1048` | Counts use HoldsAwake predicate; register source in real Service construction. | |
| +| `internal/lease/ha.go:35,169`; `hafresh/acquire.go:72` | Existing authority/read path unchanged. Absent acquire also costs LIST (`ha.go:100`). | |
| +| `internal/activator/hawake.go:413,657,730`; `hafiles.go:192`; `escrow.go:852` | Real acquire→keep/restore→sealed publication; witnesses reach these paths. | |
| + |
| +## Placement contract and failure answers |
| + |
| +**H4, enforced only in ChooseColdWake.** Host, account/app key, optional clean releaser, WakeSnapshot. No choice without self evidence/serving set. Prefer clean releaser in `Placeable(Serving,nil,now)`. Otherwise ChooseRoomiest on eligible set with app loads. None eligible: choose all serving with no spread map (most memory then HRW), return OverCapacity. Missing headroom contributes zero to last resort, never guessed totals. |
| + |
| +**§4.3 scope, enforced only in edge wakeSnapshot.** One immutable homeSnapshot: require own/candidate files, same AWS region/placement, same non-empty data bucket, matching non-empty secrets fingerprint (sealed HA needs key), dialable address, explicit hibernation_configured:true, region-ha-1, fresh generation. Candidate publishes primary role:home for **rt.Host**, matching account/app; alias/wildcard/cert-only/replica cannot qualify. This proves adoption of this pool's host; requiring ServesSharedPool would wrongly exclude leo from hapair. Reject draining:true, drained:true, explicit role other than serve; absent means serve (§4.4). No per-request identity/status read; P1b-2 deployment-store trust remains. |
| + |
| +**Budget/H4, publisher/projection.** Counts keyed `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 source omits map. Never claims, all registry rows or published host lists. Negative counts become zero. Default counts cannot make stale membership usable. |
| + |
| +**I1/I2, existing acquire/keep.** Unexpired other holder outranks placement; same-box owner retains local acquire/refusal. Only V==1, Clean, non-empty Box marker offers releaser preference; no copy guarantee. Absent lock, unclean marker or expired owner routes H4; receiver still needs all acquire proofs. Read-error/malformed lock is not free: refuse. Verified hop never rechooses/forwards; receiver acquires or returns P1b-2 diagnostic. |
| + |
| +**N-HA10/bounded forwarding, frontForwardHA.** Selected peer gone/no mesh key/dial failure: existing 503 Retry-After:10, no ingress wake/second choice. Ordinary holder ForwardNotInView unchanged. Awake/waking here bypasses placement. Missing snapshot/choice/read result uses C1 with same status/retry. |
| + |
| +**“One box” under races.** Equal snapshots yield equal preference. Different cached folds can choose differently; §6.7 allows conditional-acquire race, one winner/start. No consensus placement record. Test divergence; do not promise identical global preference during membership changes. Without §6.5 retry a loser can return retryable 503. |
| + |
| +## 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. |
| + |
| +| Path/pass | Placement + lease attempts, no conflict | |
| +|---|---| |
| +| Legacy; awake/waking here; positive holder hit | 0 new calls | |
| +| Held-peer miss | 1G lock; no ingress acquire | |
| +| Cold observation miss, choice local | 1G front + 1G+1P acquire = **2G+1P**, plus R | |
| +| Cold forwarded observation miss | 1G ingress + 1G+1P chosen peer = **2G+1P**, plus R; verified receiver skips front | |
| +| Cold cached 10s observation | **1G+1P** target acquire, plus R | |
| +| First absent-lock wake | Above **+1L** prefix-empty proof, then existing baseline/secret publication | |
| +| No fresh compatible serving box | 0 if observation cached, else 1G; 0P/0L; 503 | |
| +| Probe error/malformed | 1 attempted G, 0P/0L; 503, never cached “free” | |
| +| Choice gone/no mesh key/unreachable | Probe as above; no ingress acquire; dial costs 0 S3 | |
| +| Holder or placement suspect window | **0 S3**, 0 dials for 10s | |
| +| Refused target acquire | 1G, 0P; expired other owner 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 | |
| +| Existing timed HA publication | Existing replacement 1G+1P + index 1G+1P = **2G+2P**; increment 0 | |
| +| Existing full fold, B keys | `ceil(B/1000)L+B*G`; increment 0 | |
| + |
| +Acquire CAS conflicts: at most 3 rounds (`lease/ha.go:48`), `gG+pP+lL`, 1<=g<=3, 0<=p<=g, 0<=l<=g (LIST only absent round). Add ingress probe. Pending marker obligation may add PUT before reads (`ha.go:82`). Renewals/release retries unchanged. |
| + |
| +Edges replacement at most 3 attempts (`host/snapshot_loop.go:221`); index **4 total attempts** (`release/changeindex.go:31,130`), despite §18 “up to 4 retries.” For a replacements, k index attempts after success: (a+k)G+(a+k)P, a<=3,k<=4, max 7G+7P. Failed replacement has no bump. Do not turn 4 attempts into 5. |
| + |
| +Quiet: **0 incremental S3 requests/box/pass and /day**. §18 baseline about 3,300–3,500/hour (79,200–84,000/day) stays, not new allowance. Existing HA writer makes 10–12 timed publications/hour. Additive fields cause one rollout rewrite, not per-app/count-change writes. Coalesced fold fan-out stays `120*(ceil(B/1000)+B)`/hour/box. Count no-op passes in tests. |
| + |
| +## Review Focus |
| + |
| +1. Wrong pool despite room: Task 2 TestWakeSnapshotRequiresThePrimaryHost. |
| +2. Partial/old folds, absent counts/headroom, future time: Tasks 1–2 TestColdWakeMissingInputs/TestWakeSnapshotFreshness. |
| +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. |
| + |
| +--- |
| + |
| +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. |
| + |
| +### Task 1: Live app counts and pure cold-wake choice |
| + |
| +**Files:** Create `internal/activator/awakeapps.go`, `internal/activator/awakeapps_test.go`, `internal/boxchoice/coldwake.go`, `internal/boxchoice/coldwake_test.go`, `internal/host/haawake_source.go`. Modify `internal/host/headroom.go:14`, `internal/host/edgesfile.go:173` and `:1230`, `internal/host/agent.go:576`, `internal/edgesfile/snapshot.go:72` and `:280`, `internal/boxchoice/boxchoice.go:29`. Test `internal/host/headroom_test.go`, `internal/edgesfile/snapshot_headroom_test.go`. |
| + |
| +**Interfaces:** |
| +- `func (a *Service) AwakeApps() map[string]int`: fresh map under a.mu, count `ownedLocked(e,false)==nil`, valid account/app only. No store/registry call. |
| +- Add `Apps map[string]int`, JSON tag `apps,omitempty`, to edgeHeadroom/boxchoice.Headroom and shared edgesfile.PlacementView.Headroom; deep-copy through Snapshot.BoxChoice. |
| +- `func setHAAwakeApps(fn func() map[string]int)` / `func haAwakeApps() map[string]int`: atomic callback in haawake_source.go, nil yields nil. Register Service method before edges-loop start; headroomFor attaches snapshot. Tests restore source. Keep existing Awake field meaning. |
| +- `type WakeSnapshot struct { Self string; Region string; Serving []Candidate; Running map[string]Load }`; `type ColdChoice struct { Ref string; OverCapacity bool }`. |
| +- `func ChooseColdWake(host, app, cleanReleaser string, s WakeSnapshot, now time.Time) (ColdChoice, bool)`: contract above; empty Self invalid. Ref is published box reference, not EC2 iid/claim id. |
| + |
| +- [ ] **Step 1: Write failing tests.** TestAwakeAppsUsesOwnedEntries: two owned acct/shop hosts count 2; another account's shop 1; no alias/co-spawn duplication; waking/stopping/fenced/lease-lost/shutdown 0; returned map cannot alter service. TestColdWakeCleanEligibleReleaser: eligible releaser wins; below 15% memory/10% disk falls to H4. TestColdWakeRoomiestAndSpread: app-free, memory, exact existing HRW hash; reverse input order identical. TestColdWakeMissingInputs: no serving false; absent map zero spread; none eligible → roomiest + OverCapacity; nil headroom-derived zeros alone never refuse. TestAwakeAppsRideTimedPublication: changed Apps on ordinary pass zero calls, timed pass one replacement. TestBoxChoiceCarriesAwakeApps: old JSON decodes; new map survives conversion/copy. |
| + |
| + Pin the public policy with literal cases (the rest of Step 1 adds ownership/publication fixtures): |
| + |
| +```go |
| +func TestColdWakeCleanEligibleReleaser(t *testing.T) { |
| + now := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC) |
| + c := func(ref string, free int64) Candidate { |
| + return Candidate{BoxID: ref, MemTotalMiB: 1000, MemFreeMiB: free, |
| + DiskTotalMiB: 1000, DiskFreeMiB: 100, |
| + Generation: now.Format(time.RFC3339)} |
| + } |
| + s := WakeSnapshot{Self: "a", Region: "eu-west-1", |
| + Serving: []Candidate{c("a", 150), c("b", 800)}} |
| + got, ok := ChooseColdWake("h.example", "acct/shop", "a", s, now) |
| + if !ok || got.Ref != "a" || got.OverCapacity { t.Fatalf("%+v %v", got, ok) } |
| + s.Serving[0].MemFreeMiB = 149 |
| + got, ok = ChooseColdWake("h.example", "acct/shop", "a", s, now) |
| + if !ok || got.Ref != "b" { t.Fatalf("%+v %v", got, ok) } |
| +} |
| +``` |
| + |
| +- [ ] **Step 2: Run** `nice -n 19 go test ./internal/activator ./internal/boxchoice ./internal/host ./internal/edgesfile -run 'TestAwakeApps|TestColdWake|TestBoxChoiceCarriesAwakeApps' -count=1`. Expected FAIL. |
| +- [ ] **Step 3: Implement** interfaces using Placeable/ChooseRoomiest, no duplicate thresholds/sort. Preserve timed generation and headroom-excluded gate; update exact-wire fixture only for present additive field. |
| +- [ ] **Step 4: Run** Step 2 plus `nice -n 19 go test ./internal/host ./internal/edgesfile ./internal/boxchoice -run 'Headroom|EdgesFileSchedule|Roomiest|Placeable' -count=1`. Expected PASS. |
| +- [ ] **Step 5: Commit** `region-ha p1b-3a: publish awake app counts and define cold choice`. |
| + |
| +### Task 2: Project a host's snapshot from cached fold [own review] |
| + |
| +**Files:** Create `internal/edge/wakeplacement.go`, `internal/edge/wakeplacement_test.go`. Modify `internal/edge/homemap.go:134` and `:169` decoders; leave holderview.go age-independent. |
| + |
| +**Interfaces:** |
| +- `func (m *homeMap) wakeSnapshot(rt registry.Route, now time.Time) boxchoice.WakeSnapshot`: one snapshot read, copied slices/maps, canonical rt.Host/account. |
| +- edgesFileView gains Generation, Capabilities, HibernationConfigured *bool, Draining, Role, Drained, Headroom *boxchoice.Headroom; edgesHostView gains Replica bool. Existing writer JSON names plus future additive role/drained. Include self without boxInView's self-exclusion. |
| + |
| +- [ ] **Step 1: Write failing tests.** TestWakeSnapshotCompatibility: require matching store/key/region/placement, capability/config/dial. TestWakeSnapshotRequiresThePrimaryHost: leo shared-pool false + hapair host in; no primary, alias/cert/wildcard/replica or account/app mismatch out. TestWakeSnapshotFreshness: age 15m in, 15m+1ns out; future 1m in, +1ns out; absent/bad generation out; absent/stale self invalid; drain/platform/booting/unknown role, Draining/Drained out. TestWakeSnapshotHeadroomAndApps: missing headroom serving but ineligible, missing/negative count zero, refs key candidates/loads. TestWakeSnapshotNoIO: 100 projections zero calls, no held-fold mutation. Old holder JSON still decodes. |
| +- [ ] **Step 2: Run** `nice -n 19 go test ./internal/edge -run 'TestWakeSnapshot' -count=1`. Expected FAIL. |
| +- [ ] **Step 3: Implement** projection/decoders. Carried-forward files age by original generation. No roster/read/refresh-on-request/global holder-view change. |
| +- [ ] **Step 4: Run** Step 2 plus `nice -n 19 go test ./internal/edge -run 'TestHolderView|TestForwardHANotInView|TestHome' -count=1`. Expected PASS. |
| +- [ ] **Step 5: Commit** `region-ha p1b-3a: derive cold placement from cached fold`. |
| + |
| +### Task 3: Use choice at front without local fallback [own review] |
| + |
| +**Files:** Create `internal/activator/haplacement.go`, `internal/activator/haplacement_test.go`. Create `internal/host/haplacement.go`; modify `internal/host/agent.go:576`. Modify `internal/edge/forwardha.go:41` and `:173`, `internal/activator/haforward.go:104`, `internal/activator/hacache.go`, their tests, `internal/host/haforward_wiring_test.go`; create `internal/host/haplacement_wiring_test.go` here for the page test, extended in Task 4. |
| + |
| +**Interfaces:** |
| +- Replace interface method with `ForwardTarget(ctx context.Context, rt registry.Route, s boxchoice.WakeSnapshot) edge.ForwardDecision`. Update all callers/doubles (`rg 'ForwardTarget'`). Edge passes wakeSnapshot, zero if homes nil; zero cannot disable asleep-HA placement. |
| +- ForwardDecision/ForwardResult gain `Placement bool`, copied through result. ForwardDecision gains `Unavailable bool` for absent snapshot/choice/read result (C1). Existing Refuse means suspect/dial-failure answer. Check Unavailable before Refuse in frontForwardHA; both stop before accounting. |
| +- Replace private cache tuples with `type holderResolution struct { Ref string; Refuse bool; Gen uint64; View *hafresh.View }` and `type holderRead struct { Ref string; View *hafresh.View; Err error }`. `func (c *holderCache) resolve(ctx context.Context, host string, read func() holderRead) holderResolution` retains immutable decoded negative view for original 10s. Positive lifetime unchanged. Error/cancel/timeout returns no usable View (Unavailable/C1); Refuse is reserved for an actual suspect entry, never inferred from an ordinary read failure. Preserve detached bounded single-flight read. |
| +- `func (c *holderCache) placement(host, ref string) uint64`: preference/token alongside observation, never extend observation expiry. Same choice reuses token; new choice advances it. Dial failure marks peer suspect 10s. Expired placement suspect with free read clears/rechooses; failed read keeps suspicion. All states share 50,000-host bound. |
| +- NoteForward never promotes placement 200 without holder header to 1h holder. Platform holder header may set positive. None/headerless 503 drops observation. Old failure cannot poison newer choice/acquire; generations/dial gate preserved. |
| +- Add `Service.OnHAOverCapacity func(region, host, ref string)`, installed before Start by `func wireHAPlacement(svc *activator.Service, page func(context.Context, string, string, string) error)` in `internal/host/haplacement.go`. Use snapshot.Region from own file; Service throttles one observation/region/hour/process, host helper sends accepted C2 as subject/body at alerting.LevelWarning on a detached 5s-bounded goroutine via PageOperator (`internal/host/alertsink.go:137`), never blocks a request or reads S3. No new unreviewed subject string. Multiple ingress processes can report the same condition; a deployment-wide deduplication guarantee is outside this slice. |
| +- ForwardTarget order: non-HA/unmanaged/live entry local; positive holder/suspect as today; unexpired self owner local acquire/refusal; missing View unavailable; otherwise ChooseColdWake. No choice unavailable, self local, peer {Ref,Placement:true,Gen}. OverCapacity pages C2 through existing operator path, once/region/hour, zero S3. |
| + |
| +- [ ] **Step 1: Write failing tests.** TestPlacementPrefersCleanReleaser, TestPlacementChoosesRoomiest, TestPlacementNoCapacityStillWakes (one callback/region/hour and no store calls), TestPlacementNoSnapshotRefuses, TestPlacementProbeFailureRefuses assert decisions/API counts/C1. TestPlacementCachesObservationNotChoice: changed fold within 10s recomputes with no GET, expiry one GET. TestPlacementHintIsNotAHolder: bare 200 never hour entry. TestPlacementSingleFlight: 20 misses one GET/full marker to all; one cancellation cannot cancel others. TestPlacementSuspectGeneration: 10s zero calls/dials, expiry re-probes, late failure cannot poison newer choice/acquire. TestPlacementHeldOwnerWins: no capacity/releaser override; self refusal unchanged. TestFrontPlacementNeverFallsBack: choice gone/no mesh key → 503 RA10, zero ingress begins; holder behavior unchanged. TestPlacementHopNeverRechooses: receiver differing view never onward-forwards. TestHAPlacementPageWiring: real helper reaches supplied page sink with accepted C2, warning level and 5s deadline; repeated Service observations throttle. |
| +- [ ] **Step 2: Run** `nice -n 19 go test ./internal/activator ./internal/edge ./internal/host -run 'TestPlacement|TestFrontPlacement|TestAgentActivatorForwards|TestHAPlacementPageWiring' -count=1`. Expected FAIL. |
| +- [ ] **Step 3: Implement** interfaces/cache, one pure chooser/projection. Cached view never authorizes AcquireHA take. Preserve front-door ordering. |
| +- [ ] **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 old free-lock-always-local assertions. Run TestHAPlacementPageWiring with `nice -n 19 go test ./internal/host -run TestHAPlacementPageWiring -count=1`. |
| +- [ ] **Step 5: Commit** `region-ha p1b-3a: route cold wakes through front-door choice`. |
| + |
| +### Task 4: Production witnesses, simulation and landing gate |
| + |
| +**Files:** Extend `internal/host/haplacement_wiring_test.go`; create `internal/host/haplacement_root_linux_test.go`. Share production fixtures from `internal/host/plan14_lifecycle_root_linux_test.go` as needed. Modify `internal/sim/regionha/world_test.go`, `actions_test.go`, `invariants_test.go`, `rules_test.go`, `witness_test.go`, `sim_test.go`. Census artifacts generated during execution. |
| + |
| +**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 acceptance. 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. This request action distinguishes a forwarded receiver from the initial ingress; existing acquire/keep actions remain the authority model. |
| + |
| +- [ ] **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. TestColdPlacementRequestBudget: count every budget row, absent LIST/errors/conflicts/no-op passes/suspect. 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.** Independent aged ingress views call production ChooseColdWake then existing modeled acquire. Shared-view H4/one-hop oracles; preserve I1/I2/I5. Mutations placement-ignores-releaser, placement-ignores-room, placement-local-fallback, placement-onward-hop each caught alone by deterministic witness. H4 oracle asserts ordering properties, no duplicate chooser. Remove choice after decision to witness no fallback; 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 rule caught alone. |
| +- [ ] **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. |
| + |
| +### Task 5: Dev drill and visible acceptance |
| + |
| +**Scoped go required before dev mutation.** Prepare approval card: actual dev account id from private deployment root, eu-west-1, sophie/leo/hapair, exact fresh host/account/app/domain/prefixes, dev-only release/roll/restarts and temporary app/timer writes, permissions/traffic, expected incremental cost, maximum duration, cleanup/rollback/verification. No guessed ids. No new IAM/DNS/ASG needed for 3a. Destructive 3b needs expanded resource scope; nothing here authorizes removing sophie/leo. |
| + |
| +**5A: 3a, modeled on P1b-2 Task 5.** |
| + |
| +- [ ] **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. Check live app counts. 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/API counts. |
| +- [ ] **Step 3: Capacity/spread.** Fresh never-woken born-HA host avoids affinity. Read snapshots/compute production choice, 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-dial fault → failure within 2s, 10s suspect without GET/dial storm. 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. |
| + |
| +## P1b-3b outline: local duties and departure scan/import |
| + |
| +Required to finish §7, not ready to execute/review until 3a merges; drain acceptance also needs P3's producer on main. Write a separate executable plan with exact tests/steps. No duty files or published awake sets. |
| + |
| +**Trigger (I3/I4).** Request-driven P1b-1 alone cannot discover an asleep host's duties without traffic. Minimum no-SQS option: inspect cached generation ages on existing 30s home-map tick, even when index skips read (`homemap.go:392,1185`); crossing 15m schedules confirmation. Successful request-driven confirmation enqueues same work. Zero S3 polling, but only §9.8 lost-event/view-age fallback: up to 15m+30s from last publication, then remaining expiry/restore/delivery. Missing file/dial failure is suspicion, never evidence. Persist local pending departure before dropping discovery evidence. |
| + |
| +**Recommendation: minimal SQS consumer in 3b** for normal §9.8 event-driven recovery. Existing 20s long-poll permission, `termfence.FromEvent` (`fence.go:117`), cached `Confirmer.Terminated`, enqueue scan, acknowledge after completion; retain age fallback for lost events. **180 SQS receives/hour/box, zero new S3 polls**, no heartbeat object. Request confirmation also enqueues. Paul may choose slower no-SQS contract; do not advertise prompt unattended recovery if consumer is cut. Drain trigger is P3's merged drained:true. |
| + |
| +| Proposed task / production seams | Invariant, interface and acceptance needed | |
| +|---|---| |
| +| B1 new `internal/activator/haduties.go`; `internal/schedule/runner.go`, `converge.go`; `internal/host/schedule_wiring.go`, `runexec.go`; `internal/activator/activator.go:5615` and `:5642`; worker boot in agent | **I3, one duty gate.** Awake holder, sleeping releaser/adopter, never-woken HRW starter. Gate before token prep/ticks/due/boot/sweep/run picking. Non-owner advances ticks only after 15m; younger remain deliverable. Acquire before authority; live-peer result drops duty/suppresses probes until view/evidence changes. No HTTP forwarding of ticks. Co-spawn stays holder; WebSockets use hop, static/housekeeper unchanged. | |
| +| B2 new `internal/activator/haadopt.go`; `internal/hostfiles/wake.go:84` and `:134`; registry transaction/adopted mark | **I3, one adoptHost(ctx,route,departure).** Manifest+WakeItem only, never DB/tree/secrets restore. Missing referenced object/corruption keeps incomplete; no wake entry means no durable wake state. ImportWake replaces in 3 non-atomic writes: combine timers/next_due/replication/adopted mark transactionally. Serialize wake/registration/delivery; stale retry must not overwrite newly acquired host/advanced timer. Pin lifetime/departure identity/checkpoints. Held terminated-owner import must not grant delivery before expiry (N-HA9). | |
| +| B3 new `internal/host/hadepartures.go`; `internal/termfence/confirm.go:112`; cached fold tick; existing queue IAM | **I1/I3, evidence before scan.** Bind iid to verified deployment box record, same account/region; event alone insufficient. Cache immutable record (one GET/new ref), no claim enrollment. HRW over departed ref selects survivor; duplicate scans on different views tolerated. Durable local pending/retries on existing passes. Out-of-pool host needs eligible adopter; never call skipped host completed. | |
| +| B4 same departure file, conditional edges deletion/index | **I3, scan before deletion.** Existing region-HA records include asleep/sidecar, not only public edges. One lock GET/host/attempt, match parsed owner **or marker releaser**, validate iid/lifetime, one adoption function. Complete after all classified and every match imported/safely superseded. Persist progress. Scanner death retries elsewhere. Delete only same departed identity/ETag after completion, then index/cancel backoff/ack. Drain scan repeats while drained evidence remains. | |
| +| B5 simulation, production multi-box/root witness, 5B | **I3/sim I6.** Model durable wake state/timers; current `internal/sim/regionha/invariants_test.go:9` checks I1/I2/I5, not I6. Mutations skip scan, owners-not-releasers, delete early, partial-scanner death. Death before first sync loses only unsynced timer; replay cannot erase delivered/advanced timer. Fixture-only acceptance insufficient. | |
| + |
| +**3b per-attempt S3 budget:** N region hosts, A matches, W<=A manifests with wake state: **(N+A+W)G, 0L/0P**. Host list from existing reconciliation, no LIST. Identity at most one GET/uncached ref. Pending/progress/adopted marks local, zero S3. Termination completion adds **1D + kG+kP** index, 1<=k<=4; retain ETag from existing fold read (currently discarded), otherwise +1G refresh. Drain scan itself does not delete serving file/change role; P3 owns completion. SQS ack is not S3. CAS conflict incomplete, never unconditional delete. |
| + |
| +Partial retry costs remaining hosts or worst full formula; duplicate scanner a second formula. N=500,A=W=20 → **540 GETs**, about **$0.000216** at §18 prices, plus evidence/deletion/index. Event workload, never N GETs/box/30s. Quiet pass/no pending departure: **0 new S3 calls**. Evidence false/error cached 10s; retry with bounded backoff on existing passes, not visitor-rate describes. Ordinary duty acquire adds existing 1G (+1P if taken); duplicate live-holder encounter 1G, then suppress. Counter tests cover idle/partial/duplicate/import/delete failure. B2 reads no sealed trio. |
| + |
| +## Copy deck for controller → Luna |
| + |
| +Draft only. No Luna invocation or approval in this session. Inventory destinations before applying; no global replacement of shared text. JSON names/tests/wrapped diagnostics excluded. Existing “instance is waking elsewhere; retry shortly” reused unchanged for unavailable peers. |
| + |
| +| ID | Slice / destination | Draft text | Context / constraints | |
| +|---|---|---|---| |
| +| HA3-C1 | 3a front refusal, `internal/edge/wakeplacement.go` | This instance cannot wake right now. Please try again shortly. | 503 RA10 for absent compatible snapshot/choice or unreadable probe; not low headroom. No box/account leakage. | |
| +| HA3-C2 | 3a operator-page call, `internal/activator/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-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. | |
| + |
| +Controller supplies accepted C1/C2 before writing product destinations; C3/C4 wait for 3b plan. Implementation-plan prose uses writing-pipeline's explicit plan exception. |
| + |
| +## Census |
| + |
| +Plan-only Markdown outside census; no overlay now. Execution touches root dependencies `internal/{boxchoice,edge,activator,host,edgesfile}` even for JSON fields: bodies/sites/new units/file envelopes. Agent-run is not exemption. No new root read/authority intended; reviewer checks callbacks/decoders/cache/full diff. Test-only edits can change envelopes. |
| + |
| +Run `make census-card`; tab-separated CLAIMS per changed unit (new read or none); `make census-propose NAME=region-ha-p1b3a CLAIMS=<owned-file>`. No invented disposition/archive layer. Run `nice -n 19 go test ./internal/provision -run 'TestPlan14RootReadCensus|TestCensusScopeIsTheRootBinary|TestPlan14RootInputInventoryCoverage|TestCensusRebaseCarriesDispositions' -count=1`. Check 9B8, re-pin demonstrated changed digest only. Independent cross-family reviewer approves each unit/envelope versus amadan main and records tip/verdict on #280 at implementation landing. No review dispatched now; no census unit escalates to Paul. P2 fixes still need census/new-security-behavior checks within budget. |
| + |
| +## 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. |
| +- **Paul, before 3b plan:** minimal SQS consumer (recommended), or explicitly slower age-based no-SQS recovery. Request-only cannot recover unattended duties. |
| +- 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 has owning test. No tests/drills/reviewer verdict while drafting. |