Merge design-region-ha-held-requests (spec §25 r4, plan)
2 files changed,
+382
−1
docs/superpowers/plans/2026-11-08-region-ha-held-requests.md+97 −0docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md+285 −1
CI passed — run details
diff --git a/docs/superpowers/plans/2026-11-08-region-ha-held-requests.md b/docs/superpowers/plans/2026-11-08-region-ha-held-requests.md| new file mode 100644 |
| index 000000000..8e31961dd |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-08-region-ha-held-requests.md |
| @@ -0,0 +1,97 @@ |
| +# Region HA G5: held requests during a planned handover |
| + |
| +Branch `design-region-ha-held-requests` from origin/main 9622c65a. |
| +Spec: `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` §25 (rev 6.6, section r3 after Astra rounds 1 and 2). |
| +**Not to be built before Paul approves §25.** Review budget: three Astra rounds for spec and plan together; rounds 1 and 2 are spent (NOT READY, 11 then 8 P1, all dispositioned in §25.12; four families repeated and are now invariants H1-H5 or refusals). Round 3 is final: a P1 there goes to Paul as options, with no round 4. Stop at the first round with no P1. A family that draws a P1 twice gets cut or becomes an invariant. |
| + |
| +## Problem |
| + |
| +A planned member replacement answers 503 for every awake HA host it held. systemd stops the tenants before the edge's SIGTERM, then the edge closes its listeners before any marker, and peers then refuse with `Retry-After: 10` until a re-read finds the marker (§25.1). The fix drains the member while it is alive and holds requests on it, then takes the provider action on a lock-free box (§25.2). |
| + |
| +## Global constraints (binding on every task) |
| + |
| +- **I1 unchanged.** Only `hafresh.DecideAcquire` authorizes an acquire. A take request and an `X-Carlos-Handover` answer are never inputs to it. |
| +- **Unplanned paths unchanged.** A lost lease, a suspect holder, a hard kill and every refusal that exists today keep their answers byte for byte. A table test pins each one. |
| +- **No unsafe replay (I9, H2).** Replay only from a whole copy (at most 64 KiB, read before the first send) after an `X-Carlos-Handover` answer on a first attempt, or under §6.5's existing rule. |
| +- **No new polling.** The S3 work added is per drain (§25.10). Tests count store calls. |
| +- **Census.** Tasks that touch census-pinned sites (the front door in `ServeHTTP`, the hop answer path, the roll tool, root verbs) carry a census card and cross-family approval on #280 before merge. |
| +- **Local verification:** changed packages only, with `-run`. CI runs the full suite. |
| + |
| +## Task 0: `errShuttingDown` gets a real answer (independent; can merge first) |
| + |
| +In `serveWakeError` (`activator.go:~6534-6611`), map `errShuttingDown` to the admission "unavailable" 503 with `Retry-After: 10`, plus `X-Carlos-Holder: none` on a forwarded HA hop. Stop logging it as a wake failure. Test: a request waiting on a stopping entry during `Shutdown` gets that answer. |
| + |
| +## Task 1: drain state, acknowledged withdrawal (§25.4 steps 1 and 4) |
| + |
| +Files: `internal/host/edgesfile.go`, `internal/edge/wakeplacement.go`, `internal/activator/haplacement.go`, `internal/activator/hacache.go`, new `internal/edge/hadrain.go`. |
| + |
| +1. A box-level drain state and `drained` in the edges file. Choose the field after a §24 reader table: it withdraws placement only, and name authority, admission and holder reachability are unchanged. The per-entry `draining` that db reads use keeps its meaning. |
| +2. Placement on every box treats it as local-denied, including §6.3 rule 1. `drained` drops holder-cache entries naming the box. A draining box is never made suspect by `ForwardSilent`. |
| +3. `/.carlos/ha-drain`: a signed hop. The receiver refreshes its fold of the asker's edges file and answers what it sees. |
| +4. Tests: a clean marker naming a draining box sends the wake elsewhere; a failed fold refresh answers "not seen"; fixed and cross-region receivers. |
| + |
| +## Task 2: `MoveState`, the one front-door decision (H1, §25.5) |
| + |
| +Files: `internal/edge/edge.go` (`ServeHTTP`), new `internal/activator/handover.go`, `internal/edge/forwardha.go`. |
| + |
| +1. `MoveState(route)` is memory-only and runs under the activator lock: loss latch first, then `holding` | `releasing` | `taken(holder, gen)` | none. One call site, right after route lookup and before `frontForwardHA`, admission, the gate, rate limits, recording and the held-stream branch. |
| +2. Hold queue: 64 per host, 1,024 per box; 30 s for a client request, 25 s for a hop. The body is unread. |
| +3. Release: a client request takes the ordinary front forward to the confirmed holder. A replayable first-attempt hop gets a full-duplex 503 `X-Carlos-Handover`. Any other hop gets today's answer. |
| +4. Strip `X-Carlos-Handover` from app responses, and `X-Carlos-Replayable` from inbound client requests. |
| +5. Tests: every route kind, gated routes with a gate cookie, marked streams, F-A at each phase, once-only accounting, every bound. |
| + |
| +## Task 3: whole-copy replay and the attempt counter (H2, H3) |
| + |
| +Files: `internal/edge/forwardha.go`, `internal/edge/backhaul_holder.go`, `internal/edge/backhaul_retry.go`. |
| + |
| +1. HA forwards and HA backhaul read a body of at most 64 KiB whole before the first send, and set `X-Carlos-Replayable: 1`. Larger or unknown-length bodies stream as today and are never replayed. |
| +2. One attempt counter is shared by the forward, backhaul and retry paths. A handover answer is followed only on attempt 1, after validating the ref against view and name authority. A ref naming this box serves locally. |
| +3. Tests: a POST up to 64 KiB, and over it; chunked with trailers; `Expect: 100-continue`; no replay after a reset; a second-attempt handover answer gets today's answer; cross-region and alias requests. |
| + |
| +## Task 4: the take endpoint (§25.7) |
| + |
| +Files: new `internal/edge/hatake.go`, `internal/activator/hatake.go`, `internal/host/edgesfile.go` (`ha_take`). |
| + |
| +`/.carlos/ha-take` is hop-signed and carries the host, its lifetime and the marker generation. Its refusals are those §25.7 lists. It runs the HA acquire, never forwards, wakes H within the wake bound, and answers the owner from `lock.json`. Tests: no marker; another generation; a third box winning the race; each refusal. A mutation in which take bypasses `DecideAcquire` must fail a test. |
| + |
| +## Task 5: the drain driver and verb (§25.4, H5) |
| + |
| +Files: `internal/host/group_maintenance_verbs.go` (`drain`, `drain --cancel`), new `internal/host/hadrain.go`, activator hooks. |
| + |
| +1. Steps 1 to 5 of §25.4: withdrawal acknowledged by every live box that views the region; quiescence of starts, wakes, acquires, recovery workers, stops and marker obligations; moves up to 4 at a time; the connection drain; the report with the agent's incarnation. |
| +2. The failures of §25.4: unclean releases, missing acknowledgements and the deadline. A failed drain keeps the drain state until `--cancel`, and release work keeps its owner. |
| +3. Tests: the whole driver against two in-process boxes and MinIO; a wake restoring when the drain starts; an acquire paused before its PUT; a renewing unproven stop; Finish failing while the marker succeeds; files Final incomplete; an agent restart between report and action. |
| + |
| +## Task 6: roll tool transactions (§25.6, §25.9, H4) |
| + |
| +Files: `scripts/region-group-roll.py` and its tests. |
| + |
| +1. `replace`, `remove` and the changed `roll` share one shape: preflight and floor, lower minimum, `EnterStandby` with decrement, verify deregistration, `drain`, lock re-read and incarnation check, the action, restore, watch, report. |
| +2. H4: the provider adapter refuses any call that lowers desired other than A's `EnterStandby`. Test it with a fake provider that terminates a different instance whenever desired is lowered any other way. Confirm against the AWS docs that terminating a Standby instance without decrement leaves desired unchanged. |
| +3. Floor: `ha_take` on every live box that views the region, and on the pinned template's release. First install falls back to DR-4 and says so. |
| +4. `remove`: refuse it when a pool would be left unserved or fewer than 2 members would remain. |
| +5. Fakes and argv tests in the existing style. One attended live call on dev, with the real transport, before any window. |
| +6. Runbook text for resize and scale-in in `docs/region-ha-runbook.md`, on its own docs branch, with Paul's copy review. |
| + |
| +## Task 7: simulation (§25.10) |
| + |
| +Add the §25.10 actions, the invariants I9 to I11 and the mutations. Run one 3,000-seed sweep per revision, serially, at nice 19. |
| + |
| +## Task 8: integration witness, spec, census and CI |
| + |
| +The integration test of §25.10. Update §25 with anything the build changes. Census cards, CI, then the branch review (Opus, cross-family against Astra implementers). |
| + |
| +## Dev witnesses (a dated card for 8a3d302 after a release; not part of the build) |
| + |
| +W0 to W5 as §25.10 states, on the dev IE group. DR-4's lock-free rule stays in every card until W1 to W4 pass on a release at the floor. |
| + |
| +## Order |
| + |
| +Task 0 first (independent). Then 1; then 2, 3 and 4 in parallel (one implementer for 2 and 4, which share activator state); then 5; then 6 and 7; then 8. Release, then the card. |
| + |
| +## If Paul takes §25.14's recommendations |
| + |
| +- **R3.1 fence:** Task 5 adds a root-owned, transaction-bound start fence that the agent's start gate reads, kept across agent restarts. Task 6 stops the edge under the fence and proves the process gone before replace and remove; for roll, the restarted agent starts behind the fence until ExitStandby. Witness: a restart after the tool's last check while the provider call is delayed. |
| +- **R3.2 tickets:** Task 2 has `MoveState` register an admission ticket under the lock that starts holding. The move waits for tickets within the 10 s drain. The hook runs after route resolution, on the primary identity. Pause-point tests: after `MoveState` returns none, after `ForwardTarget` returns local, and while `begin` waits on a stop. The alias, metadata and gate-login routes are covered explicitly. |
| +- **R3.3 bounded exits:** Tasks 2 and 3 get one full-duplex, connection-close response path for every handover exit, and non-replayable hops are refused before queueing. Tested on real HTTP/1.1 with an unfinished chunked body and a stalled fixed-length body. |
| +- **R3.4 redirect:** Task 2 keeps `taken` for the whole drain. Each answer is checked by one coalesced lock read, at most one per host per 5 s, and names the current owner or the placement choice. Tested with a peer that still caches A 31 s after a move, and with the successor sleeping and a third box acquiring. |
diff --git a/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md b/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md| index 753c290da..e97808017 100644 |
| --- a/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md |
| +++ b/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md |
| @@ -1,6 +1,6 @@ |
| # Region HA without claims: N-box regions behind a load balancer |
| -Design, 2026-10-26, **rev 6.5** (§7.5 DR-5, 2026-11-08): rev 6 APPROVED by Paul on 2026-10-26, plus his ruling N-HA7 the same day (a scope ruling, not a redesign: §2.1, §8.4, §13, §19). Astra rounds 1 to 3 are complete, and the review budget is spent (AGENTS.md, stopping rules). Branch `design-region-ha-no-claims`, cut from `origin/main` at ddf3b929. Nothing here is built. |
| +Design, 2026-10-26, **rev 6.6** (§25 held requests during a planned handover, 2026-11-08, APPROVED by Paul 2026-11-08 ~22:15Z as r4 (§25.15); Astra rounds 1-3 spent, no fourth round; rev 6.5 added §7.5 DR-5): rev 6 APPROVED by Paul on 2026-10-26, plus his ruling N-HA7 the same day (a scope ruling, not a redesign: §2.1, §8.4, §13, §19). Astra rounds 1 to 3 are complete, and the review budget is spent (AGENTS.md, stopping rules). Branch `design-region-ha-no-claims`, cut from `origin/main` at ddf3b929. Nothing here is built. |
| This spec supersedes every claim-dependent part of "Region HA, spec 2: two-box regions" (`2026-10-15-region-ha-two-box-regions-design.md`, rev 21, cited **S2 §n**) and of spec 1 (`2026-10-04-region-ha-box-placement-design.md`, cited **S1 §n**). §16 lists what it reuses from S2, plan 2a (6834659c) and plan 2b (b1118925), and the removals this series owns. Line citations are to this worktree unless they name a module path. |
| @@ -13,6 +13,7 @@ This spec supersedes every claim-dependent part of "Region HA, spec 2: two-box r |
| - **Rev 6.2** adds the approved N-HA14 serialized operator ASG Standby maintenance exception to §12.1 (Paul, 2026-11-01). |
| - **Rev 6.4** records T1/DR-4 planned termination: shutdown ordering, release budgets and the real-terminate witness (§9.9, 2026-11-08). |
| - **Rev 6.5** records DR-5: a departure finishes when no surviving box serves a departed box's pool, and departures finish within 3 minutes of proof (§7.5, 2026-11-08). |
| +- **Rev 6.6** adds §25: a planned member replacement (terminate, roll, resize, scale-in) holds requests for a few seconds instead of answering 503. Unplanned deaths are unchanged. Not built; Paul approves before any build. |
| Under stopping rule 2, the families I2, I3 and I4 drew findings two rounds running. I2 and I4 are now stated as invariants, enforced in one place and checked by the simulation (§3.1). I3 drew a P1 in all three rounds, so rev 6 cuts its transfer protocol and restates I3 over the scan alone. |
| @@ -1028,3 +1029,286 @@ the production constructor and handler or pass. Pool-specific readers also |
| exercise unknown evidence so old writers retain their behavior. DNS |
| readers exercise missing configured ingress; configuration alone must not |
| be the protection against publishing disposable member addresses. |
| + |
| + |
| +## 25. Held requests during a planned handover (G5, rev 6.6, 2026-11-08) |
| + |
| +**Ruling being designed.** Paul, 2026-11-08, via agent manager 8a3d302: a planned member replacement gives tenants of HA-pool hosts a pause of a few seconds and no errors, instead of today's 503 with `Retry-After: 10`. "Planned" covers a roll, a re-pin, an instance-size change through the launch template, and scale-in. This is also what a self-hosted fleet such as Tito's needs to resize without downtime. Unplanned deaths keep today's behaviour: 503 with `Retry-After` until lease expiry plus termination proof (§9.4, N-HA9). |
| + |
| +Line citations in this section are to `origin/main` at 9622c65a. |
| + |
| +**Revision note (r3 of this section).** Astra round 2 (`~/.cache/region-ha-held/ASTRA-R2.md`, 8 P1) found four families for the second time: scale-in capacity, the coverage of the hold decision, the forward-attempt budget and body ownership. Under stopping rule 2 each is now an invariant enforced in one place (§25.3), or a refusal made up front with a narrower stated guarantee (§25.8). §25.12 maps every finding of both rounds. |
| + |
| +**Revision note (r2 of this section).** Astra round 1 (`~/.cache/region-ha-held/ASTRA-R1.md`, 11 P1) found that a handover started at SIGTERM is too late. systemd stops the tenant units before the edge receives its signal (`internal/host/units/carlos-instance@.service:14-16`, `carlos-instance-gen@.service:15-17`, both bound to the edge and ordered after it), so in-flight requests lose their app first. This revision moves the handover **before** any systemd action: the operator's tool drains the member while it is fully alive, and terminates or restarts it only once it holds no lease. That one move also removed the SIGTERM deadline arithmetic, the peer notices, the holds on every first box and the fallback lock reads, which drew R1.4, R1.5, R1.6, R1.7, R1.12, R1.13 and R1.14. §25.12 maps every finding. |
| + |
| +### 25.1 What happens today |
| + |
| +T1/DR-4 (§9.9) writes a clean release marker about 3 s after `TerminateInstances`. Requests still fail around it: |
| + |
| +1. **Tenants stop first.** Instance units are bound to the edge and ordered after it, so at shutdown or an edge restart they stop before the edge gets SIGTERM (R1.1). §9.9's witness shows it: the generation stop at 04:11:04.770, edge SIGTERM at 04:11:05.292. |
| +2. **The listeners close next.** On SIGTERM the edge closes admission (`internal/edge/shutdown.go:9-14`), then shuts both listeners with one 10 s context (`internal/edge/edge.go:4855-4858`). Only after that does `Service.Shutdown` (`internal/activator/activator.go:6127`) write markers. |
| +3. **Peers see a dead holder.** A refused dial makes the holder suspect (`internal/activator/hacache.go:27-41`). Each forward answers 503 with `Retry-After: 10` (`internal/edge/forwardha.go:376-380`) until a suspect-window re-read finds the marker (`hacache.go:358-363`). |
| +4. **A bug.** A request waiting on a stopping host that then meets `errShuttingDown` falls through `serveWakeError` to 503 "instance failed to wake" with no `Retry-After` (`activator.go:6603-6611`). |
| + |
| +Nothing on main drains a member: role `drain` is a value that group boxes treat as invalid (`internal/host/group_admission.go:101`), and the roll tool never looks at leases (`scripts/region-group-roll.py`). |
| + |
| + |
| +### 25.2 The model |
| + |
| +A planned replacement of member A is one operator transaction, in this order: |
| +1. **Out of the load balancer.** A enters Standby, so the NLB sends it no new client flows (§25.6). |
| +2. **Withdraw and quiesce.** A stops being a placement choice, every live box acknowledges that, and A settles every acquire already under way (§25.4 steps 1-2). |
| +3. **Move the leases.** A moves each awake host to a successor, and holds the requests that reach it for that host while it moves (§25.4 step 3, §25.5). |
| +4. **Drain the connections.** A finishes the requests it is still forwarding, and closes keep-alive connections and long streams in an orderly way (§25.4 step 4). |
| +5. **The provider action.** Restart the edge (roll), or terminate (replace, scale-in). A holds no lease and carries no traffic, so T1's shutdown has nothing to release. |
| + |
| +Rules that carry over unchanged: |
| +- **I1.** Only a release marker lets another box acquire (§9.4). The successor acquires through `hafresh.DecideAcquire` (`internal/hafresh/acquire.go:77-115`) like any box. Nothing in this section is an input to it. |
| +- **Takeover after proof and expiry** stands for every lease without a marker. |
| +- **F-A.** A host whose lease is lost answers 503 `Retry-After: 10` with holder `none` at once, in every phase. |
| +- **I4.** A request makes at most two forward attempts, and a box never forwards a request it received as a hop (§6.4, §6.5). This section adds no exception (§25.3 H3). |
| + |
| +### 25.3 Invariants |
| + |
| +Each is enforced in one place, checked by the simulation (§25.10) and guarded by a mutation that must fail the sweep. This is stopping rule 2's third option for the families round 2 drew a second time. |
| + |
| +| # | Invariant | Enforced only in | |
| +|---|---|---| |
| +| H1 | **One handover decision.** Every request whose route is a host that is moving on this box is classified by one memory-only activator call, `MoveState(route)`. It runs at the front door, right after route lookup, before `frontForwardHA`, admission, the gate, rate limits, recording and the held-stream branch (`internal/edge/edge.go:1953-2197`). It covers direct requests, hops and marked streams. It checks the lease-loss latch first, so F-A always wins. (R2.2, R2.3) | `MoveState`, called once from `ServeHTTP`. | |
| +| H2 | **Replay only from a whole copy.** A first box may send a request a second time only if, before its first send, it read the entire body into memory (at most 64 KiB) and marked the hop `X-Carlos-Replayable: 1`. Bodyless requests count as whole. Nothing else is ever sent twice, except under §6.5's existing rule. (R2.5) | The HA forward's body preparation, one function. | |
| +| H3 | **The attempt budget.** An `X-Carlos-Handover` answer is followed only when it answered the request's **first** attempt. On a second attempt it gets today's answer. So I4's limit of two attempts holds with no exception. (R2.4) | The forward and backhaul retry paths' shared attempt counter. | |
| +| H4 | **Desired capacity is lowered only by targeting A.** The only call that lowers the group's desired capacity is `EnterStandby` of A with decrement (`scripts/region-group-roll.py:760-765`). Minimum is lowered first, as today. Desired is raised again only by the transaction's final restore. (R2.1) | The roll tool's provider adapter. | |
| +| H5 | **Quiescence before the provider action.** The provider action runs only against a drain report from the agent's **current incarnation** that certifies: no acquire, wake or recovery in flight; no pending stop or marker obligation; no forwarded request in flight; and no lease naming A. The tool reads the report again immediately before the action. An agent restart voids the drain. (R2.7) | The drain barrier in the agent, and the tool's pre-action check. | |
| + |
| +### 25.4 Draining member A |
| + |
| +The roll tool runs a new root verb, `carlos system group-maintenance drain`, over SSM, as it runs `apply`. The verb asks the agent to drain, waits, and prints the agent's report. A is already in Standby (§25.6). The agent's steps: |
| + |
| +1. **Withdraw, acknowledged.** A publishes a box-level drain state in its edges file, and from then on places nothing on itself. The field withdraws placement only. Name authority, admission and holder reachability are unchanged, so A keeps answering as a holder and a forwarder (R2.9). Placement reads it as local-denied (`internal/edge/wakeplacement.go:36-42`), and that includes §6.3 rule 1, so a clean marker naming A no longer sends a wake to A. The builder fixes the field with a reader table under §24's rule. |
| + |
| + A timer does not prove that peers folded the change (R2.9). So A sends a signed `/.carlos/ha-drain` hop to every live box of the deployment that views its region, fixed forwarders and other regions included. Each receiver refreshes its fold of A's edges file at once, which is one normal fold read, and answers whether it now sees A draining. A asks again every 5 s. Each request names the drain transaction and the generation of A's edges file. A receiver that has already folded that generation answers from memory with no new read, so each receiver costs one fold read per round however often it is asked (R3.9). The drain goes on only once every such box has acknowledged. A box that cannot be reached, or does not acknowledge within 2 minutes, makes the drain fail (failures, below). |
| +2. **Quiesce (H5).** A closes its local start gate for tenant leases. It then settles everything that crossed the gate before it closed: wakes that are restoring, acquires waiting on their conditional PUT, and lost-lease recovery workers. Each either ends awake, and is then moved in step 3, or fails. Pending stops and marker obligations are kept and settled (§5.2). Nothing is cancelled in a way that would drop a writer proof. |
| +3. **Move each awake host H,** up to 4 at a time, busiest first: |
| + 1. *Hold.* From now `MoveState(H)` is `holding` (§25.5). |
| + 2. *Finish in-flight work.* Requests already admitted to H's app get up to 10 s, today's HTTP drain bound. Then the stop proceeds as a shutdown stop does, which ends long requests, WebSockets and edge-held stream legs (#432 G5). |
| + 3. *Release.* `finishStop` writes the marker (§5.2), with the drain as its stop reason and the existing budgets. |
| + 4. *Take.* A chooses a successor B: `ChooseRoomiest` over its eligible serving set (§6.3), or the HRW box for an always-on worker (A10). A sends B a signed take request (§25.7). B acquires and wakes H, then answers with the owner it now sees in `lock.json`. That owner is the **confirmed holder**: B, or a third box that won the marker first (§6.7). |
| + 5. *Release the holds* (§25.5). Edge-held SSE streams for H whose outer connection is on A are closed now, at an event boundary, so they reconnect to the new holder without waiting for the rest of the drain (R3.5). `MoveState(H)` becomes `taken(holder, lock generation)` for 30 s, and then the entry is dropped. After that, a stale hop for H is answered as by any non-holder (§6.4). |
| +4. **Drain the connections.** When no lease names A, it publishes `drained` and asks for the same acknowledgement as in step 1. Peers drop holder-cache entries naming A (§6.6). A then sends `Connection: close` on every response, closes idle keep-alive connections, and waits up to 60 s for the requests it is still forwarding to finish. Edge-held SSE streams still open through A are closed at an event boundary, and the browser reconnects through the NLB to another box, with `Last-Event-ID`. WebSockets and responses still running at 60 s are closed, and the report counts them. |
| +5. **Report.** The report lists hosts moved, each one's confirmed holder, the longest hold, holds that got today's answer, unclean releases, connections closed at the bound, and the agent's incarnation. The agent keeps it until it exits, for the tool's pre-action check (H5). |
| + |
| +**Failures.** A drain fails, and the tool refuses the provider action, when: |
| +- a host is left without a marker (S3 down, failed stop proof); |
| +- a take fails or names no holder; |
| +- a release was **unclean** (§5.2). Another box may hold the host, but writes or files were lost, so it is not a successful planned move (R2.11); |
| +- an acknowledgement is missing; |
| +- the drain deadline passes: 15 minutes plus 1 minute per 20 awake hosts. |
| + |
| +On a failure every hold ends with today's answer. Release work already running continues under its own budgets and obligations, owned by the activator as today (R2.10). The drain state stays, so A places nothing, until the operator reruns `drain` or ends it with `drain --cancel`. No override lets the provider action run after a failed drain. An operator who chooses to go on anyway uses today's DR-4 procedure by hand, outside the tool. |
| + |
| +### 25.5 Holds on A |
| + |
| +**What `MoveState(H)` does** (H1), in order: |
| +1. A lost lease: F-A's answer. |
| +2. `holding` or `releasing`: the request is held, and A reads none of its body. |
| +3. `taken(holder, gen)`: the request is released at once, as below. |
| +4. Anything else: nothing changes, and the request goes on as today. |
| + |
| +A marked held-stream request is classified the same way. While H is held its marked requests are held too, and they never start a held task (R2.3). |
| + |
| +**Release.** |
| +- **A request A received from a client** goes to the confirmed holder through the ordinary front forward. That is A's first attempt, and the holder runs the tenant pipeline once: gate, accounting and recording (R2.2). The unread body streams as today. If the confirmed holder were A the request would get today's answer, but that cannot happen, because A acquires nothing while draining. |
| +- **A hop from a first box C** cannot be forwarded on (§6.4). If the hop is marked `X-Carlos-Replayable: 1` and it is C's first attempt (H2, H3), A answers 503 with `X-Carlos-Handover: holder=<ref>; gen=<n>`. The answer means "not delivered, send it there". A writes it with full duplex enabled (`http.NewResponseController(w).EnableFullDuplex()`, as `internal/edge/demo_api.go:132` does), so the answer never waits for a body to drain (R2.5). C validates the ref against its view and name authority, then sends its copy there as its second and last attempt. If the ref names C, C serves the request locally, which spends no attempt. C caches the holder. |
| +- **Any other hop for a moving host** (not replayable, or a second attempt) is held, then gets today's answer at release. This is the narrowed guarantee (§25.8). |
| + |
| +**Bounds.** The constants are the builder's to tune; the shapes are not. |
| + |
| +| Bound | Value | When exceeded | |
| +|---|---|---| |
| +| Time held, a client's request | 30 s (`wakeWaitBound`, `internal/activator/activator.go:1208`) | today's answer | |
| +| Time held, a hop | 25 s, inside the hop's 30 s header timeout (`internal/edge/edge.go:4180`) | today's answer | |
| +| Held requests per host | 64 | the new request gets today's answer | |
| +| Held requests per box | 1,024 | the same | |
| +| Whole-body copy on C | 64 KiB | not replayable | |
| + |
| +**Silence.** Today a connected holder that sends no headers within 3 s is noted `ForwardSilent` (`internal/edge/forwardha.go:332`). That marks the entry silent, not suspect: it costs one lock re-read and does not refuse later requests (`internal/activator/hacache.go:264-289`, `:478-484`, pinned by `hasuspect_test.go:672-725`). A held hop is silent by design, so no box takes that re-read or any placement suspicion for silence from a box in the drain state. All other silent, suspect and unreachable behaviour is unchanged (R3.7). |
| + |
| +**The headers.** `X-Carlos-Handover` is honoured only on an answer to a hop sent over the verified forward or backhaul transport. It is stripped from app responses at the tenant boundary, beside `X-Carlos-Holder` (`stripAppHolder`, `forwardha.go:118-128`). Only the platform sets `X-Carlos-Replayable`, and it is removed from inbound client requests. |
| + |
| +**Cross-region first boxes** follow the same rules (H2, H3). In the common case, a cross-region request's first attempt goes to a box of the region other than A, which names A as the holder, so its second attempt reaches A. That second attempt cannot be redirected, so it gets today's answer (§25.8). |
| + |
| +### 25.6 The provider action and the three paths |
| + |
| +The roll tool gains `replace` and `remove` transactions beside `roll`. All three run under the existing maintenance lock and journal, one member at a time, with no concurrent transaction or region apply. They share one shape: |
| + |
| +1. Preflight: the roll's shape checks (`scripts/region-group-roll.py:917-942`) and the floor (§25.9). |
| +2. Lower minimum by one, then `EnterStandby` of A with decrement, then verify A is deregistered from both target groups, as the roll does today (H4). |
| +3. `drain` (§25.4). A failed drain stops the transaction: the tool exits Standby and restores the shape, and A stays draining until `drain --cancel`. |
| +4. Re-read every lock in the region's data bucket that names A. Each must be a marker or have another owner. Read A's drain report again and check its incarnation (H5). |
| +5. The action: |
| + - **roll:** `apply`, which restarts the edge with nothing awake, then ExitStandby and restore minimum, as today. The restarted agent is not draining. Its markers name it, but the hosts are held elsewhere; |
| + - **replace:** terminate A in the group without decrement. Desired is already N - 1, so nothing launches yet. Then restore desired, then minimum, to N, and the group launches one replacement; |
| + - **remove (scale-in):** terminate A without decrement, leave desired at N - 1, and set minimum to N - 1. Preflight refuses if the survivors would leave a pool A served with no server, or if fewer than 2 members would remain. The operator then sets `box_count` in tofu to match, which plans no instance change. |
| +6. Watch: the departure finishing within §7.5's bound and, for replace, the replacement admitted and healthy in both target groups. Report. |
| + |
| +Terminating an instance in Standby without decrement must leave desired unchanged. The builder confirms this against the AWS documentation, and tests it with a fake provider that terminates a different instance whenever any other call lowers desired (H4). One attended live call on dev, with the operator's real transport, comes before any window. |
| + |
| +**Capacity** is N - 1 from Standby until the replacement is admitted, a few minutes. With N = 2 the survivor carries every host meanwhile; wakes are never refused for headroom (A20). Launching the replacement first needs a second N-HA14 exception (Q1). |
| + |
| +**Resize.** The operator sets `instance_type` in the region's group module and applies, which makes a new launch template version. They re-pin `group_launch_template_version` to it, then run `replace` once per member. The operator sees a tofu plan with a launch template change and no instance change, then one report per member: hosts moved, the longest hold, holds that got today's answer (target 0), connections closed at the bound, and the departure time. |
| + |
| +### 25.7 The take request |
| + |
| +The take is a new hop endpoint on every HA box, `/.carlos/ha-take`, signed with the mesh key like any hop. It carries the host, its lifetime and the generation of A's marker. The receiver: |
| +- refuses unless it serves H's pool, is admitted and not draining, and holds a valid record for the host with that lifetime; |
| +- runs the HA acquire for H, and never forwards. A lock in any state other than that marker gets the normal acquire decision; |
| +- wakes H, and answers once H is awake or the wake has failed, within the wake wait bound; |
| +- answers with the owner it read or wrote in `lock.json`: itself, another box (held), or none. |
| + |
| +Both control paths, `/.carlos/ha-take` and `/.carlos/ha-drain`, are reserved on every ingress: a client request for either is refused at the front door and never forwarded. Each carries its own signature over the method, path, body, drain transaction and timestamp, as probe-burst notices do (`internal/edge/burst_notice.go:499-529`). The ordinary hop signature is not enough, because it binds only host and time (`internal/edge/mesh.go:188-190`). Bodies are bounded at 4 KiB (R3.8). A take is a forwarded wake without a visitor, and it authorizes nothing the acquire table does not already allow. A box advertises it with an additive edges field, `ha_take: 1`. |
| + |
| +### 25.8 What clients see |
| + |
| +- **Zero errors** for every request whose first attempt reaches A. That covers requests through the NLB before Standby, from a peer whose cache names A (the normal in-region case), or through a fixed forwarder in the region. The body must be empty, or have a known length of at most 64 KiB and be copied whole before the first send (H2). An unknown-length body, however small, is not replayable. A request that reached A directly streams its body and has no size limit. The condition is the attempt number on arrival at A and the body's framing, on every ingress path, not the client's region (R3.6). The pause is the rest of H's in-flight work (up to 10 s, usually milliseconds), plus the release (about 1 to 3 s), plus the successor's acquire and restore. The target is under 5 s for a small host. |
| +- **Today's 503 with `Retry-After: 10`,** only in the seconds that host is moving, for: |
| + - a hop whose body is over 64 KiB or of unknown length; |
| + - a request whose first attempt went to another box that named A, on any ingress path; most cross-region requests are like this (H3); |
| + - any bound hit or failed move. |
| +- **Connections:** keep-alive connections are closed between requests. SSE streams reconnect with `Last-Event-ID` after the browser's retry delay. WebSockets still open through A 60 s after its leases have moved are closed, and their clients reconnect. Requests already dispatched to an app (uploads, downloads, upgrades) that run past H's 10 s drain, or past the final 60 s, are cut and never retried, because they may have reached the app (R3.5). |
| +- **An unplanned death:** today's behaviour, unchanged. |
| + |
| +### 25.9 The floor |
| + |
| +A drain is only safe when every box that may send A a request understands the new headers, and successors understand a take. So: |
| +- `drain` refuses unless every live box of the deployment that views the region publishes `ha_take: 1`. The same release adds every behaviour in this section. Fixed forwarders such as adi count. |
| +- `replace` also checks that the release the pinned launch template boots (`group_config.release`, `infra/modules/region-host/group.tf:50`) is at or above the floor. After the launch, it checks that the replacement publishes `ha_take: 1`. |
| +- **First install.** Rolling a group onto the first release with §25 cannot drain. That roll uses today's DR-4 rule, replacing only lock-free members, and the tool says which rule it applied. |
| +- A rollback below the floor brings DR-4 back. The tool checks the floor on every transaction. |
| + |
| +**DR-4's lock-free rule** becomes obsolete for a region once all its boxes are at the floor and the dev witnesses (§25.10) have passed. Until then it stays in every card. |
| + |
| +### 25.10 Request budget, tests and witnesses |
| + |
| +**Request budget (§18).** |
| +- **Steady state:** unchanged. Nothing polls. `ha_take` rides the existing edges publication. |
| +- **Per drain:** |
| + - two edges mutations (the drain state, then `drained`), each with its change-index update and §18's reader amplification; |
| + - two acknowledgement rounds, each costing one fold read per live box (one LIST plus one GET per edges file, as at any fold). A failed fold read is retried at the 5 s cadence, so the worst case is 24 fold reads per box per round. The change-index fold that the publication triggers anyway is separate; |
| + - the tool's lock check: one LIST of the region's locks plus one GET per HA host. |
| +- **Per host moved:** the marker PUT, as at any sleep, plus the successor's acquire (1 GET + 1 PUT) and restore, which the host's next wake would have cost anyway. |
| +- **Example:** replacing all 4 members of a region with 200 awake hosts, some moved twice, costs about 300 markers and acquires, 8 edges mutations, 8 acknowledgement rounds over 6 boxes, and 4 lock sweeps of 500 hosts. That is about $0.01 in S3 requests, plus the restore GETs. |
| + |
| +**Simulation (§21.1).** It adds: |
| +- Standby and drains; |
| +- acknowledgements that are slow or missing; |
| +- takes that win or lose the marker race; |
| +- direct requests, hops and marked streams during a move; |
| +- whole-copy replay, and connection failures before and after a send; |
| +- lease loss mid-move, wakes in flight when the drain starts, and stale caches. |
| + |
| +New invariants: |
| +- **I9, no unsafe replay.** No request reaches two apps' handlers. |
| +- **I10, bounded hold.** Every held request is answered within its bound plus one forward. |
| +- **I11, lock-free action.** No provider action runs while a lease names A or an acquire on A is in flight. |
| +- I1 and I4 still hold. |
| + |
| +Each of these mutations must fail the sweep: |
| +- a take or a handover answer authorizes an acquire (I1); |
| +- `MoveState` is checked after the gate, or not checked for marked requests (H1); |
| +- a request is held after a lost lease (F-A); |
| +- a replay without a whole copy (H2); |
| +- a handover answer followed on a second attempt (H3); |
| +- desired lowered by any call but A's Standby (H4); |
| +- a provider action on a stale incarnation's report, or before quiescence (H5); |
| +- placement on A before every acknowledgement. |
| + |
| +**Integration tests** run in-process against MinIO, with two real activators and edges. They cover: |
| +- the front-door position of `MoveState` for every route kind, gated routes included, with once-only accounting; |
| +- F-A at every phase; |
| +- the take racing a third box, and a successor that is the first box; |
| +- replay of a hop POST up to 64 KiB, and refusal over it; |
| +- no replay after a reset; |
| +- full-duplex answers under a slow chunked upload; |
| +- an SSE stream closed and resumed with `Last-Event-ID`; |
| +- a wake still restoring when the drain starts, and an agent restart between the report and the action; |
| +- an unclean release failing the drain; |
| +- `errShuttingDown` getting a real answer; |
| +- store-call counts per drain. |
| + |
| +**Dev witnesses** run on the dev IE group. Each has a probe from outside the VPC sending about 3 requests a second to two HA hosts awake on the member: GETs, POSTs of up to 64 KiB with unique ids that write, and an SSE stream from an app that emits a numbered event every second. A witness passes with: 0 non-2xx, 0 transport errors and 0 timeouts on the probe's in-region path; every acknowledged POST id present afterwards; no SSE event number missing after the reconnect; and the longest pause under 5 s. |
| +- **W1 replace** a lease-holding member. |
| +- **W2 roll** a lease-holding member. |
| +- **W3 resize** both members, t4g.small to t4g.medium, with `replace`. |
| +- **W4 scale-in** from 3 to 2 with `remove`, plus a `remove` that is refused because it would leave a pool unserved. |
| +- **W0 control.** A hard kill still gives today's 503 with `Retry-After: 10` until expiry plus proof. |
| +- **W5 limits** (recorded, not gating): a cross-region request and a POST over 64 KiB during W1. They get today's answer within the move window. |
| + |
| +W1 to W4 passing on a release at the floor is what retires the DR-4 rule. |
| + |
| +### 25.11 What a self-hosted fleet needs (Tito) |
| + |
| +- **Version floor:** a release with §25 on every box of the region and on every box that forwards into it, the console included. The console must be current main. |
| +- **Shape:** |
| + - the nested layout; |
| + - the region in group mode (`infra/modules/region-host`), with its NLB, launch hook, terminations queue and rule; |
| + - `CARLOS_REGION_HA` and `CARLOS_GROUP_ADMISSION` on the members; |
| + - chrony, and SSM on the members for the roll tool. |
| +- **Pool:** a named HA pool in `CONSOLE_HA_CAPACITY_CONFIG` (`ha_pools`), and `CONSOLE_HA_REGIONS` on the console (§23). |
| +- **Which instances benefit:** only born-HA instances in that pool (N-HA7). Existing instances need the operator migration slice, which is not built. Until it is, they resize the old way. |
| + |
| +### 25.12 Findings and where they went |
| + |
| +| Finding | Disposition | |
| +|---|---| |
| +| R1.1 tenants stop before SIGTERM | The move runs before any systemd action (§25.2). | |
| +| R1.2, R2.2, R2.3: coverage of the decision, F-A, gate | Invariant H1: one front-door `MoveState` for every request kind, after the loss latch. | |
| +| R1.3 closed admission | A draining box keeps admission open. Placement is withdrawn, not admission (§25.4 step 1). | |
| +| R1.4, R1.12, R1.13, R1.14: notices, fallback reads, deadlines | Gone with the notices. A is alive and answers itself. | |
| +| R1.5, R2.9: placement and fold | Withdrawal is acknowledged before any move (§25.4 step 1). | |
| +| R1.6 successor hint | The take names the confirmed holder from `lock.json` (§25.7). | |
| +| R1.7, R2.4: attempt budget, cross-region | Invariant H3: a handover answer is followed only on a first attempt. The guarantee is narrowed (§25.8). | |
| +| R1.8, R2.5: body ownership | Invariant H2: replay only from a whole copy of at most 64 KiB, taken before the first send. Handover answers are full duplex. | |
| +| R1.9 SSE | Marked requests are held. Streams through A close at the connection drain (§25.4 step 4). | |
| +| R1.10, R2.1: scale-in, capacity | Invariant H4: desired is lowered only by A's Standby (§25.6). | |
| +| R1.11 floor | The floor covers forwarders and the pinned template. First install uses DR-4 (§25.9). | |
| +| R1.15 witnesses | Integration tests against MinIO. Dev witnesses track ids, transport errors and SSE numbers, and gate DR-4 (§25.10). | |
| +| R2.6 forwarding cut at the action | Standby comes first, and the connection drain runs before the action (§25.2, §25.4 step 4). | |
| +| R2.7 quiescence | Invariant H5 (§25.4 step 2). | |
| +| R2.8 remembered holder | Kept 30 s, keyed by lock generation, then the normal non-holder answer (§25.4 step 3.5). | |
| +| R2.10 deadline and `--accept-left` | No override. A failed drain stops the transaction, and release work keeps its owner (§25.4 failures). | |
| +| R2.11 unclean release | Fails the drain (§25.4 failures). | |
| + |
| +### 25.13 Open questions for Paul |
| + |
| +- **Q1. Surge replacement.** `replace` drains and terminates first, so capacity is N - 1 for a few minutes. Launching first needs a second N-HA14 exception: maximum and desired up by one for the transaction. Recommendation: drain first for now. |
| +- **Q2. The narrowed guarantee (§25.8).** Zero errors covers in-region traffic and bodies up to 64 KiB. Cross-region requests that first reach another box, and hops with larger bodies, keep today's 503 for the seconds a host moves. Closing those gaps needs either a third, handover-only attempt (an exception to I4) or a bounded body spool on every forwarding box. Both drew P1s twice in review. Recommendation: accept the narrower guarantee now and measure W5. |
| +- **Q3. Drain time.** Two acknowledgement rounds, about 5 s per host at 4 at a time, and up to 60 s of connection drain make about 3 to 4 minutes for 40 awake hosts. Recommendation: accept. |
| + |
| +### 25.14 Round 3 (final): four P1s for Paul |
| + |
| +Astra round 3 (`~/.cache/region-ha-held/ASTRA-R3.md`) was NOT READY, with 4 P1s and 5 P2s. The P2s are applied above (R3.5 to R3.9; R3.7 corrected a false claim about silent holders). The review budget is spent, so there is no round 4 (stopping rule 1). Each P1 below has the smallest cut that removes it, and a recommendation. **Ruled 2026-11-08 ~22:15Z: Paul approved all four recommendations, and Q1 to Q3 as recommended. They are binding as §25.15 (r4).** |
| + |
| +| P1 | The defect | Options | Recommendation | |
| +|---|---|---|---| |
| +| R3.1 | H5 certifies a snapshot. A request a peer chose earlier can still reach A's open listener after the report. And if the agent restarts after the tool's last check, the new incarnation is not draining and can acquire while the provider call is in flight. | (a) **Retained fence:** a root-owned fence bound to the transaction id, kept across agent restarts, that refuses every tenant start until the tool returns the member or cancels. For replace and remove, the tool stops the edge under that fence, then proves the process gone, before the provider call. For roll, the restarted agent starts behind the fence. (b) Cut: the zero-error claim covers holds only, and the action may cut a request that arrives after the report. | (a). It is small: one fence file read at the start gate, plus a stop under maintenance the tool already orchestrates. | |
| +| R3.2 | `MoveState` is read once. A request that read "none" just before the move started is neither held nor counted as in flight, so it can be refused when it reaches the stopping host. The front-door hook also runs before the final route is chosen (alias, metadata and gate-login routes). | (a) **Admission tickets:** `MoveState` registers a ticket under the same lock that starts holding, and the move waits for outstanding tickets (within the 10 s drain) before it stops the app. The hook runs on the host's primary identity after route resolution, and keeps name, door and regional checks. (b) Cut: keep DR-4 lock-free maintenance for members with live tenant traffic until (a) exists. | (a). It is the barrier H1 needed. Option (b) gives up the goal. | |
| +| R3.3 | The full-duplex answer covers only the replayable handover answer. A non-replayable upload is held unread, then refused through an ordinary `http.Error`, which can block on draining a slow body past every bound. | Refuse non-replayable hops at once, before queueing, and send every handover exit (success, refusal, cap, timeout, loss, failed move) through one bounded full-duplex response path with connection close. | Accept. It also shortens the error for those requests. | |
| +| R3.4 | `taken` is dropped after 30 s. A peer that still caches A for a host that moved early sends its first attempt to A, and A, closed to starts, refuses before it finds the new holder. Within the 30 s, the remembered holder may also have slept, with a third box now holding. | (a) Keep the redirect for the **whole drain**, until `drained` is acknowledged and peers have dropped A. Each redirect answer is checked by one coalesced lock read on A (at most one per host per 5 s): it names the current owner, or the placement choice when the lock is a marker, which a hop receiver may acquire (§6.4). (b) Cut: no redirect after the take. Post-take stale hops get today's answer, which in practice means most in-region traffic for a host moved early. | (a). The lock reads are bounded per drain and per host, and run only on the draining box. | |
| + |
| +If Paul takes the four recommendations, they become §25 r4 as refusals and barriers, with no fourth review round. The branch review of the build and its census cards are where they are checked next. That is how rev 5 of this spec was settled on 2026-10-26. |
| + |
| +### 25.15 r4: the rulings, binding on the build (Paul, 2026-11-08) |
| + |
| +Paul approved all four §25.14 recommendations and Q1 to Q3 as recommended: drain first, the narrowed guarantee with W5 measured, and the drain time. There is no fourth spec round. The branch review of the build checks these. Where §25.3 to §25.7 say otherwise, this section wins. |
| + |
| +**H5 amended: a retained start fence (R3.1).** Quiescence is a state the transaction holds, not a report it reads. |
| +- `drain` installs a root-owned **start fence** bound to the transaction id, under the maintenance directory the group-maintenance verbs already own. The agent's tenant start gate refuses every start while a fence is present. The agent reads the fence at start and at every start decision, so a restarted agent is fenced too. Only the tool removes the fence: at ExitStandby for roll, at cancel, or when the member is gone. |
| +- **replace and remove** stop `carlos-edge.service` under the fence after the drain report, prove the edge process gone, and only then make the provider call. A peer request chosen against an old snapshot then meets a closed port, not a box that might acquire. |
| +- **roll**'s `apply` restarts the edge behind the fence, so the restarted agent can acquire nothing until the tool's return step. |
| +- The pre-action check reads the fence, the report and the stopped edge. A fence of another transaction refuses. |
| + |
| +**H1 amended: admission tickets (R3.2).** `MoveState` runs after route resolution, on the primary identity of the accepted route: after metadata and alias authority (`internal/edge/haingress.go:63-126`) and the gate-login upstream change (`internal/edge/edge.go:2320-2359`). Name, door and regional checks keep their places. When `MoveState` answers "none" for a host this box holds, it registers an **admission ticket** under the same activator lock that sets `holding`. The ticket lasts until the request finishes or is forwarded. A move waits for that host's outstanding tickets, and for requests already waiting in `begin`, within the 10 s in-flight drain, before it stops the app. So every request crossing a move is either counted or held. |
| + |
| +**One bounded exit path (R3.3).** Every handover exit goes through one response function: success, refusal, cap, timeout, lost lease and failed move. It enables full duplex before writing, flushes headers, and closes the connection after the reply, so no exit waits for an unread body. A hop for a moving host that is not replayable, or is a second attempt, is answered at once through that function. It is never queued. |
| + |
| +**The redirect lasts the whole drain (R3.4).** `taken(holder, gen)` is kept per host lifetime until `drained` is acknowledged, not for 30 s. Before A answers a hop from it, A checks the lock with one coalesced read, at most one per host per 5 s. The answer names the current owner, or, when the lock is a release marker, A's placement choice, which a hop receiver may acquire from the marker (§6.4). Anything else gets the bounded refusal. Budget: at most one lock GET per moved host per 5 s on the draining box, only while stale hops arrive. |