spec: region HA §25 held requests during a planned handover (rev 6.6)
Draft for Astra review and Paul's approval. No code.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md+172 −1
Intent
<task-notification> <task-id>a650cfb23dbffd937</task-id> <tool-use-id>toolu_01SkWUVXhCkUVtf6VruonCZa</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/283be278-5c6a-4a71-a8d6-b3d32c668985/tasks/a650cfb23dbffd937.output</output-file> <status>completed</status> <summary>Agent "Map HA handover code paths" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>I've mapped all seven items to file:line in the code. Two things you asked about don't exist: a "replace only lock-free members" rule, and any per-host awake/holder publication. A third is stale: the spec's `activator.go:5186-5194` pointer for the activator shutdown, which now starts at `activator.go:6127`. Line numbers are at HEAD `5b6d5374`. ## 1. Edge request path for an HA tenant host **Order in `Edge.ServeHTTP`** (`internal/edge/edge.go:1940`): 1. The `carlos_hold=1` mark goes on the context at 1953. 2. `acceptHop` runs at 2031. Headers are `X-Carlos-Hop` / `X-Carlos-Hop-Auth` (`homemap.go:102-103`). The HMAC covers host and time, ±30 s skew (`mesh.go:111`, `signHop` at 188). Verification is `homemap.go:1375-1419`. 3. The admission check (`admissionRefuses`) runs at 2068, **before any forwarding**. A box whose admission is closed answers the 503 itself and never forwards. 4. `routeHAIngress` (2095, `haingress.go:47-127`) applies the name authority and the memory-only ingress table. `frontForwardHAIngress` (`haingress.go:130-169`) can only forward or refuse. 5. Cross-region `backhaulTo` (2131/2166, `edge.go:4212-4237`). 6. `frontForwardHA` (2197, `forwardha.go:175-238`) is the in-region holder forward. It never forwards a verified hop, a door call, a tunnel delivery or a regional name (`forwardha.go:176-180`). 7. Hibernating routes then reach `act.ServeHTTP` at 2715. **Activator half of the decision:** `Service.forwardTarget` (`activator/haforward.go:126-169`): - "Serve here" (`here`, line 131) needs: entry for the same pool route, not retired, not probe-held, no error, not fenced, **`!a.shuttingDown`**, and the state is waking, or awake with a live process and a healthy lease. - Otherwise it consults the holder cache, or does one lock read (`holderReadFor`, 172-189, `holderReadTimeout = 2s` at 95). - `otherHolder` (243-252) counts only an unexpired HA lease owned by **another** box. A marker, an absent lock or this box's own lease all give "". - `decideForward` (192-237) then calls `DecidePlacement` (`haplacement.go:50`). This box as owner gives `base-self-owner`, so it serves here (line 78-79). - Forwarding goes through `forwardHAObserved` (`forwardha.go:273-330`): `boxInView` (`holderview.go:35-61`), then `hopTo` (`edge.go:4248-4287`) on `backhaulPort = "443"` (`edge.go:4154`). - `forwardDialTimeout = 2s` (`forwardha.go:143`). `holderHeaderSuspectAfter = 3s` without final headers reports `ForwardSilent` (332-372). - Outcomes go back through `NoteForward` (`haforward.go:261-301`). A holder that answers "unreachable" also calls `OnDepartureSuspect`. **Every HA-related 503 at the edge and activator:** | Answer | Where | Headers / body | |---|---|---| | `HAUnavailableResponse` ("holder none", the C1 copy) | `haingress.go:15-20` | `Retry-After: 10`, `X-Carlos-Holder: none`, marked answered, body "This instance cannot wake right now. Please try again shortly." | | ↳ called from | `forwardha.go:218` (`d.Unavailable`), `230` (not in view and not locally eligible); `haingress.go:96,105,109,119,132,136,141,149,154,161,166`; `regional.go:171,178`; `activator.go:6374` (pool-ineligible); `6534` (`ErrHALeaseUnavailable`, the lost-lease answer); `6540` (`ReasonPoolIneligible`) | | | `answerHolderUnreachable` | `forwardha.go:376-380` | `Retry-After: 10`, **no** `X-Carlos-Holder`, "instance is waking elsewhere; retry shortly" | | ↳ called from | `forwardha.go:222` (`d.Refuse`, holder suspect), `234` (placement hint not in view), `306` (waited out the dial queue), `312` (connect or TLS failure) | | | Admission refusal | `group_admission.go:31-37` (`admissionResponse`) | **Deletes** `X-Carlos-Holder`; `Retry-After: 10`, `Cache-Control: no-store`; "starting" or "unavailable" copy | | lb-health while admission is closed | `edge/lbhealth.go:36-46` | 503, `Retry-After: 10`, "Not ready to receive traffic." | | Holder answering a forwarded hop when the lease is held | `answerForwarded`, `haforward.go:311-327` | **`Retry-After: 1`** plus `X-Carlos-Holder: <owner ref>`. Any other refusal on a forwarded HA hop gets only `X-Carlos-Holder: none`, then the normal answer below | | `errLeaseHeld` (direct request) | `activator.go:6585-6589` | `Retry-After` = lease time left + 1 s (`leaseError`, `hawake.go:300-314`). Can be about 900 s | | `errLeaseRefused` | `6568-6577` | `Retry-After: 10` (`leaseRefusedRetryAfter`, `hawake.go:41`) | | `errWakeTimeout` | `6590-6593` | `Retry-After: 5` | | Stale-hop / backhaul cap | `homemap.go:1468-1470`, `edge.go:4315` | `Retry-After: 2` | **Lost lease (F-A):** - `haLeaseRefusalLocked` (`haleaseloss.go:93-128`) is purely local. It latches the loss through `latchHALossLocked` (60-84), which also calls `a.holders.drop(host)`. - The latch is checked in `begin` (`activator.go:1761`), `serve` (6436), and `forwardTarget` (129/134). `forwardTarget` returns `Unavailable` unless the loss is "foreign" and the cache names a holder (139-148). - Recovery: at most 4 workers, retry every 10 s, 2 s attempt budget (`haleaseloss.go:17-20`, `scheduleHALostHost` at 144, `recoverHALostHost` at 180). - "F-A" is a docs label only (`docs/superpowers/plans/2026-11-06-region-ha-g2-fixes.md:392`). It does not appear in code. **Activator holder cache** (`activator/hacache.go`): - Max 50,000 entries, oldest-set evicted first (`putLocked` 217-219). - Positive entry: 1 h. Negative entry: 10 s. Suspect: 10 s (lines 27-41). - `resolve` (270-341): one read in flight per host (single flight), bounded to 2× the read timeout. A suspect entry gets **one** re-read; only a release marker or an absent lock ends the suspect window early (`runRead` 358-363). - `peek` (253-268) serves memory-only callers. - Outcome rules in `holderResult` (438-511): - Not in view, `none`, or a 503 without a holder name: drop. - A header naming another box: set positive for 1 h. Naming self: drop. - Unreachable or silent: suspect. **Per-address dial gate:** `forwardDialGate` (`forwardha.go:463-517`). At most one TCP dial per holder address. A failure answers every waiter, and every new dial, until 2 s after that dial started. **Separate cross-region backhaul holder cache** (`edge/backhaul_holder.go`): - TTL 10 min, LRU of 50,000 (17-18). It learns holders from `X-Carlos-Holder` on a 503 (167-193). - It retries once, for bodyless GET, HEAD or upgrade requests only. - Suspect boxes stay suspect for 60 s (`backhaul_retry.go:10`). ## 2. Activator: waking, stopping, acquire table **Waiting on a wake:** - `begin` (`activator.go:1738-1927`) uses `wakeWaitBound = 30s` (1208), one timer per request, started at arrival. - `awaitWake` (1948-1969) returns `errWakeTimeout`, which becomes 503 with `Retry-After: 5` (6590). A planned first wake gets one extension, to `arrival + firstWakeBudgetFor(rt)`. - A failed wake hands `e.err` to every waiter (1900-1905). **Requests while the host is stopping on this box** (1908-1924): - The request waits on `e.stopped` or `e.haRefused` until the same 30 s deadline. - A `stopped` signal loops back and wakes the host afresh here. That acquire sees its own marker and takes it (`ActTake`). - `haRefused` (closed by the lost-lease latch) loops back and gets the immediate refusal. - The deadline gives `errWakeTimeout`. - During the stop, `forwardTarget` gives `here=false`. The lock read finds this box's own lease, so `DecidePlacement` says serve here, and the request queues in `begin`. **The release itself:** - `finishStop` (5204-5337) has a 30 s context (5256) and calls `releaseHAClean` (`harelease.go:171-239`) in this order: 1. host-slice emptiness 2. `stopFiles`, then files `Final` (budget 2 min) 3. replica `Finish` (30 s) 4. the local release record 5. the `ReleaseMarker` PUT (10 s) - Budgets are at `harelease.go:34-39`. During shutdown, `haReleaseContext` (241-261) caps each phase at the deadline minus 40 s, minus 10 s, and the deadline itself. - `e.stopped` closes only at 5332, after the marker write has returned. **A gap to note:** `errShuttingDown` (1262, returned at 1779) has no case in `serveWakeError`. It falls to `default` (6603-6611): 503 "instance failed to wake", **no `Retry-After`**, and it is logged as a wake failure. On a forwarded hop it also carries `X-Carlos-Holder: none`. **HA acquire table:** `hafresh.DecideAcquire` (`hafresh/acquire.go:77-115`), run by `lease.acquireHARestricted` (`lease/ha.go:75-165`, at most 3 conditional rounds): - **Release marker** (`v.Lock.Release != nil`, line 87): `ActTake`, a conditional If-Match write, generation + 1. `restoreHA` (`hawake.go:503-569`) keeps the local copy only when `hafresh.DecideKeep` says yes; otherwise it restores. - **Held, unexpired** (95-96): `ActHeld`, which becomes `HeldError` and then `errLeaseHeld`. Nothing is written. - **Expired, another box:** taken only with a termination proof (`decideOtherExpired`, 119-131). - **Expired, same box:** taken only with an emptiness proof. - "Owner in view" is not part of the acquire. It only matters at the edge: `boxInView` decides whether to forward. If the owner is out of view, the request is served here, which leads to `ActHeld` and a 503 with `Retry-After` up to about 900 s on a direct request, or `Retry-After: 1` plus the owner's ref on a forwarded one. - Refusal tracking for the page: `observeHARefusal` (`hasuspectholder.go:48`), which pages after 10 min. ## 3. Shutdown on SIGTERM 1. `edge.go:4849` `<-stop`, then `e.beginShutdown()` (`edge/shutdown.go:9-14`): - Fires `WithShutdownStarted`, which sets `shutdownDeadline = SIGTERM + agentShutdownBudget (90 s)` (`host/agent.go:1128`; `claimfilesseed_shutdown.go:10`). - Then `closeTenantAdmission` calls `fixedAdmission.Close` (`host/group_admission.go:208-239`). That clears `allowed`, closes the state, and calls `health.SetHosting(false)`. This is the "serving latch" clear. - From then on lb-health answers 503 with `Retry-After: 10`, and `admissionRefuses` answers every non-exempt request. - If `CARLOS_GROUP_ADMISSION` is unset, this is a no-op (`activator/group_admission.go:23-27`). 2. `closeDoor` (4852-4854). 3. **`httpsSrv.Shutdown` then `httpSrv.Shutdown`, sharing one 10 s context** (4855-4858). Listeners close immediately. In-flight handlers get up to 10 s. Hijacked WebSockets are not tracked. 4. Back in the agent: - `admission.Close()` again (`agent.go:1293`). - `departureLife.Stop`, up to 5 s (1294-1302). - `joinAgentShutdown` (`claimfilesseed_shutdown.go:12-39`): cancels startup, closes the seed server (up to 30 s), joins startup and duties (5 s). The base context is the 90 s deadline, further capped to now + 60 s if there is no seed server. 5. `svc.Shutdown(ctx)` (`agent.go:1315`, `activator.go:6127-6305`): - `CloseTenantAdmission`, set `shuttingDown` and `shutdownCtx`, cancel proofs and the service lifetime, join the lost-lease discovery workers, stop the sweeper. - Awake entries go to `beginStopLocked(StopShutdown)`. Waking entries are cancelled and joined. - It waits on every `stopped` with a 100 ms poll of `finishPendingStops`. Each stop releases with a marker through `finishStop`. - Then it waits on unproven wakes, owed releases and release operations until the context ends. Exit logs: `logHAUnreleasedAtExit` (6307), `logUnresolvedAtExit` (6335). **Ordering answer:** listeners close **before** any instance is slept. Instances are slept only after the HTTP drain (up to 10 s) and the agent joins (5-35 s). **What requests get in that window:** - A new connection to the box is refused. - An in-flight request in `begin` re-checks `TenantAdmitted` on each loop pass (1786) and gets 503 with `Retry-After: 10` "unavailable". - Peers forwarding to this box get connect failures. The holder becomes suspect, so peers answer 503 `Retry-After: 10` (unreachable). Each 10 s suspect window allows one lock re-read, and that re-read finds the marker once it is written (`hacache.go:358-363`). **Unit ordering:** in `carlos-edge.service`, `After=…carlos-instance-control.socket/.service dbus.service` and `TimeoutStopSec=120` (units/carlos-edge.service:15,32). `carlos-instance@` has `BindsTo/After=carlos-edge`, so on an edge restart, instance units stop before the edge. Spec §9.9 is at `2026-10-26-region-ha-without-claims-design.md:497-571`. ## 4. Edge-held SSE streams (#432) - Marked at `edge.go:1953`. Classified by `classifyHold` (2788-2807); dispatched to `serveHeld` at 2531-2544. - `serveHeld` (`heldstream.go:309-346`) and `heldTask.run` (441-537). - Defaults (`heldstream.go:47`): 64 per host, 4096 per box, MaxHold 1 h, Commit 2 s, LegHeader 10 s, WriteDeadline 10 s, Tick 25 s, ReopenSpacing 1 s, ShortLeg 30 s, BackoffCap 30 s, 5 short legs to close. - Legs are admitted by `AdmitHeldLeg` (`activator/heldlegs.go:61-84`). They **never wake** a host: a host that is not admissible is refused and the stream holds. - **How it learns the instance is up:** `SetHeldWakeHook(e.HeldWake)` (`host/agent.go:1204`), then `Edge.HeldWake` (`edge.go:2863`), then `heldSet.wake` (`heldstream.go:230`), then the stream's `wakeC`, then `scheduleReopen`. - The activator calls it on wake completion (`activator.go:2321`), a lifted fence (`maintenance.go:236,256`), a recovery probe (`recoveryprobe.go:315`), and pool withdrawal (`poolwithdrawal.go:288`). - Backstop: `HeldAdmissible` checked on every tick (`heldstream.go:528`). - All of this is **local only**. - **HA routes:** a non-holder box forwards a held stream from memory (`forwardha.go:194-213`). On a cold cache it calls `answerHeldRetry` (`edge.go:2826`), which writes 200 `text/event-stream` with `retry: 30000` (`heldstream.go:294-303`). - The ingress path does not do this: a cold memory miss there gives `HAUnavailableResponse` (`haingress.go:146-156`). - **No generic edge-side "hold while waking" exists.** The closest: - activator `begin` (30 s); - local upstream dial hold, 13 s dial / 30 s cap (`edge/localhold.go:12-19`, `retryLocalDial` at 83). It is used by the generation proxy (`genproxy.go:46`) and the prober hold (`prober.go:268-278`); - the client-side pending page (`pending.go`, `Retry-After: 5`, 90 s window) for unknown hosts. ## 5. Group admission, roles, lbhealth - `newFixedAdmission` (`host/group_admission.go:55-69`) is gated on `CARLOS_GROUP_ADMISSION=1` and needs `CARLOS_REGION_HA`. It starts in role `booting` with hosting false. - `bind` (70-80) wires `TenantAdmitted`, `TenantStartAllowed` and `TenantExempt` into the activator. Platform and unit routes are exempt only on non-group boxes (81-83). - Facts that must all hold: EnvLoaded, Reconciled, RolePublished, TerminationStarted (`groupadmission/state.go:9-13`). `Close` is permanent (47). - `tick` (133-193) sets hosting true and then calls `Admit`, which on group boxes completes the launch hook. - Roles (`boxroles/roles.go:23-26`): booting, serve, drain, platform. `Read` falls back from the box key to the region key to `serve` (53-71). The reader is `host/boxroles.go:53-89`, behind a change-index read gate on scope `control/box-roles`. - **`drain` exists only as a value.** - Group boxes treat any role other than `serve` as invalid (`applyRole`, group_admission.go:101). - On a fixed box, drain keeps `TenantAdmitted` true, so existing awake hosts keep serving, but `startAllowed` requires `serve` (116). New wakes therefore get `ErrTenantAdmission`, answered with the "unavailable" admission 503 (`activator.go:6543-6549`). - `EdgesRole` always reports drained = false (118-125). - Peers see role ≠ serve, or `draining`, as local-denied in placement (`edge/wakeplacement.go:41`). - Nothing actively empties a drain box. The `draining` flag in the edges file is described as "set while the placer empties this box" (`host/edgesfile.go:382`). - **lbhealth conditions** (`lbhealth/lbhealth.go:154-178`): hosting, forwarding (map and key loaded), certificates, an edge beat within 60 s (`Watch`, `edge.go:3435`), an activator sweep within 60 s, and a refresh within 5 min. Served on `:80` (`edge.go:3346`). - `SetHosting` callers are only `group_admission.go:60,163,220` and `group_hairpin_retry.go:59,96`. The spec's `claimwiring` caller is gone, so with group admission off nothing sets hosting true. ## 6. The roll script and group-maintenance **`scripts/region-group-roll.py`** (docstring 1-54) is an in-place binary update, not a replacement. Sequence (line 105): "Prepare, lower minimum, enter Standby, verify deregistration, permit, apply, verify, return, restore minimum, revoke." - Preflight (917-942): min = desired = max = N ≥ 2, and every peer InService and healthy in both target groups. - `standby` (1093-1098): the member is in Standby, min = desired = N-1, and deregistered. - `mutation` (1157-1200) runs `group-maintenance apply` over SSM. - Return: `return_member` (1359), the only place ExitStandby is sent. - It never terminates a member (line 33). `close-lost` (1049-1070) only records a member that was already lost. - **It never looks at leases or lock.json** (grep shows no lease logic). Its only readiness checks are health, admission and role (`readiness`, 888-915). **`carlos system group-maintenance`** (`host/group_maintenance_verbs.go:21-50`, `run` 93-192) has the verbs `status|permit|revoke|prepare|apply|rollback`. `apply` runs the normal system apply, which restarts instance-control and then the edge (`systemapply.go:697-703`). Leases are released only through that SIGTERM path (item 3). **"Replace only lock-free members" (DR-4):** not in code or docs. DR-4 in the repo means T1 planned termination: release markers written during shutdown, and "no ASG termination lifecycle hook" (spec:557; plan `2026-11-08-region-ha-graceful-terminate.md`). ## 7. Learning about another box's lease change - **Change index scopes** (`release/changeindex.go:55-90`): `apps/<a>/<b>`, `accounts/<a>`, `control/certs`, `control/edges`, `control/box-roles`, `system/managed-fleets.json`, `control/demo-moved.json`. - `lock.json` lives in the data bucket and is written by the lease or litestream client, so **no scope ever moves on a lease change**. - **Edges file per-host entry** (`host/edgesfile.go:51-117`): role, platform, alias, replica, wildcard, account, app, stamp, incarnation, serving_seq, target_host, assets. - Box level: box_role, admitted, drained (280-282), draining (382), headroom with an aggregate `awake` count and a per-app `apps` map (179-187), and generation. - **No per-host awake or holder field.** Peers poll it every 30 s (`homemap.go:124`). - **Push channels that exist today:** - (a) The `X-Carlos-Holder` header on a forwarded answer, piggybacked on request traffic. - (b) **Probe-burst notices** (`edge/burst_notice.go:28-60`): signed and sealed with the mesh key, POST to `/.carlos/burst-notice` with `X-Carlos-Burst-Auth`, a 64-deep queue and goroutine per peer, 120 per minute per box, dropped after 10 s, opt-in through the edges file's `burst_notices` flag, answered ahead of routing (`edge.go:2037`). This is the ready-made template for an "I released H" notice. - (c) Hop signing (`signHop` / `verifyHopEitherKey`) over `backhaulPort = 443`. - (d) The SQS terminations queue (`awsterminations/queue.go`, `hadeparture.Consumer`). These are cloud events, not box-to-box messages. - (e) `OnDepartureSuspect`, which runs on the box that saw the forward fail (`haforward.go:298-300`, `host/hadepartures.go:269`).</result> <usage><subagent_tokens>286254</subagent_tokens><tool_uses>86</tool_uses><duration_ms>557222</duration_ms></usage> </task-notification>
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..dd66bd074 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, for Paul's approval; 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,173 @@ 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. |
| + |
| +### 25.1 What happens today |
| + |
| +T1/DR-4 (§9.9) writes a clean release marker about 3 s after `TerminateInstances`. The requests around it still fail, for three reasons in the code: |
| + |
| +1. **The listeners close first.** On SIGTERM the edge closes admission (`beginShutdown`, `internal/edge/shutdown.go:9-14`), then runs `http.Server.Shutdown` on both listeners with one 10 s context (`internal/edge/edge.go:4855-4858`). Only after that, and after the agent's joins, does `Service.Shutdown` (`internal/activator/activator.go:6127`) stop instances and write markers. A new connection to the dying box is refused for the whole release. |
| +2. **Peers treat that as a dead holder.** A refused dial makes the holder suspect (`internal/activator/hacache.go:27-41`, `holderResult` 438-511). Each forward answers 503 with `Retry-After: 10` (`answerHolderUnreachable`, `forwardha.go:376-380`). One lock re-read per 10 s suspect window finds the marker (`runRead`, `hacache.go:358-363`), so a host is down for up to about 10 s after its marker, plus its restore. |
| +3. **The dying box refuses its own clients.** A request already inside `begin` sees admission closed and gets 503 `Retry-After: 10` (`activator.go:1786`). A request for a host that is stopping waits on `e.stopped`, then tries to wake the host again here and gets `errShuttingDown`. That error has no case in `serveWakeError` and answers 503 "instance failed to wake" with no `Retry-After` (`activator.go:6603-6611`). This is a bug today, whatever this section decides. |
| + |
| +The flagship A5 drill (2026-11-08, before T1 reached the boxes) saw the unplanned shape: 503 from the next second until lease expiry +8 s. With T1 the planned shape is shorter, but it is still a run of errors per awake host. |
| + |
| +### 25.2 The model |
| + |
| +A planned handover moves each awake host from the departing box A to another serving box, and every request that arrives meanwhile **waits at the box whose edge accepted the client's connection** (the *first box*). The first box can be a group member, a fixed forwarder such as adi, or A itself for clients already connected to it. The first box keeps the request, its body and the client's connection until the host's new holder is known, then forwards it once, as §6.4 allows. Nothing is replayed that may have reached A's app. |
| + |
| +Three rules carry over unchanged: |
| +- **I1.** Only the release marker lets another box acquire (§9.4). Nothing in this section authorizes an acquire. A notice (§25.4) is advice, so a box that acts on one still reads the lock and makes the conditional write. |
| +- **"Takeover only after proof and expiry"** stands for every lease that has no marker. A planned handover that fails to write a marker falls back to it, and so to today's 503s. |
| +- **F-A.** A box that has lost its lease answers 503 `Retry-After: 10` with holder `none` at once, as today. A lost lease is never a handover, and a first box never holds on that answer. |
| + |
| +### 25.3 The departing box |
| + |
| +When SIGTERM arrives on a box with `CARLOS_REGION_HA`, the agent enters **handover mode** for at most the shutdown deadline D (SIGTERM + 90 s, §9.9). The order in shutdown changes as follows: |
| + |
| +1. **Announce.** The box closes tenant admission for new wakes and clears the serving latch, as today, so lb-health turns 503 and the box stops taking leases. It publishes no edges change. It sends a **departing notice** to every box in its view of its region (§25.4). |
| +2. **Keep the listeners open.** `http.Server.Shutdown` moves to the end of handover mode. Until then the edge accepts connections and answers: |
| + - a **forwarded hop** for a host awake or stopping here: 503 with `X-Carlos-Handover: pending`, written by the edge before the request reaches the activator or the app (§25.6). The header means the request was not delivered; |
| + - a **direct request** for such a host: held here, as on any first box (§25.5); |
| + - a request for any other host: routed as from any first box. This box is no longer a placement choice for anything, because its admission is closed. |
| +3. **Finish in-flight work, bounded.** For each awake host, requests already admitted to the app may run for up to 10 s, the same bound as today's HTTP drain. Edge-held stream legs are cancelled first (#432 G5). Long requests and hijacked WebSockets still running at 10 s are cut, as they are today; their clients reconnect and the reconnect is held like any request. |
| +4. **Release.** Every awake host is stopped and released in parallel, as `Service.Shutdown` does today, with the §9.9 budgets. Nothing about the marker changes. |
| +5. **Hand over.** As each host's release returns, the box picks a **successor**: `ChooseRoomiest` over its cached eligible serving set without itself (§6.3), or the HRW box for an always-on worker (A10). It then: |
| + - sends a **released notice** to every box in its view of the region, naming the host, the marker's generation and the successor; |
| + - forwards the requests it holds for that host to the successor, which acquires from the marker and wakes (§25.5); |
| + - when it holds no request for the host, sends the successor a **wake notice** if the host had a request in the last 60 s or is an always-on worker. The successor treats a wake notice as a forwarded wake with no body (§6.4): HA acquire, then wake, never forward. |
| + |
| + A host whose release ends without a marker (S3 down, stop proof failed, deadline) gets a released notice with `marker: none`. Its held requests get today's answer, 503 `Retry-After: 10`. |
| +6. **Close.** When every host is handed over and every held request is answered, or at D - 10 s, the edge runs `http.Server.Shutdown` with what remains of the deadline. Then the process exits as today. |
| + |
| +The successor is a hint. If two boxes race, for example a first box that read the marker itself, the conditional PUT picks one winner and the loser forwards to it (§6.7). |
| + |
| +**Restart on the same box.** In a roll (§25.8) the box restarts its edge in Standby. Its markers name it, so placement rule 1 (§6.3) sends a later cold wake back to it once it serves again. Hosts that were handed over stay on their successor until they sleep. |
| + |
| +### 25.4 Notices |
| + |
| +Notices reuse the probe-burst notice transport (`internal/edge/burst_notice.go:28-60`): a POST over the backhaul port, sealed and signed with the mesh key, from one goroutine per peer with a bounded queue, and answered ahead of routing. A notice gets a new path, `/.carlos/ha-notice`, and its own rate bound. It is opt-in through a new additive edges field, `ha_notices: 1`, so a box sends notices only to peers that publish it. |
| + |
| +| Notice | Fields | The receiver | |
| +|---|---|---| |
| +| departing | box ref, instance id, deadline | marks the box *departing* in its holder cache until the deadline. A failed dial to a departing box means "handover", not "suspect". | |
| +| released | host, marker generation or `none`, successor ref | sets its holder entry for the host to the successor (positive, as an `X-Carlos-Holder` answer would) and releases its held requests for the host (§25.5). With `marker: none` it answers them as today. | |
| +| wake | host, marker generation | runs the HA acquire for the host and wakes it, as for a forwarded wake. It is only sent to the successor. | |
| + |
| +A receiver validates every ref against view(region) (§4.3) and drops a notice from a box not in view. **A notice never authorizes anything:** an acquire still reads `lock.json`, and a holder named by a notice is a cache entry like any other (§6.6). |
| + |
| +Notices are best effort. A lost released notice costs time, not correctness, because the first box falls back to the lock (§25.5). A released notice is sent once per host. Notices travel in batches of up to 200 hosts per POST per peer, sent at most every 200 ms. |
| + |
| +### 25.5 The first box: holding and releasing |
| + |
| +A request is **held** when the first box would otherwise answer it 503 for one of these reasons, and only these: |
| +- a forward got `X-Carlos-Handover: pending` (§25.3 step 2); |
| +- a forward to a box marked departing failed to connect (§25.4); |
| +- on the departing box itself, a direct request for a host awake or stopping there. |
| + |
| +Everything else answers as today: a lost lease (F-A), `HAUnavailableResponse`, a held lease of a box not departing, admission refusals, and every refusal for an unplanned death. |
| + |
| +**Where it waits.** In memory on the first box, in a per-host queue. A held request keeps its client connection and its buffered body (below). The box answers nothing until the host is released. |
| + |
| +**What releases it,** in order of preference: |
| +1. a released notice for the host, which names the successor: forward every held request for the host to it; |
| +2. on the departing box itself, its own release of the host (§25.3 step 5); |
| +3. a **fallback lock read.** If no notice has come 2 s after the first hold for the host, the box reads `lock.json` once for the host, coalesced (one read in flight per host, as `resolve` does today, `hacache.go:270-341`). It retries at 4 s and 8 s from the first hold. A release marker sends the held requests through the normal §6.2 decision: the box acquires and wakes the host itself, or forwards to the §6.3 choice. An unexpired lease of a box in view sends them there. A held lease of the departing box keeps them waiting. Any other answer gives today's response. |
| + |
| +A released request is forwarded at most once, to one box, and the receiver never forwards it again (§6.4). If that forward fails, the request gets today's answer for that failure. A held request is never held twice. |
| + |
| +**Bounds.** The constants are the builder's to tune; the shapes are not. |
| + |
| +| Bound | Value | When exceeded | |
| +|---|---|---| |
| +| Time held, from the first refusal | 15 s | today's answer: 503, `Retry-After: 10` | |
| +| Held requests per host | 64 | the new request gets today's answer | |
| +| Held requests per box | 1,024 | the same | |
| +| Buffered body per request | 1 MiB | the request is not holdable (below) | |
| +| Buffered bodies per box | 64 MiB | the same | |
| + |
| +The departing box applies the same bounds and stops holding at D - 10 s. |
| + |
| +**Which requests may be held.** A request may be held only when the first box can prove it was not delivered and can send it again exactly as received: |
| +- **Not delivered.** Either the first box has not sent it anywhere, or the answer it got was `X-Carlos-Handover: pending`, or the connection failed before it was established (TCP or TLS). A failure after the connection was made proves nothing. Then only a GET, HEAD or OPTIONS with no body, or an upgrade that has not switched protocols, may be held. That is A9's rule (§6.5). Everything else gets 502 as today. |
| +- **Replayable.** A request with no body qualifies. So does one whose whole body the first box has buffered, up to 1 MiB (Content-Length, or chunked ending within 1 MiB). Only HA forwards buffer: the edge tees the body into a bounded buffer as it sends it, so the first send streams as it does today. A body over the limit, or a client that has not finished sending, makes the request unholdable, and it gets today's answer. |
| +- **Methods.** With both conditions met, every method may be held, POST and PUT included. The pending answer is written before the request reaches A's activator, so the app never saw it. |
| +- **WebSockets and upgrades.** An upgrade that has not switched protocols may be held, since it has no body. An established WebSocket on A is cut at the step 3 bound, as today. The client's reconnect is held like any request. |
| +- **Edge-held SSE streams (#432).** A marked held-stream request is held like a GET, and it never wakes a host. On release it is forwarded to the successor from memory. If the successor is not running the host, the successor holds the stream as #432 already does for a sleeping host. A's own held streams close when A's edge exits, and the browsers reconnect. |
| +- **T6-b.** Today a marked request on a forwarding box with a cold holder cache gets `retry: 30000` (`forwardha.go:194-213`). During a handover, the released notice puts the successor in every peer's cache, so reconnecting streams find it from memory and do not get the retry. The general cold-cache case, a box that learned nothing, stays the open #432 follow-up. This section does not add a lock read on the held-stream path. |
| +- **Cross-region first boxes.** A box in another region that forwards to A (backhaul) is a first box too. It honours `X-Carlos-Handover: pending` and holds. It receives no notices (it is outside view(region)), and a foreign region's lock is never read (§6.1). So it releases by retrying: at 2, 4 and 8 s from the first hold, one hop through `backhaulTo` to a box of the region in its view other than A. That box answers as §6.4 says: it acquires from the marker and wakes, or serves, or refuses with a holder it names, which the first box tries once (§6.5). When the bound runs out, the answer is today's. |
| + |
| +**The header.** `X-Carlos-Handover` is honoured only on an answer to a hop this box sent over its verified transport (`forwardTransport`, TLS to the box's name). It is stripped from app responses at the tenant boundary, as `X-Carlos-Holder` is (`stripAppHolder`, `forwardha.go:118-128`). |
| + |
| +### 25.6 What clients see |
| + |
| +- **Within the bounds:** the request completes after a pause. The pause is the rest of A's in-flight drain for that host (up to 10 s, usually milliseconds), plus A's release (about 3 s, §9.9), plus the successor's acquire and restore. The target is under 5 s for a small host. Responses carry no new header. |
| +- **A bound hit, or a failed handover:** today's 503 with `Retry-After: 10`, and the C1 copy. |
| +- **An unplanned death:** today's behaviour, unchanged. |
| + |
| +### 25.7 Interactions |
| + |
| +- **Takeover after proof and expiry** (§9.4, N-HA9) is untouched. Holds only wait for a marker. A host left without a marker is down until expiry plus proof, as today. |
| +- **F-A** is untouched. A lost-lease answer is never held, and a box that has lost a lease sends no released notice for it. |
| +- **DR-4's replacement rule** ("replace only lock-free members") becomes obsolete for a group whose members all run the release with §25, through every path in §25.8. Until then it stays in every card. The roll and replace tools check the floor per member (§25.8). |
| +- **The NLB deregistration delay** (30 s, `infra/modules/region-host/ingress/main.tf:105`) works in our favour. When the group terminates a member, it deregisters it from the target groups and waits for the delay before EC2 terminates it. The member then gets no new flows, still holds its leases and serves forwards normally. SIGTERM comes after. In Standby the member is already deregistered when the roll restarts its edge. |
| +- **Drain** (§13 step 2): handover mode is the same work as draining a box, but compressed into the shutdown deadline. The role `drain` is not needed for these paths. §13's retirement drain, which sleeps instances one at a time without a deadline, can reuse §25.3 steps 3 to 5 per host later. It is not part of this slice. |
| +- **Litestream #284 and restore time.** The pause includes a restore on the successor. A large database makes the pause longer than 15 s, and then the client gets today's 503. The witnesses measure restore time per host size (§25.10). |
| +- **Box-local caches.** The successor's edge asset cache is cold for the host. That is a speed cost, not an error. |
| + |
| +### 25.8 The three paths, end to end |
| + |
| +**Planned terminate, scale-in and member replacement.** `scripts/region-group-roll.py` gains a `replace` transaction. Today the script only does in-place rolls and never terminates (docstring 1-54). The transaction: |
| +1. preflight as for a roll: min = desired = max = N ≥ 2, every member InService and healthy in both target groups, and every member's published version at or above the §25 floor (otherwise it refuses and names the member); |
| +2. `TerminateInstanceInAutoScalingGroup` on the member, without decrementing desired, so the group launches its replacement at once. For scale-in, the operator first lowers the module's `box_count` through tofu as today; the tool is not used; |
| +3. watch: the departing member's journal lines for handover mode (hosts handed over, held requests, holds that hit a bound, hosts without a marker), the departure finishing (§7.5's bound), the replacement admitted and healthy in both target groups, and every lock that named the departed ref now a marker or another owner; |
| +4. report, then allow the next member. |
| + |
| +Capacity dips to N - 1 for the 2 to 3 minutes the replacement takes. With N = 2 the survivor carries every host for that time; wakes are never refused for headroom (A20). A surge replacement (launch first, then terminate) needs maximum raised by one, which N-HA14 does not allow. That is open question Q1 (§25.12). |
| + |
| +**Roll.** The existing Standby transaction. Its `apply` step restarts the edge (`systemapply.go:697-703`), and that SIGTERM runs handover mode. The member is already deregistered, so its direct clients are only the keep-alive connections the delay did not end. The tool adds the floor check to its preflight and the handover lines to its verify step. |
| + |
| +**Resize.** The operator sets `instance_type` in the region's group module and applies, which creates a new launch template version. The re-pin then sets `group_launch_template_version` to it, as for a release re-pin. Then `replace` runs once per member, one at a time. Every replacement launches on the new type. The operator sees a tofu plan with one launch template version and no instance change, then one `replace` report per member. Each report gives hosts handed over, the longest hold, holds that hit a bound (target 0) and the departure time. |
| + |
| +### 25.9 Request budget (§18) |
| + |
| +- **Steady state:** unchanged. Nothing here polls. The `ha_notices` field rides the existing edges publication. |
| +- **Per planned departure:** one departing notice per peer. No S3. |
| +- **Per host handed over:** the marker PUT, as today; one released notice per peer, batched; and on the successor the acquire (1 GET + 1 PUT) and restore that the host's next wake would have cost anyway. A wake notice brings that wake forward. |
| +- **Fallback lock reads,** only when a released notice is lost: at most 3 GETs per host per first box per handover. |
| +- **Example:** a 4-member region replacing all members, 200 awake hosts in all: about 200 marker PUTs and 200 acquires (as any sleep and wake), 2,400 notices in about 50 POSTs, and no fallback reads if no notice is lost. That is about $0.002 in S3 requests. |
| + |
| +### 25.10 Tests and witnesses |
| + |
| +**Simulation (§21.1).** It adds planned terminations, notices that are lost, delayed and reordered, held requests with and without bodies, and connection failures before and after a request was sent. New invariants: |
| +- **I9, no unsafe replay.** No request reaches two apps' handlers. A request whose first send may have been delivered is never sent again unless it is a bodyless GET, HEAD, OPTIONS or upgrade. |
| +- **I10, bounded hold.** Every held request is answered within its bound plus one forward. |
| +- I1 still holds with notices. Mutations that must fail the sweep: a notice authorizes an acquire; hold after a post-connect failure for a POST; hold on a lost-lease answer; a held request forwarded twice; the departing box closes its listeners before its releases. |
| + |
| +**Unit and integration tests.** The pending answer comes before the activator for every route kind; the header is stripped from app responses; the body tee and its bounds; the notice seal and its validation against view(region); the fallback read is coalesced; and `errShuttingDown` gets a real answer. |
| + |
| +**Root runner.** `TestRootHAHandoverHold` extends `TestRootHATerminateRelease`: two real agents, real `TerminateInstances`, and a client driving GET, POST with a body, and SSE through the survivor and through the departing box during the terminate. It asserts 0 non-2xx, every hold within its bound, and every acknowledged write present after. |
| + |
| +**Dev witnesses,** one per path, each with a probe at about 3 requests a second (GETs, POSTs that write and an SSE stream) on two HA hosts awake on the member being replaced: |
| +- **W1 planned terminate** of a lease-holding member: 0 non-2xx, the longest hold under 5 s, 0 acknowledged writes lost, an SSE gap under 5 s, and the departure finished within §7.5's bound. |
| +- **W2 roll** of a lease-holding member through the Standby transaction: the same. |
| +- **W3 resize** (t4g.small to t4g.medium) of both members with `replace`, one at a time: the same per member, and both members on the new type. |
| +- **W0 control:** a hard kill (`SIGKILL` of the agent, then terminate) still gives today's 503 with `Retry-After: 10` until expiry plus proof. |
| + |
| +### 25.11 What a self-hosted fleet needs (Tito) |
| + |
| +- **Version floor:** a release with T1/DR-4 (v0.34.27), DR-5 (v0.34.28) and §25, on every box of the region, the console included. The console must be current main; a forked console is not supported. |
| +- **Shape:** the nested layout; the region in group mode (`infra/modules/region-host`) with its NLB, launch hook, termination queue and rule; `CARLOS_REGION_HA` and `CARLOS_GROUP_ADMISSION` on the members; chrony. |
| +- **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, created in that pool after switch-on (N-HA7). Instances that exist today need the operator migration slice, which is not built. Until then a resize is still the old way for them. |
| + |
| +### 25.12 Open questions for Paul |
| + |
| +- **Q1. Surge replacement.** `replace` terminates first and lets the group launch the replacement, so capacity dips to N - 1 for 2 to 3 minutes. Launching first needs a second N-HA14 exception: raise maximum and desired by one for the transaction. Recommendation: terminate first now; surge later if a 2-box region's survivor runs short. |
| +- **Q2. Wake notices.** §25.3 step 5 re-wakes a host on its successor if it had a request in the last 60 s, so the next visitor does not pay the restore. It costs extra awake time for hosts that were about to sleep. Recommendation: keep it. |