spec: region HA without claims, N-box regions behind a load balancer (rev 1)
Supersedes the claim-dependent parts of region HA spec 2 (rev 21). The Litestream S3 lease is the only single-writer guard (N-HA1). Covers wake freshness against the S3 head, holder forwarding, takeover of a terminated box's leases by EC2-confirmed conditional write (N-HA3), load balancer health without the claim, files sync (H6), retiring the old box (N-HA2), plan 2c infra and boot, the 2d rows, the R3 deletion list, request budget, rollout and a seeded simulation.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+615
−0
docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md+615 −0
CI failed — run details
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| new file mode 100644 |
| index 000000000..8fd1e6c30 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md |
| @@ -0,0 +1,615 @@ |
| +# Region HA without claims: N-box regions behind a load balancer |
| + |
| +Design, 2026-10-26, **rev 1**. Branch `design-region-ha-no-claims`, cut from `origin/main` at ddf3b929. Status: draft for review. 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**). §15 lists what it reuses from S2, plan 2a (6834659c) and plan 2b (b1118925), and gives claims-cleanup step R3 its exact deletion list. New plans start from this document. |
| + |
| +Line citations are to this worktree unless they name a module path. |
| + |
| +## 1. Intent |
| + |
| +Part 1 of two: **a region's load balancer keeps serving when one box is killed.** The target is carloku.com's regions (IE, UK, US, AU), dev first. Each region runs a fixed-size group of N boxes, N ≥ 2, behind one Network Load Balancer. When a box dies, its instances come back on the others within a few minutes, and lose about the last second of writes. |
| + |
| +Out of scope: |
| +- Part 2: spreading stateless replicas of one app across boxes. |
| +- Autoscaling beyond a fixed-size group. |
| +- Cross-region failover (#251). |
| +- Live moves (parked with the claims). |
| +- Kubernetes or k0s. Considered and rejected: two boxes cannot run an HA control plane, and it would replace the box runtime and change the self-hosted product. |
| + |
| +## 2. Rulings |
| + |
| +### 2.1 Paul's rulings |
| + |
| +These stand from spec 1 and spec 2. They are not reopened here. |
| + |
| +| # | Ruling | |
| +|---|---| |
| +| H1 | A box is dead when its Auto Scaling group has terminated it. | |
| +| H3 | About 1 s of data loss on failover, stated plainly. | |
| +| H4 | Place on the box with the most capacity. Spread an app's instances where possible. If nothing qualifies, unplaced and alert. | |
| +| H5 | The per-region minimum box count is configurable: 1 by default, 2 where HA is sold. Scale-in only after drain. | |
| +| H6 | Files durability follows the paid plan: continuous sync on the top plan, snapshots on the bottom one, as a per-app platform setting. `instance.key`, `report.token` and `<host>.env` always sync continuously. | |
| +| H20 | The first HA release recovers hung boxes as well as lost ones. Each region's boxes run in a fixed-size Auto Scaling group with health checks. | |
| +| H21 | One Network Load Balancer per region, TCP passthrough on 80 and 443, created with the region's existing EIP so customer DNS is unchanged. | |
| +| H22 | Every region runs the group, dev first. | |
| +| H24 | IE's current box becomes a fixed platform box outside the group, with no tenants (console, keymail, relay, scanner), and its own EIP for the relay and MX. | |
| +| Roll order | Dev boxes, then the dev console, then a check, then flagship boxes, then the flagship console. | |
| + |
| +New on 2026-10-26: |
| + |
| +| # | Ruling | |
| +|---|---| |
| +| N-HA1 | HA is built **without claims**. The Litestream S3 lease is the only single-writer guard. | |
| +| N-HA2 | Replaces H25. Each region's existing box is not kept as a third box. Once every instance's DB and files are in S3, the old box joins the load balancer as an ordinary member. Its instances are put to sleep one at a time and wake on the group boxes, a few seconds down per app. The old box is removed once empty. IE's platform box (H24) stays outside the group. | |
| +| N-HA3 | Failover is "a few minutes, lower is better", met **without shortening every lease**, because of S3 request cost. Once EC2 confirms a box is terminated, a survivor takes over its leases at once. | |
| + |
| +### 2.2 Author's calls |
| + |
| +Each is mine, with the reason. Paul can overturn any of them. |
| + |
| +| # | Call | Reason | |
| +|---|---|---| |
| +| A1 | The freshness rule (§5) runs on every wake, on every box, with no switch. | It costs one LIST and one GET per warm wake, and it makes single-box regions and dev's existing two IE boxes safe too. | |
| +| A2 | A local database copy is kept only when it equals the S3 head or provably extends it. Anything else is set aside and restored. | S3's head is the only shared truth. Keeping a proven extension preserves today's behaviour after an agent crash. | |
| +| A3 | The lease owner string becomes `box/v1;ref=<ref>;iid=<instance id>;pid=<pid>`. Only that shape is ever taken over. | Litestream's default owner is `hostname:pid`, which does not name the EC2 instance. | |
| +| A4 | Boxes confirm terminations themselves, from the existing queue and `ec2:DescribeInstances`. No console role, no regional election. | The box role already holds both rights. The console is one box in IE. | |
| +| A5 | Takeover is per lease, at the first need after confirmation: a request, a duty, a tick. There is no bulk pass. | Nothing publishes a cheap list of a box's leases, and the first need comes within seconds. | |
| +| A6 | The box that confirms a termination deletes the dead box's edges file, after copying its due entries into its own. | One conditional delete drops the dead box from every box's view through the change index. | |
| +| A7 | A box learns a lease holder from the lease itself (the held error's owner) and from a peer's 503 header. Awake sets are not published. | Zero steady-state requests. Publishing on every wake would make every box re-read every edges file. | |
| +| A8 | A cold wake happens on the receiving box when it is eligible. Otherwise it is forwarded to the roomiest eligible box. Spread uses what the receiving box knows locally. | No extra hop in the common case, and H4 applied within what a box can see. | |
| +| A9 | The receiving box may forward a second time, to the holder a 503 names, for a GET or HEAD with no body. A forwarded request is still never forwarded again. | Removes most stale-cache bounces without a new hop protocol. | |
| +| A10 | Work with no request behind it (always-on starts, schedule ticks, due wakes) goes to the host's rendezvous-hash owner among the region's serving boxes. Delivery is routed to the lease holder. | One actor per duty, which is what the activator's mesh seam already describes (`activator.go:5025-5028`). | |
| +| A11 | A write fence: the lease package refuses every replica and files write once its own lease is unhealthy or past its safe deadline. | A box frozen past its lease must not write after a survivor took over. | |
| +| A12 | Box roles `serve`, `drain` and `platform` are control objects set through an operator console door, with their own change-index scope. | Replaces plan 2a's roster roles. One read per change, no polling. | |
| +| A13 | The platform box adopts tenant records but never wakes a tenant (it forwards), and it is not a load balancer target. | The console's local-registry reads keep working, and tenant health never depends on the platform box. | |
| +| A14 | Region membership is "a verified box with a fresh edges file in this region". Auto Scaling membership is not an input, and nothing is enrolled. | The group is only the replacement mechanism. Enrolment was the claim's. | |
| +| A15 | `CARLOS_REGION_HA` stays the box switch, redefined claim-free, once the claim-bound code under it is deleted. | It already gates the claim-free plan 2a parts (private dial, load balancer health). | |
| +| A16 | A box may take over its own lease after an agent crash, once the host's process group is proven empty. | Same primitive. It closes today's 15-minute stall after an agent crash. | |
| +| A17 | Files sync is plan 1a's `hostfiles`, under the instance's hibernate prefix with one fixed generation, fenced like the replica. | Plan 1a's code, without the claim's generations. | |
| +| A18 | Spec 1's H7 (ticks are at-least-once) and H8 (`files_durability` defaults to `snapshot`) carry over. | Both are claim-free and still the right defaults. | |
| +| A19 | The old box drains before the EIP cut-over, not after. | It keeps its address while its instances move, so nothing needs a temporary address. | |
| +| A20 | The no-capacity refusal (S2's H27 form) applies at create only. A wake is never refused for headroom. | An existing instance down is worse than an overfull box, and the alarm covers the box. | |
| + |
| +## 3. Model |
| + |
| +Every box in a region adopts every host record of its region, as today (`internal/provision/reconcile.go:443-457`). An instance has no home box. It runs on whichever box holds its Litestream lease, and only there. A box that receives a request for a host it is not running either takes the lease and wakes the host, or, if another box holds the lease, forwards the request to that box once. Before a box trusts its local copy of a database or files directory, it checks that copy against S3. When a box is terminated, the first survivor that needs one of its leases confirms the termination with EC2 and takes the lease over by a conditional write. A hung box is never taken over: the group terminates it, and then it is. Work with no request behind it is done by one box per host, chosen by a hash over the region's serving boxes. One load balancer per region sends traffic to any healthy box. |
| + |
| +## 4. Identity, lease owner and the region view |
| + |
| +### 4.1 Box reference |
| + |
| +Fixed boxes keep their status label. Group boxes use the group reference, `g-` plus a hash of account and instance id (`internal/host/boxreference.go`, `GroupBoxReference`; claims-cleanup R1 moves it into `internal/host`). Each box publishes its signed identity record, `control/boxes/<ref>.json` (`internal/boxid/record.go:21-35`), at agent start when `CARLOS_REGION_HA` is on (`internal/host/boxrecord.go:163`). |
| + |
| +### 4.2 Lease owner |
| + |
| +Today the owner in `lock.json` is litestream's default, `hostname:pid` (`litestream@v0.5.14/s3/leaser.go:52-65`). Carlos never overrides it; `createLease` copies it (`internal/lease/createlease.go:32`). An EC2 hostname does not name the instance, so no survivor could map a lock to a machine. |
| + |
| +The lease package sets `Owner` to `box/v1;ref=<box ref>;iid=<instance id>;pid=<agent pid>`. The instance id comes from the identity document the agent already reads for its identity record (`boxrecord.go:65-112`). |
| + |
| +- The parser is strict. Any other shape is never taken over and waits out its expiry, as every lease does today. That covers old binaries' `hostname:pid`, offline-move tombstones (`moved:<id>`, `internal/lease/tombstone.go:45-47`) and anything garbled. |
| +- A box with no instance id (off AWS) writes no `iid`, so its leases are never taken over. |
| + |
| +### 4.3 The region view |
| + |
| +A box's **view** of its region is the set of boxes whose edges file (`control/edges/<ref>.json`) is no older than 15 minutes, the existing placeable bound (`internal/boxchoice/policy.go:16-83`), with the same region, placement, data bucket and secrets-key fingerprint. Every box already folds every edges file (`internal/edge/homemap.go:464-527`, `:791-867`), so the view costs nothing new. |
| + |
| +The **serving set** is the view minus boxes whose role is `drain` or `platform` (§4.4). The console also verifies each box's identity record, as `internal/console/boxselect.go:147-174` already does without a roster. |
| + |
| +### 4.4 Box roles |
| + |
| +A role object, `control/box-roles/<ref>.json` (`{role, by, at}`), holds `serve`, `drain` or `platform`. Absent means `serve`. A region default, `control/box-roles/@region-<code>.json`, applies to every box of that region with no object of its own, so a replacement launched during a rollback comes up with the region's role. |
| + |
| +- Written only by an operator, through `carlos system box role <ref|@region-code> serve|drain|platform` and its console door. These replace plan 2a's `system_roles.go` and `internal/console/apiboxroles.go`, which wrote the roster. |
| +- `ChangeScope` gains `control/box-roles` (`internal/release/changeindex.go:53-76`). A box reads its own object, and its region's, at start and whenever that scope moves. |
| +- A box publishes its effective role in its edges file, in a new additive field `role`. Readers that do not know the field treat the box as `serve`, which is what every box is today. |
| + |
| +## 5. Wake freshness |
| + |
| +### 5.1 The hazard |
| + |
| +`restorePlain` keeps any database file it finds on disk (`internal/activator/backend_exec.go:819-820`). The comment at `internal/activator/activator.go:2302-2310` says this is safe only while a region has one box. |
| + |
| +With N boxes, box A can wake a host from a copy older than what box B wrote since. It then serves stale data. Worse, litestream starts uploading from the replica's position, which it reads from S3 (`litestream@v0.5.14/replica.go:208-215`, `:170-176`). A local database behind S3 uploads nothing until its own transaction id passes the replica's, and then writes a different history under transaction ids S3 already holds. |
| + |
| +### 5.2 The rule |
| + |
| +It runs under the lease, after `Acquire` and before `Replicate`, where `restorePlain` runs now (`activator.go:2311`). |
| + |
| +1. **Remote head R.** List level 0 of the replica: one LIST. Litestream never deletes the newest level-0 file (`litestream@v0.5.14/db.go:2627-2630`), so the head is there whenever the replica exists. If level 0 is empty, list levels 1, 2, 3 and the snapshot level until a file is found: at most four more LISTs. Read the head file's 16-byte trailer (`ltx@v0.5.1/ltx.go:30`) with one ranged GET, for its post-apply checksum. |
| +2. **No replica.** Keep the local copy if there is one, otherwise start fresh. This is today's behaviour; §16 says what it leaves to #199. |
| +3. **Local position L.** Open the local database through litestream with no replica client, so a WAL tail is folded into local LTX files without any S3 call, and read `DB.Pos` (`db.go:559-590`). If there is no local LTX file to read, checkpoint the WAL and compute the database checksum with `ltx.ChecksumReader` (`ltx@v0.5.1/checksum.go:119`), with the transaction id unknown. |
| +4. **Keep the local copy** when one of these holds: |
| + - L and R have the same transaction id and the same checksum; |
| + - L's transaction id is unknown and its checksum equals R's; |
| + - L is ahead of R, the local level-0 files from R+1 to L are contiguous, and the first one's pre-apply checksum (`ltx.go:187`) equals R's post-apply checksum. Replication then uploads the tail on start (`replica.go:170-176`). |
| +5. **Otherwise** rename the local database and its sidecar files aside as `<db>.stale` (the newest one is kept, for an operator), purge litestream's local state (`PurgeLocalDBArtifacts`, `backend_exec.go:831`), and restore (`backend_exec.go:853`). Count it and log it (§19). |
| + |
| +**Why this is safe.** Under the lease nobody else writes. Every write that reached S3 moved R. So a local copy that equals or extends R is the newest copy that exists anywhere. Writes another box never got to S3 are lost, which is H3. |
| + |
| +The seeded path (`seededRestore`) applies the same rule to any local database it would keep. |
| + |
| +**Failure cases.** |
| +- A LIST or trailer GET that fails fails the wake. It is never read as "no replica", as `restorePlain` already insists for restores (`backend_exec.go:855-858`). |
| +- A corrupt local file goes through the existing check and quarantine. |
| +- The checksum is CRC-64, built for accidents, not adversaries. A tenant who forged a match would only fool itself about its own data. |
| + |
| +**Cost.** A warm wake made no S3 request for the database before. Now it makes one LIST and one GET, five LISTs and one GET at worst. At $0.005 per 1,000 LISTs and $0.0004 per 1,000 GETs that is about $0.0000054 per warm wake. A restoring wake costs what it does today, because the restore reuses the listing. |
| + |
| +## 6. Who serves |
| + |
| +### 6.1 The invariant |
| + |
| +An awake instance runs only on its lease holder. Every other box forwards to it. |
| + |
| +### 6.2 The decision at box A, for a request to host H |
| + |
| +Every box in the region has H's route, so A always has one. |
| + |
| +1. H is awake or waking on A: serve, as today. |
| +2. A's holder cache names box B, B is not A, and B is in A's view: forward to B. |
| +3. Otherwise A probes the lease. |
| + - If A would wake H itself (§6.3), the probe is `Acquire`: one create-only PUT, plus one GET if a lock exists (`createlease.go:31-58`). If A wins, it wakes H. |
| + - If A would not (role `drain` or `platform`, or A is ineligible while an eligible peer exists), the probe is `LockState`, one GET (`internal/lease/lockstate.go:47-79`). Free: forward to the box §6.3 chooses. Held: go to step 4. |
| +4. The lease is held by owner O: |
| + - O parses (§4.2) and its box is in A's view: forward to it, and cache H against it. |
| + - O is A itself under an older agent: same-box takeover (§9.6). |
| + - O's box is not in A's view, or the forward fails to connect: the suspect path (§9.1). |
| + - O does not parse: 503 with `Retry-After`, as today (`activator.go:5507-5511`). |
| + |
| +### 6.3 Where a cold wake happens |
| + |
| +- The receiving box wakes H itself when it is serving and eligible. Eligible is the existing policy: at least 15% of memory and 10% of disk free, and a fresh edges file (`policy.go`). |
| +- **Soft spread.** If the receiving box already runs an instance of the same app and another eligible serving box exists, it forwards to the roomiest such box (`ChooseRoomiest`, `policy.go`). It never refuses for spread. |
| +- If the receiving box is not eligible, it forwards to the roomiest eligible serving box. |
| +- If no box is eligible, it wakes H anyway when it is serving, and raises the over-capacity alert. A box that cannot wake (`drain`, `platform`) answers 503 with `Retry-After: 5` and alerts. |
| + |
| +### 6.4 Forwarded requests |
| + |
| +A forwarded request carries the existing verified hop marker (`internal/edge/edge.go:3097-3131`). The box that receives it, B, **never forwards it again**. |
| +- H awake on B: serve. |
| +- The lease is free and B's role is `serve`: wake H on B. |
| +- Otherwise: 503 with `Retry-After: 1` and an `X-Carlos-Holder: <ref>` header naming the holder B's own probe saw. The existing no-route refusal (`homemap.go:1359-1362`) stays as it is. |
| + |
| +### 6.5 One retry by the receiving box (A9) |
| + |
| +On that 503, the box that first received the request may forward it once more, to the named holder, when the holder is in its view and the request is a GET or HEAD with no body, or a WebSocket upgrade that has not switched protocols. No request makes more than two forward attempts, and no forwarded request is ever forwarded again, so there can be no loop. |
| + |
| +### 6.6 The holder cache |
| + |
| +Each box keeps an in-memory map from host to holder reference and the time it learned it. It is fed by the owner in a held-lease error and by `X-Carlos-Holder`. An entry goes when this box takes the lease, when the holder answers "not here", when a dial to the holder fails, or when the holder leaves the view. It has a one-hour ceiling and a bounded size (LRU, 50,000 entries). It costs no S3 reads to keep. |
| + |
| +An entry that goes stale does no harm. If B has put H to sleep, a request forwarded to B finds the lease free and B wakes H again, so H tends to stay where it was. |
| + |
| +### 6.7 The concurrent cold-wake race |
| + |
| +Two boxes probe a free lease at once. The create-only write lets one win (`createlease.go:41-52`). The loser's `AcquireLease` reads the winner's lock (`litestream@v0.5.14/s3/leaser.go:90-101`) and gets a held error naming the winner, so it forwards. The winner's activator queues the forwarded request behind its own wake (`awaitWake`, `activator.go:1559-1564`). |
| + |
| +### 6.8 Where it goes in the code |
| + |
| +The activator's mesh seam (`activator.go:5479-5483`: "one hop max, guarded by a forwarded marker") and its held-lease branch (`activator.go:2275-2280`) gain a "forward to holder" outcome, which the edge carries out through `backhaulTo`. The held error's `Retry-After` of "until expiry" (`backend_exec.go:729-733`) is kept only for owners that do not parse. |
| + |
| +### 6.9 Requests from another region |
| + |
| +A request for an IE host that arrives on a UK box is forwarded to the IE box `foldHomes` picks for it (`homemap.go:791-867`). That box wakes H if the lease is free, or answers with the holder. The UK box then caches the holder and dials its public address next time. The bounce costs one extra round trip on the first such request after a holder change. For a request with a body the client sees one 503. That is an accepted limit of part 1 (§21 Q4). |
| + |
| +### 6.10 A holder that loses its lease |
| + |
| +A failed renewal latches the loss (`internal/lease/health.go:135-147`). The activator stands the instance down at the next request or sweep (`activator.go:1540-1551`, `:4606-4609`). Forwards to it then get "not here", and the receiving box wakes H once the lease is free, whether released or expired. |
| + |
| +## 7. Work with no request behind it |
| + |
| +Rendezvous hashing (HRW): for host H, the owner is the serving box with the highest `sha256(H + "\x00" + ref)`, the same tie-break shape as `boxchoice.Choose`. |
| + |
| +| Work | Today, with N boxes in a region | Under this spec | |
| +|---|---|---| |
| +| Always-on native sidecars: the boot pass (`internal/host/agent.go:705-724`) and the sweep (`activator.go:5052-5084`) | Every box starts every one. The lease lets one win, and the rest retry every sweep, each retry a PUT and a GET. | Only H's HRW owner starts it. Other boxes never probe. An owner that meets a lease held by a live peer waits until that lease's expiry before probing again. | |
| +| Schedule ticks: the converger gives every box timer rows (`internal/schedule/converge.go:18-20`) and each box's runner delivers by waking locally | Every box delivers every tick: N deliveries. | Only H's HRW owner delivers, through §6's routing: local, forwarded to the holder, or a wake. A non-owner advances its own row past a tick once the tick is 15 minutes old, so a new owner delivers every tick younger than that it has not advanced. A view change can deliver a tick twice, which H7 allows. | |
| +| Due-time wakes: `next_due` sits in the local registry of the box that slept H (`activator.go:4996-5050`) | Only the sleeper knows the time. Other boxes hold stale values and race wakes. | The sleeper publishes H's `next_due` and its sleep time in its edges file (new additive host field). H's HRW owner does the due wake from the folded entries, and the newest sleep time wins. A confirming box copies a dead box's entries before deleting its file (§9.3). | |
| +| App once-timers, registered on the waking box only (`internal/schedule/control.go:15-19`) | Lost when H wakes elsewhere. | Part of H's wake state, exported to S3 at sleep and imported at wake (`hostfiles.ExportWake`/`ImportWake`, `internal/hostfiles/wake.go:47,84`), and always continuous (S1 §5.6). | |
| +| Co-spawn sidecars (`activator.go:17-25`) | Start with the instance on the box that woke it. | Unchanged: holder only. | |
| +| Instance key and admin token, minted into the box-local `<host>.env` (`internal/activator/instancekey.go:3-10`, `EnsureAdminToken`) | A second box mints a different key. Data sealed with the first becomes unreadable. | `<host>.env` is a platform file synced to S3 (§8). A box mints only while it holds the lease and S3 answers "no such key" for the host's files manifest. Otherwise it restores the env first. | |
| +| `carlos run`: the record names one picking box by CAS (`internal/host/runexec.go:109-119`) | Any box may pick. | A box picks a run only if it holds H's lease, or H is asleep and the box is H's HRW owner. | |
| +| WebSockets | Held on the waking box. | On the holder. A forwarded upgrade rides the backhaul; the plan confirms the backhaul carries upgrades. When the holder dies, the client reconnects. | |
| +| Named units and `Backing=unit` rows | Box-local operator rows, never adopted from records (`reconcile.go:611-616`). | Unchanged. They live on the platform box. | |
| +| Static sites | Served on every box from the signed channel (`reconcile.go:336-338`). | Unchanged. | |
| +| Housekeeper duties | One deployment-wide lease election. | Unchanged. | |
| + |
| +## 8. Per-instance files (H6) |
| + |
| +### 8.1 What is there |
| + |
| +- **App files:** the files directory, `<instance dir>/<host>/` (`internal/layout/plan.go:196`), holding `instance.key`, `report.token`, blobs and uploads. |
| +- **Platform files:** `<host>.env` (admin token and instance key) and the wake state. |
| +- `<host>-sidecar.env` and `<host>.config.env` are rendered from the bucket on every box, so they are not synced. |
| + |
| +Today nothing claim-free publishes files. `hostfiles.Run` has no production caller, and every caller of the package is claim, moves or relocation code. |
| + |
| +### 8.2 The mechanism |
| + |
| +`hostfiles` as plan 1a built it, made claim-free (A17). The location is the host's hibernate prefix (`activator.go:138-150`) plus `files/0/`: one fixed generation. Objects are immutable and the manifest is replaced by compare-and-swap (S1 §5.6, "Ordering"). Every write passes the fence (§9.5). |
| + |
| +- **On wake**, under the lease, after the database rule: read the manifest (one GET). |
| + - If the local `.files-gen` marker names the same manifest (sequence and hash), keep the local directory. |
| + - Otherwise bring the directory to the manifest (`hostfiles.Restore`, `internal/hostfiles/restore.go:65`), downloading only objects whose hash differs. Local changes that were never published are lost, as H3 accepts for the database. |
| + - Platform files are restored before the key mint and before the app starts. |
| +- **While awake:** |
| + - continuous plan: `hostfiles.Run` (inotify, one-second deadline; `internal/hostfiles/run.go:22,44`); |
| + - snapshot plan: a full publish every `files_snapshot_interval` (15 minutes by default), only when the tree changed. A local digest decides, so an idle instance makes no request; |
| + - platform files are continuous on every plan (H6). |
| +- **At sleep,** a final publish and the wake-state export happen before the lease is released, on every plan. So graceful sleeps and drains lose nothing. A failed final publish fails the sleep the way a failed final database sync does today; the plan names that path. |
| + |
| +### 8.3 The setting |
| + |
| +`files_durability` (`continuous` or `snapshot`, default `snapshot`, H8) and `files_snapshot_interval` become per-app platform settings, read by boxes with the app's configuration (the `apps/<acct>/<app>` change scope). Nothing stores them today. An operator door sets them; Carloku maps its plans to them (H6). Any console text goes through copy review. |
| + |
| +### 8.4 Backfill |
| + |
| +When `CARLOS_REGION_HA` turns on, a box runs a one-time files pass over its local instances. Each files directory with no manifest is published under that host's lease: the box acquires it, publishes, and releases. A host whose lease is held elsewhere is skipped and retried later. The box reports `files_unsynced` in its status snapshot, and retiring an old box waits for zero (§13). |
| + |
| +**Failure cases.** Only the lease holder writes a manifest, and the fence stops a holder that lost its lease, so two boxes never race one manifest. Apps that update a file in place can find a torn image after a failover; S1 §5.6 already says so in the docs. |
| + |
| +**Cost.** Continuous sync makes up to two PUTs per second per file being written: the object and the manifest. A file rewritten every second all month costs about $26 a month in requests (§21 Q1). The snapshot plan makes at most four publishes an hour, and none when idle. A wake costs one GET plus any changed objects. |
| + |
| +## 9. Termination and takeover |
| + |
| +### 9.1 How a survivor learns |
| + |
| +Two triggers, both on boxes (A4). |
| + |
| +- **The event.** The EventBridge rule already forwards every EC2 `terminated` state change in the account and region to an SQS queue (`infra/modules/region-host/main.tf:835-888`), and the box role can already receive and delete from it (`main.tf:890-904`). With `CARLOS_REGION_HA` on, each box long-polls it with 20-second waits. Each message reaches one box. A message for an instance that is not a box of this deployment is deleted and ignored. |
| +- **Suspicion.** A forward to a holder fails to connect (a 2-second connect timeout on the private address), or a held lease names an owner whose box is not in the view. |
| + |
| +### 9.2 How it confirms |
| + |
| +Confirmation is one `DescribeInstances` for the owner's instance id in the box's own AWS region (`internal/termfence/fence.go:154-166`). The box role already has that action, in the inventory statement (`main.tf:203-235`). The check is `termfence.Verify`'s (`fence.go:177-198`): found, the same instance id, the same account and region as this box's own identity document, and state exactly `terminated`. |
| + |
| +- Absence is never evidence (`fence.go:86-90`). `shutting-down` is not terminated. |
| +- An event is only a hint: a box always describes before it acts. |
| +- A positive answer is cached for 24 hours, since a terminated instance never returns. A negative one is cached for 10 seconds. |
| + |
| +### 9.3 What confirmation does |
| + |
| +When a box confirms that box C (instance I, reference R) is terminated, it: |
| +1. reads C's edges file (one GET) and copies C's due entries (§7) into its own next publication; |
| +2. deletes `control/edges/R.json` on its ETag. That bumps the `control/edges` scope (`changeindex.go:71`), and every box drops C from its view at its next fold, within about 30 seconds; |
| +3. logs the confirmation and counts it (§19). |
| + |
| +Leases are not touched in bulk (A5). Each is taken at its first need. |
| + |
| +### 9.4 The takeover write |
| + |
| +The lease package gains `TakeOver`: |
| +1. Read `lock.json` with its ETag, as the tombstone code does (`tombstone.go:117-140`). |
| +2. Require an owner that parses as `box/v1` with an instance id confirmed terminated (§9.2). |
| +3. Write `{generation + 1, expires_at = now + TTL, owner = this box}` with `If-Match` on that ETag. It is the same conditional-PUT primitive the tombstone uses (`tombstone.go:1-26`). |
| +4. On 412, read again and decide again. Another survivor won, so forward to it. |
| +5. On success, start the renewer as `AcquireTTL` does (`internal/lease/lease.go:206`) and return a held lease. The wake continues from step 1.5 (`activator.go:2288-2301`) and then §5's rule, which almost always restores, because the survivor has no copy or an old one. |
| + |
| +Only a box that would wake H under §6.3 takes over. A `drain` or `platform` box forwards to a serving box, which does. |
| + |
| +### 9.5 The write fence (A11) |
| + |
| +The lease package wraps the litestream replica client it builds (`newStore`, `lease.go:401-429`) and the files publisher. Every `WriteLTXFile`, `DeleteLTXFiles` and manifest write first checks that the renewer has not failed and that the safe deadline has not passed (`health.go`). |
| + |
| +What remains is a process frozen between that check and the request leaving the box for longer than the rest of its safe window. Every lease without a storage-side fencing token has that window. It is accepted and stated. |
| + |
| +### 9.6 Same-box takeover (A16) |
| + |
| +If the owner's instance id is this box's and the pid is not this agent's, the previous agent on this box is gone, because systemd runs one at a time. Once `wakeHostProven` has shown the host's process group empty (`activator.go:2288-2301`), the box takes the lease as in §9.4. Otherwise it waits, as today. |
| + |
| +### 9.7 A hung box that is not terminated |
| + |
| +It is **never** taken over. If any health condition fails (§10), the load balancer stops sending it new connections within 20 to 30 seconds (10-second checks, 2 failures). The group then terminates it (H20), and §9.1 to §9.4 apply. |
| + |
| +If the group does not terminate it, its leases expire after at most 15 minutes (`lease.go:38`) and are acquired normally. That happens in a region's first build, where AWS does not replace a target group's unhealthy instances until it has had a healthy one (S2 §5). |
| + |
| +### 9.8 A box that is alive but has lost S3 |
| + |
| +Its renewal fails, the renewer latches the loss, and the activator stops the instance at the next request or sweep (§6.10). Renewal runs every TTL/3 (`health.go:114`), five minutes, and the safe deadline is expiry minus 5 seconds (`health.go:19`). So the instance stops at least about ten minutes before the lease expires. |
| + |
| +Other boxes see a lease held by a running box that is in their view. They answer 503 with `Retry-After` capped at 30 seconds until the lease expires: up to 15 minutes for that box's instances. Its health stays 200 by design, because a shared dependency never marks a box unhealthy (S2 §6, A2-3). It keeps forwarding, which needs no S3. This is an accepted limit: one box losing S3 on its own is rare, and the lease TTL bounds it. |
| + |
| +### 9.9 Timeline |
| + |
| +These are estimates. Dev measures each one before any flagship region (§18). |
| + |
| +| Phase | Box terminated through the API | Box hung | |
| +|---|---|---| |
| +| The box stops serving | 0 s | 0 s | |
| +| The load balancer stops sending new connections | 20 to 30 s | 20 to 30 s | |
| +| The group terminates it | not needed | typically 1 to 2 min after it turns unhealthy | |
| +| EC2 reports `terminated` | 30 s to 2 min | 30 s to 2 min after the group's terminate | |
| +| The event is on the queue | seconds later | seconds later | |
| +| First request for one of its instances: probe, describe, takeover | under 1 s | under 1 s | |
| +| Restore | seconds, by database size | the same | |
| +| **Total, request-driven instances** | **about 1 to 3 min** | **about 2 to 5 min** | |
| +| Always-on workers and ticks | one sweep (30 s or less) after the event | the same | |
| +| Worst case, event lost | the dead box ages out of the view: 15 min, then a sweep | the same | |
| + |
| +A graceful termination (a healthy box shut down, scale-in, zone rebalancing) needs no takeover. systemd stops the agent, and the activator's shutdown sleeps every instance and releases its lease (`activator.go:5186-5194`): seconds per instance. |
| + |
| +The "few minutes" target is met. Going lower means tightening the health checks and the group's reaction, never the lease TTL (N-HA3). |
| + |
| +## 10. Load balancer health |
| + |
| +Keep `internal/lbhealth` with all six conditions (`internal/lbhealth/lbhealth.go:154-178`) and the endpoint (`internal/edge/lbhealth.go:21-39`). |
| + |
| +The hosting condition is set today only by the claim wiring (`internal/host/claimwiring.go:102-106`), so health stays 503 with claims off. A **serving latch** replaces that caller. |
| + |
| +- **Set** once, after all of these: `host.env` loaded; the first registry reconcile pass for this box's region done; the first edges file published with the box's role; and the termination consumer started, on AWS. |
| +- **Cleared** first thing in shutdown (the seam at `activator.go:5190`), so new connections stop before instances sleep. |
| +- A box in role `drain` stays healthy until the operator removes it, because it still forwards. The `platform` box is not a target (A13). |
| +- **During boot** the answer is 503 until the latch is set. The group's grace period comes from dev measurement; start at 15 minutes. S2's 20 minutes covered enrolment, which is gone. |
| +- **Unchanged:** forwarding latched, certificates latched, edge and activator beats within 60 seconds, a home-map refresh attempt within 5 minutes. |
| +- **Not added:** S3 reachability. A bucket outage must never terminate working boxes (S2 §6). |
| + |
| +## 11. Placement inputs and capacity |
| + |
| +- **Published by each box:** headroom in its edges file (`internal/host/headroom.go:13-16`, published whenever `CARLOS_REGION_HA` is on), its role (§4.4) and its private address (plan 2a, once split from the claim code, §15.2). |
| +- **Eligibility:** the existing placeable policy (`policy.go`), applied to the serving set. |
| +- **The console** reads live edges files and verifies identity records without a roster (`boxselect.go:147-174`), then applies the same policy. |
| + - It publishes `Carlos/Region EligibleBoxes` (`internal/console/awsregionmetric.go:56-70`). That pass starts at console start when `CARLOS_REGION_METRICS=cloudwatch`, instead of inside `StartClaimRecoveryPass` (`internal/console/hostclaimops.go:44-61`). |
| + - `regioncapacity.go` counts with the policy instead of the hostops chooser. |
| +- **The create door** (and domain attach of a first route, and standalone sidecar create) refuses with 503 and the approved no-capacity message when the instance's region publishes headroom and has no eligible serving box. It alerts at most once per region per hour (A20). `nocapacity.go` is rewritten without its claim parts. |
| +- **Wakes are never refused for headroom** (§6.3). |
| +- **Group membership is not an input** (A14). A box detached from its group that keeps running stays in the view until it stops publishing. |
| + |
| +## 12. Infrastructure and boot (S2's plan 2c, claim-free) |
| + |
| +### 12.1 Group mode in `infra/modules/region-host` |
| + |
| +Today the module makes one `aws_instance` and one `aws_eip` (`main.tf:536-587`). Group mode, chosen by a variable, adds the following; fixed mode stays for the platform box and for deployments without HA. |
| + |
| +- **Launch template,** as S2 §4: the same AMI, type, root volume with delete on termination, security group and instance profile; IMDSv2 with hop limit 1; an auto-assigned public IPv4 address for cross-region dials. The user data names the deployment, its bucket, the region and the AWS region. |
| +- **Auto Scaling group:** `min = max = desired = box_count` (H5), across at least two zones; health checks ELB plus EC2; the grace period from dev (§10); no instance refresh, since releases arrive through `carlos system update`; `AZRebalance` suspended, because each rebalance would sleep every instance on a box for nothing. |
| +- **Network Load Balancer:** one subnet mapping per group zone. Zone A carries the region's existing EIP, a standalone `aws_eip` with `prevent_destroy` (S2 A1-13). The other zones get new EIPs, unpublished. Cross-zone on; TCP 80 and 443; one target group per port with instance targets, so the client IP is kept; deregistration delay 30 s; health HTTP on 80, `/.carlos/lb-health`, every 10 s, 2 healthy and 2 unhealthy. |
| +- **Security group:** 80, 443 and the backhaul port from the VPC CIDR (`vpc_cidr`), for health checks and private dials. |
| +- **The termination rule and queue:** unchanged (`main.tf:835-904`). |
| +- **Alarms:** §19. |
| + |
| +### 12.2 IAM |
| + |
| +- **Box role:** |
| + - `ssm:GetParameter` and `GetParametersByPath` on `/carlos/<deployment>/<region>/*` and `/carlos/<deployment>/shared/*`; |
| + - `kms:Decrypt` with the `ViaService` and `PARAMETER_ARN` conditions; |
| + - the existing SSM Deny kept (S2 §4); |
| + - an explicit HA statement for `ec2:DescribeInstances`. Today the action rides the inventory statement (`main.tf:203-235`), which may be narrowed for reasons of its own. |
| + - No Auto Scaling, ELB or EC2 write right. |
| +- **Console:** nothing new. H28's membership read existed for enrolment, which is gone. |
| +- **Operator seeding:** `ssm:PutParameter`, `kms:Encrypt`, and `kms:Decrypt` with the same conditions (S2 §5 step 2). |
| + |
| +### 12.3 Boot |
| + |
| +The start-up script replaces `bootstrap-box.sh`, `set-alert-sns-topic.sh` and the hardening scripts, which are run by hand over SSM today. A failed step stops the script. The box then never answers 200, and the group replaces it after the grace period. |
| + |
| +1. **Harden,** as `harden-box.sh` and `harden-host.sh` do, including the nftables gate that keeps tenants away from IMDS credentials. |
| +2. **Configure.** Download `s3://<deployment-bucket>/bootstrap/carlos` and check it against `/carlos/<deployment>/shared/bootstrap-sha256`. Then `carlos system host-env write` (`internal/hostenv`, plan 2b) writes `/etc/carlos/host.env` from SecureString parameters, with S2 §5 step 2's allowlist, value and directory rules, minus `CARLOS_HOST_CLAIM*` (R9). |
| +3. **Install.** `carlos bootstrap`, then `carlos system install-channel` (`internal/host/installchannel.go`, plan 2b), which installs the signed channel release into both binary slots. Its guard and floor checks go, since `hostfloor` leaves with R4b. |
| +4. **Start the agent.** There is no joining mode, invitation, enrolment or guard-arm. |
| + |
| +### 12.4 The platform box and the cut-over |
| + |
| +- **The platform box** (IE, H24) stays in fixed mode, with its own new EIP for the relay and MX. S2 §6's platform-box steps apply unchanged: lowered TTLs, the relay restarted on its new address, SPF and reverse DNS. It is not a target (A13), and its `host.env` moves to the same parameters. |
| +- **The cut-over** moves the region's EIP to the load balancer's zone A mapping. That costs a few minutes per region (S2 §9 step 3), announced, at a quiet hour, measured on dev first. |
| + |
| +### 12.5 Provider boundary |
| + |
| +The core assumes what the README says a deployment is: one object store with conditional writes (`If-None-Match`, `If-Match`), N hosts running `carlos`, and DNS. The AWS parts are adapters: |
| +- (a) the termination oracle and event source: EC2 describe, EventBridge and SQS; |
| +- (b) box identity: the IMDS identity document, and the instance id in the lease owner; |
| +- (c) the private address: IMDS; |
| +- (d) the group and load balancer: tofu only. No code calls Auto Scaling or ELB; |
| +- (e) the eligible-boxes metric: CloudWatch. |
| + |
| +Without (a), a deployment gets everything but fast takeover: a dead box's leases wait out the 15-minute TTL. Without (c), forwarding dials public addresses. No core package imports an AWS SDK for HA; only the adapters do, as `termfence` does today. |
| + |
| +## 13. Retiring the old box (N-HA2) |
| + |
| +This is the sequence for UK, US and AU. IE differs only in step 4. |
| + |
| +**Preconditions:** |
| +1. Releases 1 and 2 (§18) run on the old box and the console. |
| +2. `CARLOS_REGION_HA=1` on the old box. With one box every multi-box rule is a no-op: it is the only serving box, every hash picks it, and every lease is its own. |
| +3. The files backfill shows `files_unsynced = 0`, and every hibernating instance has a replica. A console readiness door, `carlos system region readiness <region>`, lists hosts missing either. |
| +4. The group is built and healthy behind zone B's address, and has been rehearsed there. |
| + |
| +**Steps:** |
| +1. **Join.** Register the old box in the target groups. It is an ordinary member and serves like the group boxes. Customer traffic still reaches it through the region's EIP, and zone B's traffic reaches every box. |
| +2. **Drain.** `carlos system box role <old> drain`. The old box stops waking anything and leaves the serving set, so its duties move by hash. It then sleeps its awake instances one at a time: a graceful stop (final database sync, files and wake state published, lease released), a 5-second pause, then the next. A request for a host that is mid-stop waits for the stop. It is then forwarded to the box §6.3 chooses, which restores and wakes it: a few seconds down per app. Always-on workers stop the same way, and their hash owner starts them again. |
| +3. **Cut over.** Once the old box runs no tenant instance, disassociate the region's EIP from it and add zone A's mapping to the load balancer with that EIP (S2 §9 step 3). A few minutes down, announced. The old box keeps forwarding whatever still reaches it. |
| +4. **Remove.** Deregister the old box, wait the 30-second delay, and terminate it. **In IE**, instead: set role `platform`, deregister it, and swap it to its new EIP, moving the relay and MX in the same window (S2 §6 and §9's IE steps). |
| +5. **Accept** after seven days. |
| + |
| +**Rollback:** |
| +- **Before step 3:** set the old box back to `serve`. If the group itself is at fault, drain its boxes: their instances sleep one at a time and wake on the old box. A drained group can then be destroyed, because no state lives only on a group box. This replaces S2's rule never to destroy a group that has hosted an instance. |
| +- **From step 3 until acceptance:** remove zone A's mapping, wait until the EIP shows as unassociated, associate it with the old box, and set it to `serve`. A few minutes down. |
| +- **After acceptance:** recovery is forward only. |
| + |
| +Local copies on a removed box go with it. None is newer than S3, because of precondition 3 and the graceful stops. |
| + |
| +**Cost.** During the window a region runs `box_count + 1` boxes. Afterwards it runs `box_count`, plus IE's platform box. Each region adds a load balancer (about $20 a month before traffic) and an EIP per extra zone. |
| + |
| +## 14. S2 §8's single-box rows, restated (the old plan 2d) |
| + |
| +| Row | Status | Claim-free answer | |
| +|---|---|---| |
| +| Move door and `selectMoveBoxes` refuse multi-box regions (`internal/console/apiinstancemove.go:687-713`, `boxselect.go:78-140`, `internal/host/movesphase1.go:502-518`) | Dropped | Phase 1 live moves are deleted by R4a. Offline moves: §16. | |
| +| Seed import refuses a multi-box region (`internal/console/seedfloor.go:25-29`, `:88-89`) | Kept for now | The import's swap journal is box-local. Imports keep refusing N-box regions until the seeded-instances owner moves the journal to S3 under the lease. Seeds (`oneBox=false`) already land under the lease on whichever box wakes. Ask the owner. | |
| +| `CheckOneBoxRegion` (`internal/hostfence/onebox.go:12-35`) | Dropped | All three callers are claim-only hostops code, deleted by R6. | |
| +| Activator warm cache (`activator.go:2302-2311`, `backend_exec.go:819-820`) | Built here | §5. | |
| +| Hosts unique to one box: heartbeats joined last-wins (`internal/console/apiinstances.go:523-527`) | Rewrite | Show the box whose snapshot reports the host awake, or none. A host in several boxes' registries is normal now. | |
| +| EIP list as A-record targets (`internal/console/view.go:178-237`, `server.go:1301-1376`) | Rewrite | A region ingress list set by tofu (`CONSOLE_REGION_INGRESS`), plus `PLATFORM_EDGE_IPS`. The domain check's "pointing" verdict uses it. Copy review. | |
| +| Forwarding dial (`homemap.go:159-174`) | Keep plan 2a | Private address in the region, public between regions. The address source moves out of the claim code (`internal/host/edgesfile.go:983-988`). A box publishes only addresses IMDS reports (`edgesfile.go:733-757`). | |
| +| `consoleBoxLabel` (`cmd/console/main.go:1719-1729`) | Holds | The console runs only on the platform box. | |
| +| Scoped restart (`internal/console/apirestartscope.go:133-150`) | Holds | Every box of a region, the console's included (A13), holds every route of that region. The cross-region limit predates this spec. Every box acts on the restart; only the holder has a process to cycle. | |
| +| Domain attach's primary route (`internal/console/domainattach.go:472-500`) | Holds | Same reason. | |
| +| Economics attribution (`internal/console/economicspass.go:308-318`) | Holds | Every box's usage is matched against routes the console box holds for its region. Other regions are unchanged. | |
| +| Fleet listing (`internal/status/fleet.go:158`) | Holds | Every box of a region lists the same routes. | |
| +| Retention (`internal/host/retention.go:36-37`) | Holds | Same. | |
| +| Platform routes reaching group boxes | Requirement and tests | The platform box publishes console and platform hostnames as home (`edgesfile.go:478-519`), and group boxes backhaul them (`edge.go:1611-1645`). Tests cover it. | |
| +| Flagship tofu and scripts | Rewrite | The group, the load balancer and the platform box. Group boxes use §12's boot and `carlos system update`. The platform box keeps its scripts. | |
| +| Offline moves (new row) | Rewrite | §16. | |
| + |
| +## 15. What happens to existing dormant code |
| + |
| +### 15.1 Kept as is, or nearly |
| + |
| +- `internal/lbhealth`; `internal/edge/lbhealth.go`; `homemap.go`'s `privateDial` and `dialAddress`; `internal/edgesfile/private.go`; |
| +- `internal/host/awsaddr.go` and `boxaddress.go`; `headroom.go`; `internal/boxid`; `boxrecord.go`; `boxreference.go` and `GroupBoxReference`; |
| +- `internal/boxchoice`: `policy.go` and `Choose`; |
| +- `internal/termfence`, with `Box` cut to `{Ref, Cloud}` and the enrolment fields dropped; |
| +- `internal/hostfiles`; |
| +- `internal/hostenv`, minus the `CARLOS_HOST_CLAIM*` keys (R9); |
| +- `installchannel.go`, minus its guard and floor checks; |
| +- the termination rule and queue in infra; |
| +- plan 2a's approved no-capacity copy, where the text still fits. |
| + |
| +### 15.2 Rewritten |
| + |
| +- The `SetHosting` caller (`claimwiring.go:102-106`) becomes the serving latch (§10). |
| +- The address source moves from `edgesclaims.go` into the edges publisher, with no `hostclaim.Read`. |
| +- `apiboxroles.go` and `system_roles.go` become the role objects (§4.4). |
| +- `nocapacity.go` loses its claim half (§11). |
| +- `regioncapacity.go` counts with the policy, and the metric starts at console start (§11). |
| +- `boxselect.go` keeps `liveEdges` and `verifiedRoster`. `selectMoveBoxes` goes with R4a. |
| + |
| +### 15.3 Handed to claims-cleanup R3 for deletion |
| + |
| +- `internal/hostrelocate`, and `internal/host/relocat*.go` with their tests. |
| +- `internal/hostactors/awsmembership`, `internal/console/awsmembership.go`, `internal/console/enrollpass.go`, and `hostactors`' `autoenroll.go`, `membershipread.go` and `enrollment_confirmation.go`, or with R6's removal of `hostactors`. |
| +- `internal/host/joining.go`, `joinmode.go`, `joinroot.go`; the `carlos system join` verb; the units `carlos-system-join.{service,path}`. `system apply` must also remove the installed units from boxes. |
| +- `internal/console/hostclaimexecutor.go`, and the region-HA branches of `hostclaimops.go`. |
| +- `internal/host/edgesclaims.go`, once the address split has landed. |
| +- `hostops/chosen.go` and plan 2a's additions to `hostops/executor.go`; `hostactors/roles.go` (with R6). |
| +- The `region-ha-2a` and `region-ha-2b` census rows of deleted units, retired the R0 way. |
| + |
| +### 15.4 Amendments to the cleanup plan |
| + |
| +- R3 no longer deletes `termfence`, `boxrecord.go`, `carlos system install-channel`, `hostenv`'s `CARLOS_REGION_HA` key, `privateDial` or `edge/lbhealth.go`. |
| +- R4a keeps `boxchoice`. |
| +- R1's move of `GroupBoxReference` stands. |
| +- Changes to root verbs (`install-channel`) and to the unit set need a census card and an approval (AGENTS.md, "The census"). |
| + |
| +## 16. Interactions |
| + |
| +- **Offline and self-serve moves** (`origin/self-serve-moves-2` to `-4`). Two refusals change for an HA region: |
| + - "Exactly one target box" (`internal/console/apiinstancemove_offline.go:387-389`) becomes "at least one serving box". Staging goes to the region's data bucket, and the first box to wake the host promotes it under the lease (`backend_exec.go:833-851`). |
| + - "Local data on more than one box" (`:1043-1045`) becomes: in an HA region every source box drops its local copy after the tombstone, because S3 holds the database and files once the holder's final sync is done. |
| + - The moves owner writes both. §5 also protects a landing box from an old local copy. |
| +- **Nearest region and #199** (`origin/design-nearest-region-199`, rev 2, Option B). #199's hazard is a local copy left by an earlier incarnation of a hostname. §5 rejects a local copy that disagrees with S3, but keeps one when S3 has no replica, as today. With N boxes such a leftover can sit on any box of the region. Recommendation for that design: a delete purges the host's local data on every box of its region. Every box adopts the record, so every box sees the delete. |
| +- **Static sites:** unchanged; every box serves them. |
| +- **Edge asset cache** (plans 1 and 2 merged, dormant): each box's cache warms on its own. Keys carry the version. No change. |
| +- **Rootfs apps (#366):** a box materializes an app's root image on its first wake there, so there are more first wakes. No correctness change. |
| +- **Seeded instances:** §14's import row. A seed lands under the lease on any box. |
| +- **`db pull`/`db query --at` and cross-region db forward:** they read the S3 replica, so any box of the region can serve them. Staleness stays about one second (H3). `Incarnation` moves with R1. |
| +- **Litestream #284** (`origin/litestream-oom-284`): restores get more frequent, because a host now wakes on boxes with no copy. Land slice A before small group instances. |
| +- **Change index (#336):** one new scope, `control/box-roles`. A dead box's edges deletion rides `control/edges`. No new poll of S3. |
| +- **Housekeeper and certificates:** unchanged (S2 §6). |
| + |
| +## 17. Request budget |
| + |
| +**Steady state, per box per hour.** |
| +- **S3:** unchanged. Today that is about 3,300 to 3,500 requests: the serial GET, index 304s, home map and certificate polls, plus edges re-reads when `control/edges` moves. This spec adds no steady S3 request. |
| +- **Edges writes:** the timed pass is unchanged. Each sleep that changes a due entry adds one write, plus the index GET and CAS PUT. |
| +- **SQS:** 180 long-poll receives, about 4,300 a day, which is about $0.05 a month per box at $0.40 per million. |
| +- **EC2:** describes only on suspicion, at most one per suspected instance per 10 seconds per box. Normally none. They are free and rate-limited. |
| +- **Lease TTL:** unchanged at 15 minutes, 288 renewal PUTs a day per awake instance (`lease.go:28-38`, N-HA3). |
| + |
| +**Per event.** |
| + |
| +| Event | S3 requests | Notes | |
| +|---|---|---| |
| +| Cold wake, lease free, no local copy | 1 PUT (+1 GET if an expired lock is present), the restore as today, 1 GET for the manifest, changed objects | | |
| +| Warm wake | as today, + 1 LIST + 1 ranged GET (database) + 1 GET (manifest) | at worst 5 LISTs | |
| +| Probe of a lease held elsewhere | 1 PUT (412) + 1 GET, or 1 GET (`LockState`) | once per box, host and holder change | |
| +| Sleep | as today, + a files publish if anything changed, + an edges write if a due entry changed | | |
| +| Takeover | 1 GET + 1 PUT, + 1 EC2 describe | | |
| +| Termination confirmed | 1 GET + 1 DELETE (edges file), + the index bump | | |
| +| Awake hour, snapshot plan | at most 4 publishes, none when unchanged | | |
| +| Awake hour, continuous plan | up to 2 PUTs per second per file being written | §21 Q1 | |
| + |
| +**Example.** 10,000 warm wakes a day add 10,000 LISTs and 20,000 GETs: about $0.06 a day. |
| + |
| +## 18. Switches and rollout |
| + |
| +**Switches.** |
| +- **Box:** `CARLOS_REGION_HA`, from `host.env` and SSM (A15). It gates the termination consumer, holder forwarding, takeover, duty hashing, files sync, the serving latch, headroom, the identity record and private dials. With one box each is a no-op. |
| +- **Always on in the release, no switch:** the freshness rule (A1), the write fence (A11) and the owner format (A3). |
| +- **Console:** `CARLOS_REGION_METRICS=cloudwatch` (exists), `CONSOLE_REGION_INGRESS` (new), and the operator role door. |
| +- **App:** `files_durability` and `files_snapshot_interval`. |
| + |
| +**Order.** |
| +0. R3 (§15.3) lands, so nothing claim-bound sits under `CARLOS_REGION_HA`. |
| +1. **Release 1:** the freshness rule, the fence and the owner format. Roll it dev boxes, dev console, check, flagship boxes, flagship console. Watch the stale-copy count: dev's IE region already has a second box (`platform-infrastructure/dev/region-ie-b.tf`). |
| +2. **Release 2:** everything behind `CARLOS_REGION_HA`. Same roll. |
| +3. **Turn on `CARLOS_REGION_HA`** box by box: dev first, including dev's two IE boxes, the first real two-box test. Then the flagship's old boxes, one region at a time, each until its files backfill is done. |
| +4. **Per region:** infrastructure (§12) and retirement (§13). Dev, then UK, US, AU, and IE last, because of the platform box. |
| + |
| +On dev, before any flagship region, run and time a terminate drill and a hang drill (§20). |
| + |
| +## 19. Observability and alerts |
| + |
| +- The load balancer's `UnHealthyHostCount > 0` for 10 minutes, and `HealthyHostCount < box_count` for 25 minutes. |
| +- `EligibleBoxes < box_count` for 25 minutes, with missing data as breaching (S2 §4). |
| +- `GroupInServiceInstances < desired`. |
| +- The termination queue's `ApproximateAgeOfOldestMessage` over 10 minutes: nobody is consuming it. |
| +- **Takeovers:** a `Carlos/Region Takeovers` metric and one log line each, with the host, dead box, instance id and latency. Alert above a rate that means flapping. |
| +- **Suspect holders:** a host refused for more than 20 minutes because of a lease held by an owner not confirmed dead. That is a hung box the group did not terminate. |
| +- **Stale copies set aside (§5):** a count per box. On the flagship, alert on any for the first month, since each one means the rule caught a real case. |
| +- **Files:** the oldest unpublished change over 5 minutes (continuous) or over two intervals (snapshot); `files_unsynced > 0` on a draining box. |
| +- **Over capacity:** a wake with no eligible serving box, at most once per region per hour. |
| +- The memory alarm on the group dimension. |
| + |
| +## 20. Tests |
| + |
| +### 20.1 The simulation |
| + |
| +A seeded, invariant-based simulation, `internal/sim/regionha`, test only. |
| + |
| +**It models:** |
| +- 2 to 5 boxes and one S3 with conditional writes, holding per-host replica chains (transaction id and checksum); |
| +- `lock.json` with expiry and ETag; |
| +- EC2's states, `running` to `shutting-down` to `terminated`, with delays; |
| +- load balancer health and the group's reaction; |
| +- a termination queue that can lose messages. |
| + |
| +**Actions:** requests at random boxes, sleeps, kills, hangs (with and without a later resume), one box losing S3, agent restarts, concurrent cold wakes, drains, and clock skew within the margin. |
| + |
| +**Invariants:** |
| +- **I1, single writer.** Every uploaded LTX file was written while its writer held an unexpired lease it acquired or took over. No two uploads for one host share a transaction id. |
| +- **I2, no stale serving.** A box starts serving a host only from a database equal to, or extending, the S3 head at that moment. |
| +- **I3, no wrong takeover.** No takeover of an owner that is not terminated. |
| +- **I4, bounded forwarding.** At most two forward attempts per request, no forwarded request forwarded again, no cycle. |
| +- **I5, liveness.** After a kill, every host can be served again within the modelled detection bound. |
| +- **I6, ticks.** Every tick is delivered at least once within the 15-minute window. |
| +- **I7, keys.** No host's instance key is minted twice. |
| + |
| +**Mutation checks.** Each of these must make the sweep fail: drop the freshness rule; accept `shutting-down`; drop the write fence; let a forwarded request be forwarded again; mint without the manifest check. |
| + |
| +One 3,000-seed sweep per revision, run serially at nice 19. |
| + |
| +### 20.2 Other tests |
| + |
| +- **Unit tests:** |
| + - freshness: equal, behind, ahead and extending, diverged, no local LTX with a matching checksum, a WAL tail, no replica, a failed LIST, a failed trailer read; |
| + - owner parsing; |
| + - `TakeOver`: 412, absent lock, tombstone, old-format owner, owner not terminated; |
| + - termination verification; the holder cache; hashing; the role reader; the serving latch; the files marker. |
| +- **Against MinIO:** `TakeOver` and the fence, with real conditional writes. |
| +- **Dev drills, each timed:** |
| + - terminate a group box through the API; |
| + - hang one: `SIGSTOP` the agent, and separately black-hole its health port; |
| + - black-hole S3 for one box; |
| + - send concurrent first requests to a cold host from both boxes; |
| + - drain and retire an old box; |
| + - the EIP cut-over, and both rollbacks. |
| + |
| +## 21. Open questions for Paul |
| + |
| +Most important first. |
| + |
| +1. **How fast should continuous files sync be?** S1 §5.6's one-second deadline costs up to two PUTs per second for each file an app keeps rewriting: about $26 a month per such file. *Recommendation:* coalesce app files to 10 seconds on the top plan (about $2.60 a month at worst, a 10-second loss window), and keep one second for the platform files, which are small and rarely written. |
| +2. **Ship same-box takeover (A16) in release 1?** It also shortens today's 15-minute stall after an agent crash in single-box regions. *Recommendation:* yes, behind the fence. |
| +3. **Is one SQS long-poll per box acceptable?** It is the one new poll, on SQS, not S3, at about $0.05 a month per box. *Recommendation:* accept it. The alternative is one elected consumer per region, which adds an election to save about $0.05. |
| +4. **Accept the cross-region bounce?** A request with a body that lands in the wrong region just after a holder change gets one 503, because A9 only retries GET and HEAD with no body. *Recommendation:* accept it for part 1. Part 2's replicas, or a later in-region second hop, can remove it. |