carlos / platform Public

spec rev 2: region HA without claims, Astra round 1 and builder check

Release marker in lock.json as the only proof a local copy may be kept
(replaces rev 1's checksum rule, which the pinned litestream cannot
support); expiry never lets another box acquire; HRW preferred wake box;
duties owned by holder or releaser with acknowledged duty-file transfer;
key and token producers moved to the holder; moves and seed imports
refused in HA regions; old box stopped, not terminated, until
acceptance; hairpin redirect; budgets with pagination and reader fan-out.
Same-box takeover and the write fence are dropped. Disposition table at
the top.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 3da049742c8708913d13a80c187d682ed9ff0697 parent 6672180
1 file changed, +493 −405
  • docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md +493 −405
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 8fd1e6c30..ea42ef253 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,27 +1,57 @@
# 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.
+Design, 2026-10-26, **rev 2**. Branch `design-region-ha-no-claims`, cut from `origin/main` at ddf3b929. Status: draft for Astra round 2. 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.
+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 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.
+**Rev 2** answers Astra round 1 (`docs/superpowers/notes/reviews/ASTRA-FINDINGS-region-ha-no-claims-r1.md`, 66721809, NOT READY, cited **astra-1.N**) and a builder check (cited **builder-N**), with the coordinator's dispositions. Its central change is that a local copy is kept only on positive proof: a release marker in the lease object (§5). Rev 1's checksum comparison is cut. Rev 2 also cuts scope:
+- moves into and out of HA regions, and seed imports, are refused (§14);
+- same-box takeover (rev 1's A16) is dropped;
+- the write fence (rev 1's A11) is dropped, because no other box can now acquire while the owner may still run.
+
+| Finding | Disposition | Where |
+|---|---|---|
+| astra-1.1 checksum proof absent in litestream v0.5.14 | Accepted. Checksum reuse is cut; the release marker replaces it. | §5 |
+| astra-1.2 expiry bypasses "never take over a hung box" | Accepted. Expiry never lets another box acquire. Clock-skew bound added. | §9.4, §9.7 |
+| astra-1.3 A16 relies on a proof that skips nested and unit layouts | Accepted. A16 dropped; listed as a later improvement. | §9.6 |
+| astra-1.4 files marker does not prove the tree | Accepted. A stat digest at release, else a restore into a clean tree. | §5.3, §8 |
+| astra-1.5 the ~1 s loss window is not implemented | Accepted in part. The stream class captures every second; the other classes' loss is stated, not refused. | §5.5 |
+| astra-1.6 key and token producers missed | Accepted. Every producer is listed and moved to the holder after restore. | §7.3 |
+| astra-1.7 HRW strands once-timers | Accepted. Duties belong to the holder or the releaser. | §7 |
+| astra-1.8 due handoff can delete the only trigger | Accepted. Duty files, an acknowledged transfer, and sidecars carried. | §7.4 |
+| astra-1.9 timeline omits backoffs and the boot grace | Accepted. Backoffs follow holder identity; grace kept separate; new test. | §7.2, §9.8, §10, §21 |
+| astra-1.10 forwarded requests cannot take over | Accepted. The receiving box takes over locally; cross-region views defined. | §4.3, §6.4 |
+| astra-1.11 records carrying `Unit` are adopted | Accepted. Unit, platform and non-hibernating socket records are excluded from serving boxes. | §6.1 |
+| astra-1.12 relaxing offline moves is unsafe | Accepted. Moves involving HA regions are refused. | §14 |
+| astra-1.13 rollback uses a terminated box | Accepted. The old box is stopped, and terminated after acceptance. | §13 |
+| astra-1.14 #199 not closed | Accepted. The marker carries the lifetime; reused names with leftovers are refused. | §5.3, §11 |
+| astra-1.15 backfill cannot acquire a held lease | Accepted. Publish through the live handle; readiness is publication success. | §8.4 |
+| astra-1.16 budgets understated | Accepted. Pagination, the expired-lock acquire, reader amplification. | §18 |
+| astra-1.17 A8 does not honour H4; drain blocks on headroom | Accepted. The chooser, and drain always forwards. | §6.3 |
+| builder-1 warm wakes need a positive local proof | Accepted. The release marker. | §5 |
+| builder-2 cold wakes scatter, so copies rarely match | Accepted. The HRW box is the preferred wake box. | §6.3 |
+| builder-3 NLB hairpin with client IP preserved | Accepted. Ingress addresses are redirected to the local edge. | §12.4 |
+| builder-4 edges writes fan out to every reader | Accepted. Duty files stay outside the change index; costs counted. | §7.4, §18 |
+
## 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.
+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 is terminated, its instances come back on the others within a few minutes. A stream-class database loses about the last second of writes; other classes lose more (§5.5).
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).
+- part 2: stateless replicas of one app across boxes;
+- autoscaling beyond a fixed-size group;
+- cross-region failover (#251);
+- live moves, which are parked;
+- offline moves and seed imports touching an HA region (refused, §14);
- 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.
+These stand from spec 1 and spec 2.
| # | Ruling |
|---|---|
@@ -29,587 +59,645 @@ These stand from spec 1 and spec 2. They are not reopened here.
| 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. |
+| H6 | Files durability follows the paid plan: continuous on the top plan, snapshots on the bottom one, as a per-app 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. |
+| H21 | One Network Load Balancer per region, TCP passthrough on 80 and 443, created with the region's existing EIP. |
| 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 |
-|---|---|
+| H24 | IE's current box becomes a fixed platform box outside the group, with no tenants, and its own EIP for the relay and MX. |
+| Roll order | Dev boxes, dev console, check, flagship boxes, flagship console. |
| 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. |
+| N-HA2 | Replaces H25. Once every instance's DB and files are in S3, the old box joins the load balancer as an ordinary member. Its instances are slept one at a time and wake on the group boxes. The old box is removed once empty. IE's platform box stays outside the group. |
+| N-HA3 | Failover is "a few minutes, lower is better", met **without shortening every lease**. 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.
+Each is the author's or the coordinator's. 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. |
+| A1 | The local-copy rule (§5) and the expiry rule (§9.4) apply on every box with `CARLOS_REGION_HA`. Single-box regions keep today's behaviour until they turn it on. | The rules cost requests, and only multi-box regions need them. |
+| A2 | **Release marker** (supersedes rev 1's A2). A graceful release overwrites the lease object with a "released" record. A box keeps its local DB and files only when that marker names it, the lifetime matches, and the local state is provably unchanged since it was written. Anything else is set aside and restored into a clean tree. | It is a positive proof with no checksum and no extra S3 request on the warm path, and it closes #199's local-copy half. |
+| A3 | The lease owner string is `box/v1;ref=<ref>;iid=<instance id>;pid=<pid>`. | Litestream's default `hostname:pid` does not name the EC2 instance. |
+| A4 | Boxes confirm terminations themselves, from the existing queue and `ec2:DescribeInstances`. One SQS long-poll per box is accepted (about $0.05 a month per box). | The box role holds both rights already. The console is one box in IE. |
+| A5 | Takeover is per lease, at the first need after confirmation. There is no bulk pass. | Nothing lists a box's leases cheaply, and the first need comes within seconds. |
+| A6 | The box that confirms a termination adopts the dead box's duties (§7.4) and only then deletes its duty and edges files. | The transfer is acknowledged before the source goes. |
+| A7 | A box learns a lease holder from the lease itself and from a peer's 503 header. Awake sets are not published. | No steady-state requests. |
+| A8 | Each instance's HRW box (A10) is its **preferred** cold-wake box when serving. If it is ineligible, `ChooseRoomiest` over the cached eligible serving set chooses. | The preferred box usually holds the matching release marker, so wakes stay warm. |
+| A9 | The receiving box may forward once more, to the holder a 503 names, for a GET or HEAD with no body. The cross-region bounce, and a rare 503 for a POST during a membership change, are accepted. | Removes most stale-cache bounces without a new hop protocol. |
+| A10 | Rendezvous hash (HRW) over a region's serving boxes chooses where an instance with no holder and no releaser starts, including always-on workers. | One deterministic starter per instance. |
+| A11 | While an instance is awake its duties belong to its lease holder. While it sleeps they belong to the box that released it. | Duties follow the copy that has the state. |
+| 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. |
+| A13 | The platform box adopts tenant records but never wakes a tenant, and it is not a load balancer target. | The console's local-registry reads keep working. |
+| A14 | Region membership is "a verified box with a fresh edges file in that region". Auto Scaling membership is not an input, and nothing is enrolled. | Enrolment was the claim's. |
+| A15 | `CARLOS_REGION_HA` stays the box switch, redefined claim-free, once the claim code under it is deleted. | It already gates plan 2a's claim-free parts. |
+| A16 | H3's window applies to the stream replication class, whose local capture runs every second under HA. Other classes lose up to their interval, stated plainly. | The capture cadence costs CPU, not S3. |
+| A17 | Files sync is plan 1a's `hostfiles`, under the instance's hibernate prefix with one fixed generation. | 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. |
+| A19 | The old box drains before the EIP cut-over, and is then stopped, not terminated, until acceptance. | Rollback inside the window just starts it again. |
+| A20 | The no-capacity refusal applies at create only. A wake of an existing instance is never refused for headroom: drain and platform ingress always forward to a serving peer. | An existing instance down is worse than an overfull box. |
+| A21 | Each box redirects traffic it sends to its own region's ingress addresses to its local edge. | NLB hairpin connections fail when the client IP is preserved. |
## 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.
+Every box in a region adopts every tenant host record of its region, as today (`internal/provision/reconcile.go:443-457`), except records the serving boxes must not run (§6.1). 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 forwards the request once to the box that holds it. It forwards a cold wake to the host's preferred box first. A graceful sleep leaves a release marker in the lease object, naming the box and the exact state it released. Only that box, with that state untouched, may reuse its local copy. Every other wake restores from S3 into a clean tree. Another box may take a lease only from a release marker, or from an owner EC2 has confirmed terminated. Expiry alone is never enough. A hung box therefore keeps its instances down until its group terminates it. A sleeping instance's timers belong to the box that released it, and they are handed on, with an acknowledgement, when that box leaves.
-## 4. Identity, lease owner and the region view
+## 4. Identity, lease owner and views
### 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`).
+Fixed boxes keep their status label. Group boxes use `g-` plus a hash of account and instance id (`internal/host/boxreference.go`, `GroupBoxReference`; R1 moves it into `internal/host`). Each box publishes its signed identity record, `control/boxes/<ref>.json` (`internal/boxid/record.go:21-35`), at 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.
+Today the owner is litestream's `hostname:pid` (`litestream@v0.5.14/s3/leaser.go:52-65`), copied by `createLease` (`internal/lease/createlease.go:32`). The lease package sets it to `box/v1;ref=<ref>;iid=<instance id>;pid=<pid>` instead, taking the instance id from the identity document the agent already reads (`boxrecord.go:65-112`). The owner format ships unconditionally, since it changes nothing a reader acts on today.
-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. Old `hostname:pid` owners, tombstones (`moved:<id>`, `internal/lease/tombstone.go:45-47`) and anything else are never acted on by another box (§9.4).
-- 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 Views
-### 4.3 The region view
+For any region r, a box's **view(r)** is the set of boxes whose edges file is no older than 15 minutes (`internal/boxchoice/policy.go:16-83`), with region r, the same placement and data bucket, and the deployment's secrets-key fingerprint. Every box folds every region's edges files already (`internal/edge/homemap.go:464-527`, `:791-867`), so a view costs nothing new.
-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.
+**serving(r)** is view(r) minus boxes whose role is `drain` or `platform`. A box validates a holder named for a host in region r against view(r), for its own region and for cross-region callers alike (astra-1.10). The console also verifies identity records, as `internal/console/boxselect.go:147-174` 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.
+- **The 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`, covers boxes with no object of their own, so a replacement launched during a rollback takes the region's role.
+- **Who writes it.** Only an operator, through `carlos system box role <ref|@region-code> <role>` and its console door. These replace plan 2a's `system_roles.go` and `internal/console/apiboxroles.go`.
+- **How boxes read it.** `ChangeScope` gains `control/box-roles` (`internal/release/changeindex.go:53-76`). A box reads its own and its region's object at start, and whenever that scope moves.
+- **Publication.** A box publishes its effective role, and `drained: true` once a drain is complete (§13), in new additive edges fields. Readers that do not know the fields treat the box as `serve`.
-## 5. Wake freshness
+## 5. Local copies: the release marker
### 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.
+`restorePlain` keeps any database file on disk (`internal/activator/backend_exec.go:819-820`). That is safe only while a region has one box (`internal/activator/activator.go:2302-2310`). With N boxes, a box can wake a host from an old copy and serve stale data. Litestream then uploads a different history under transaction ids S3 already holds (`litestream@v0.5.14/replica.go:170-176`, `:208-215`).
+
+Rev 1 compared checksums. Litestream v0.5.14 writes LTX files with no database checksums (astra-1.1), so that proof does not exist, and it is cut.
+
+### 5.2 Writing the marker at release
+
+Today a graceful release deletes `lock.json` (`Replicator.Close`, `internal/lease/lease.go:497-524`, through `ReleaseLease`, `s3/leaser.go:171-200`). On an HA box it instead does the following, in order, after the final database sync and the final files and wake-state publish have both succeeded:
+1. **The local record.** Write `<db>.release.json` beside the database, and fsync it. It holds:
+ - the marker fields below;
+ - the database file's identity: inode, size, `mtime_ns`, `ctime_ns`, and that its `-wal` is absent or empty after the checkpoint;
+ - a **files tree digest**: a SHA-256 over every entry of the files directory and the platform files, each as (path, type, mode, size, inode, `mtime_ns`, `ctime_ns`). It reads metadata only, never contents.
+2. **The marker.** Overwrite `lock.json` by a conditional PUT, with `If-Match` on the held lease's current ETag. The marker is `{generation, expires_at: 1970-01-01T00:00:00Z, owner: "released/v1;ref=<ref>;iid=<iid>", carlos_release: {v:1, box, iid, lifetime, txid, files_gen, at}}`:
+ - `lifetime` is the record's incarnation id (`provision.Incarnation`, as `internal/host/runexec.go:101-106` computes it);
+ - `txid` is the replica position after the final sync;
+ - `files_gen` is the last manifest published, as a sequence number and hash.
+
+The marker is safe for every existing reader:
+- Litestream decodes `lock.json` without refusing unknown fields (`s3/leaser.go:217-220`), and it reads an expired lock as free (`:96`).
+- The package's own `LockState` (`internal/lease/lockstate.go:94-98`) and the tombstone code's `leaseFree` (`tombstone.go:68-77`) also read it as free. That is the same trick `LiftTombstone` uses.
-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.
+So old binaries and non-HA boxes see a marker as a released lease.
-### 5.2 The rule
+**Failures.**
+- A 412 means the lease is no longer ours: no marker, and the local copy will be set aside next time.
+- A failed PUT is retried by the existing owed-release path (#292, `lease.go:326-358`), with the same condition.
+- If the final sync or publish failed but S3 is reachable, the marker is written with `clean: false`. Another box may then acquire, but nobody keeps a local copy, and the writes that did not reach S3 are lost.
+- If S3 is unreachable, no marker is written. The lease stays held until it expires, and then only this box may take it again (§9.4).
-It runs under the lease, after `Acquire` and before `Replicate`, where `restorePlain` runs now (`activator.go:2311`).
+### 5.3 Keeping or restoring at wake
-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).
+The HA acquire (§9.4) reads `lock.json` anyway, so the decision costs no extra request. A box **keeps** its local database and files only if all of these hold:
+- the lock is a clean release marker naming this box's reference and instance id;
+- its `lifetime` equals the current record's incarnation;
+- its `txid` and `files_gen` equal the local record's;
+- the database file's identity is unchanged, with no WAL content;
+- the files tree digest, recomputed now, is unchanged.
-**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.
+`ctime` cannot be set from userspace, so a write, rename or chmod since the release breaks the proof.
-The seeded path (`seededRestore`) applies the same rule to any local database it would keep.
+**In every other case,** it renames the local database and files directory aside (`<db>.stale`, `<host>.stale/`, newest kept), purges litestream's local state (`PurgeLocalDBArtifacts`, `backend_exec.go:831`), and restores. That covers no marker, another box's marker, an expired lease, a crash, a different lifetime, `clean: false`, and no replica. The database restores as today (`backend_exec.go:853`). The files restore into a new empty directory, which then takes the old one's place. So `hostfiles.Restore`'s preservation of unlisted paths (`internal/hostfiles/restore.go:42-47`) never applies (astra-1.4).
-**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.
+**What this loses, stated plainly.**
+- After an agent crash, the box re-takes its own lease when it expires (§9.4). It then restores, losing the writes not yet in S3: about a second for the stream class.
+- An instance whose box crashed before its first replication starts fresh. Everything it wrote is lost.
+- No copy is ever kept because it is "ahead" of S3.
-**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.
+**#199.** An older lifetime's copy can never match, on any box, whether or not that box saw the delete. §11 refuses the S3 half.
+
+### 5.4 Cost
+
+On the warm path: no LIST and no checksum. The acquire costs one GET and one conditional PUT (§9.4), against today's single create PUT. The release costs one PUT, where today's DELETE was free. So each sleep-and-wake cycle on an HA box costs 1 GET and 1 PUT more than today (§18).
+
+Turning HA on for a box writes no markers for leases released earlier. So each of its instances restores once, on its first HA wake.
+
+### 5.5 The loss window (H3, astra-1.5)
+
+The local WAL capture runs every 10 s (`lease.go:96-104`, applied at `:406`). On HA boxes, the stream class (`activator.go:428-431`) captures every second instead: one local WAL check per second per awake instance, CPU only, no S3.
+
+The batched and daily classes keep their 5-minute and 24-hour sync intervals (`activator.go:438-443`). In a failover they lose up to that interval. The console states it beside the class, and the terminate drill measures committed-write loss for each class (§21).
## 6. Who serves
-### 6.1 The invariant
+### 6.1 What serving boxes run (astra-1.11)
+
+A box with role `serve` in an HA region never routes locally:
+- a record carrying `Unit` (copied by `RouteFor`, `reconcile.go:478-483`);
+- a platform record;
+- a non-hibernating socket route.
-An awake instance runs only on its lease holder. Every other box forwards to it.
+Those records are not minted there, so a request for one misses locally and is backhauled to the box that publishes it (`internal/edge/edge.go:1611-1645`). Only the platform box runs them. A non-hibernating socket instance has no lease, so a create of one in an HA region is refused, and an existing one blocks that region's readiness (§13).
-### 6.2 The decision at box A, for a request to host H
+### 6.2 The invariant and the decision
-Every box in the region has H's route, so A always has one.
+An awake instance runs only on its lease holder. At box A, for a request to tenant host H:
+1. **Awake or waking on A:** serve.
+2. **A's holder cache names B in view(H's region):** forward to B.
+3. **Otherwise A runs the HA acquire (§9.4)**, if A would wake H here (§6.3). If A would not, it runs `LockState`, one GET (`lockstate.go:47-79`).
+4. **The outcome:**
+ - acquired: wake H on A;
+ - free but not for A: forward to the box §6.3 chose;
+ - held by an owner in view: forward to it, and cache it;
+ - an owner confirmed terminated: take over (§9.4) and wake;
+ - anything else: 503, with `Retry-After: 10`, and the suspect alert (§20).
-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 (A8, astra-1.17)
-### 6.3 Where a cold wake happens
+1. H's **preferred box** is its HRW box: the box in serving(region) with the highest `sha256(H + "\x00" + ref)`. If it is eligible, the wake happens there. A forwards to it, or wakes locally if A is it. Eligible means the existing policy: at least 15% of memory and 10% of disk free, and a fresh edges file (`policy.go`).
+2. If the preferred box is ineligible, `boxchoice.ChooseRoomiest` over the cached eligible serving set chooses (`policy.go:77-99`).
+3. If no box is eligible, an existing instance is still woken, on the preferred box, and the over-capacity alert fires (A20).
+4. **Drain and platform ingress always forward** an existing instance to a serving peer, whatever its headroom.
+5. Spread comes from the hash, which scatters an app's instances across boxes.
-- 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 (astra-1.10)
-### 6.4 Forwarded requests
+A forwarded request carries the existing verified hop marker (`edge.go:3097-3131`), and the box that receives it **never forwards it again**. That box is in the host's home region, so it can act on the lease itself:
+- H awake there: serve.
+- HA acquire succeeds (absent lock, release marker, or its own expired lease): wake.
+- Owner confirmed terminated: take over and wake.
+- Otherwise: 503, `Retry-After: 1`, and `X-Carlos-Holder: <ref>` when its probe saw a live holder.
-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.
+The existing no-route refusal (`homemap.go:1359-1362`) is unchanged.
-### 6.5 One retry by the receiving box (A9)
+### 6.5 One retry by the first 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.
+On that 503, the box that first received the request may forward once more, to the named holder, when the holder is in view(H's region) and the request is a GET or HEAD with no body, or an upgrade that has not switched protocols. That is at most two forward attempts, never an onward forward, and so 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.
+Each box keeps an in-memory map from host to holder reference, fed by the owner in a held-lease answer and by `X-Carlos-Holder`. An entry goes when this box takes the lease, when the holder answers "not here", when a dial fails, or when the holder leaves the view. It has a one-hour ceiling and holds at most 50,000 entries. It needs no S3 reads.
-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 Races and lease loss
-### 6.7 The concurrent cold-wake race
+- **The concurrent cold-wake race.** Both boxes' conditional PUTs target the same ETag (or absence), so one wins and the loser reads the winner and forwards. The winner queues the forwarded request behind its wake (`awaitWake`, `activator.go:1559-1564`).
+- **Lease loss.** A failed renewal latches the loss (`internal/lease/health.go:135-147`), and the activator stops the instance at the next request or sweep (`activator.go:1540-1551`, `:4606-4609`).
+- **Where it goes in the code.** The work slots into the activator's mesh seam (`activator.go:5479-5483`) and its held-lease branch (`:2275-2280`), and the edge acts on it through `backhaulTo`.
-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`).
+## 7. Duties
-### 6.8 Where it goes in the code
+### 7.1 Who owns them (A11)
-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.
+| Instance state | Owner of its duties |
+|---|---|
+| Awake | Its lease holder. |
+| Asleep | The box that released it. That box's unsuperseded local release record says so. |
+| Neither: never woken, or held by a dead box | Its HRW box in serving(region) (A10). |
-### 6.9 Requests from another region
+A box acts on a duty only after an HA acquire, which every duty needs anyway, since each one wakes or reaches the instance. If the acquire shows the instance held by a live peer, or released by another box, this box drops the duty for that host. That is how an older copy of a due entry stops being acted on, at one GET per conflict.
-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).
+### 7.2 What the duties are
-### 6.10 A holder that loses its lease
+| Work | Today, with N boxes | Under this spec |
+|---|---|---|
+| **Schedule ticks.** The converger gives every box timer rows (`internal/schedule/converge.go:18-20`). | Every box delivers every tick. | Only the duty owner's runner delivers. A non-owner advances its own row past a tick once the tick is 15 minutes old. A new owner delivers every younger tick it has not advanced. A change of owner can deliver a tick twice (H7). |
+| **Due wakes** (`next_due`, `activator.go:4996-5050`) | Only the box that slept the instance knows the time. | The releaser keeps them, as today, and also lists them in its duty file (§7.4). |
+| **App once-timers** (`internal/schedule/control.go:15-19`) | Kept in the waking box's registry only. | They stay in the holder's or releaser's registry. Their earliest deadline goes into `next_due` and the duty file. The rows travel in the wake state (`hostfiles.ExportWake`/`ImportWake`, `internal/hostfiles/wake.go:47,84`), which is continuous (S1 §5.6). A new owner imports them before it delivers. |
+| **Sidecar due wakes**, a native sidecar's only timer source (`activator.go:5032-5044`) | Excluded from edges files (`internal/host/edgesfile.go:481-500`). | Carried in duty files as non-routable entries (`kind: sidecar`), never in the hosts map. |
+| **Always-on workers:** the boot pass (`internal/host/agent.go:705-724`) and the sweep (`activator.go:5052-5084`) | Every box tries; the rest retry every sweep. | The holder runs one. With no holder, its HRW box starts it. A box that met a live holder skips it until that holder leaves the view. Termination confirmation cancels the wait at once, with no periodic probing (astra-1.9). |
+| **Co-spawn sidecars** (`activator.go:17-25`) | Start on the box that woke the instance. | Unchanged: the holder. |
+| **`carlos run`:** the record names one picking box (`runexec.go:109-119`) | Any box may pick. | Only the duty owner picks. |
+| **WebSockets** | Held on the waking box. | On the holder. A forwarded upgrade rides the backhaul; the plan confirms it does. |
+| **Static sites** and **housekeeper duties** | Every box, and one election. | Unchanged. |
-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.3 Keys and tokens (astra-1.6)
-## 7. Work with no request behind it
+Every producer of `<host>.env` secrets runs **only on the lease holder, after the restore** of §5.3:
+- the launch paths: `prepare.go:83-87`, `backend_exec.go:1034-1039` and `:2130-2137`. They mint an admin token or instance key only when the restored platform files hold none, and only if S3 answers "no such key" for the host's files manifest;
+- the schedule runner's token preparation: `runner.go:564-586` through `scheduleToken` (`internal/host/schedule_wiring.go:186-205`) runs `EnsureAdminToken` before delivery on any box, and its fence grants no durable authority (`internal/activator/scheduled_token.go:3-6`). On HA boxes, preparation moves to the delivering holder, after its restore;
+- the instance-key backfill (`internal/host/instancekeys.go:14-27`, `:75-85`): disabled on HA boxes, since every launch mints anyway;
+- `claim_snapshot.go:120`: deleted with the claims.
-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`.
+`instance.key`, `report.token` and `<host>.env` are continuous on every plan (H6). A newly minted key is published durably, with the manifest PUT acknowledged, before the app starts. A failed publish fails the launch.
-| 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. |
+### 7.4 Duty files and their transfer (astra-1.8, builder-4)
+
+**The file.** Each box keeps `control/duties/<ref>.json`: one entry per host whose duties it owns while asleep, `{host, kind, next_due, released_at, lifetime}`.
+- It is written when the set changes, batched to at most once a minute.
+- It is **not** a change-index scope, so no reader re-reads anything when it changes.
+- Only a box adopting another box's duties reads it.
+
+**Transfer.** When a box leaves, through termination confirmed (§9.3) or `drained: true` (§13), its **adopter** takes over. The adopter is the serving box with the highest `sha256(departing ref + "\x00" + ref)`. It:
+1. reads the departing box's duty file (one GET);
+2. merges the entries into its own set, keeping the newest `released_at` per host;
+3. writes its own duty file, and waits for the PUT's success;
+4. only then deletes the departing box's duty file, and on termination its edges file.
+
+If the adopter dies part way, the source is still there, and the next adopter repeats the transfer. The merge is idempotent. An adopted host's marker still names the departed box, which counts as a release, so the adopter's acquire succeeds and restores from S3.
+
+**Delay.** A due entry released in the last minute before a termination can be up to a minute stale in the file. Its wake state in S3 is current, and the adopter's first acquire for the host brings its timers back.
## 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.
+- **App files:** the files directory, `<instance dir>/<host>/` (`internal/layout/plan.go:196`).
+- **The H6 trio:** `instance.key`, `report.token` and `<host>.env`, plus the wake state.
+- **Not synced:** `<host>-sidecar.env` and `<host>.config.env`, which are rendered from the bucket on every box.
-Today nothing claim-free publishes files. `hostfiles.Run` has no production caller, and every caller of the package is claim, moves or relocation code.
+Today nothing claim-free publishes files. `hostfiles.Run` has no production caller.
### 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).
+The location is the host's hibernate prefix (`activator.go:138-150`) plus `files/0/`. Objects are immutable and the manifest is replaced by compare-and-swap (S1 §5.6). Only the lease holder writes, and nobody else can acquire while it might still run (§9.4).
-- **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.
+- **At wake:** §5.3 keeps the tree or restores it into a clean directory, platform files first, before any key mint or app start.
- **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.
+ - continuous plan: `hostfiles.Run` (`internal/hostfiles/run.go:22,44`) at the cadence of §22 Q2;
+ - snapshot plan: a full publish every `files_snapshot_interval` (15 minutes by default) when a local digest says the tree changed;
+ - the H6 trio and the wake state: continuous on every plan.
+- **At sleep:** a final publish, then the release (§5.2).
### 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
+`files_durability` (`continuous` or `snapshot`, default `snapshot`, H8) and `files_snapshot_interval` become per-app platform settings, read with the app's configuration. An operator door sets them; Carloku maps its plans to them. Console text goes through copy review.
-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).
+### 8.4 Backfill (astra-1.15)
-**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.
+When `CARLOS_REGION_HA` turns on:
+- for each **awake** instance, the activator's files publisher runs an initial full publish through the live lease handle it already holds;
+- for each **sleeping** instance, the box runs the HA acquire, publishes, and releases with a marker.
-**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.
+Each host records `files_published_at` only on a successful publish. Readiness counts only that, so a skipped or failed publish keeps it false.
-## 9. Termination and takeover
+## 9. Termination, takeover and expiry
### 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
+- **The event.** The EventBridge rule forwards EC2 `terminated` changes to an SQS queue (`infra/modules/region-host/main.tf:835-888`). The box role can receive from and delete on it (`main.tf:890-904`). Each HA box long-polls it with 20-second waits. A message about an instance that is not a box of this deployment is deleted.
+- **Suspicion.** A forward to a holder fails to connect within 2 seconds, or a lease names an owner that is not in view.
-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`.
+### 9.2 Confirmation
-- 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.
+One `DescribeInstances` for the owner's instance id in this box's AWS region (`internal/termfence/fence.go:154-166`). The box role has the 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 identity document, and state exactly `terminated`.
+- Absence is not evidence (`fence.go:86-90`), and `shutting-down` is not terminated.
+- An event only prompts a describe.
+- A positive answer is cached for 24 hours, a negative one for 10 seconds.
-### 9.3 What confirmation does
+### 9.3 After confirmation
-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).
+The confirming box:
+1. becomes the adopter or tells the adopter (§7.4);
+2. the adopter deletes the dead box's edges file on its ETag once its duties are durable. That bumps `control/edges` (`changeindex.go:71`), and every box drops the dead box from its views within about 30 seconds;
+3. the box counts the confirmation (§20) and cancels any duty backoff keyed to that box (§7.2).
-Leases are not touched in bulk (A5). Each is taken at its first need.
+### 9.4 The HA acquire, and why expiry is not enough (astra-1.2)
-### 9.4 The takeover write
+On an HA box, the lease package's acquire reads first: one GET of `lock.json` with its ETag. Then:
-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)
+| Lock state | Action |
+|---|---|
+| Absent | Create, with `If-None-Match: *`. |
+| A release marker, clean or not | Conditional PUT, with `If-Match`. |
+| Held and unexpired | A held answer naming the owner (§6.2). |
+| Expired, owner is this box's instance id | Conditional PUT. This is today's same-box recovery after an agent crash, which waits out the TTL. |
+| Expired or unexpired, owner confirmed terminated (§9.2) | Conditional PUT: the takeover. |
+| Anything else | Refused: another box's expired lease, an old-format owner, or a tombstone. |
-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`).
+The refused cases keep the instance down until its owner is terminated or the owner itself re-takes the lease. **Expiry alone never lets another box acquire.** That holds for a stopped agent whose app processes still run, a frozen process, and a box that has lost S3.
-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.
+- A 412 on any write means re-read and decide again.
+- A successful write starts the renewer as `AcquireTTL` does (`lease.go:206`). The wake continues from step 1.5 (`activator.go:2288-2301`), then §5.3.
+- Only a box that would wake the instance under §6.3 takes over.
+- Non-HA boxes keep today's `AcquireTTL`, which accepts any expired lock (`lease.go:193-195`).
-### 9.6 Same-box takeover (A16)
+**Precondition for a region's HA readiness (§13):** no host's lock has an old-format owner. Such a lock would stay refused until an operator terminated its box.
-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.5 The cost of the rule
-### 9.7 A hung box that is not terminated
+A hung box's instances wait for the group to replace it. That takes 2 to 5 minutes once the box is past its boot grace, and the grace remainder plus that inside it (§9.8).
-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.
+A box that is alive but has lost S3 keeps its instances down until someone terminates it. Its health stays 200 by design, because a shared dependency must never terminate boxes (S2 §6). The suspect-holder alarm (§20) fires after 10 minutes. The runbook step is to terminate that instance in its group, which H1 counts as death. This is an accepted, stated limit.
-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.6 Same-box takeover: dropped (astra-1.3)
-### 9.8 A box that is alive but has lost S3
+Rev 1's A16 is dropped. After an agent crash, a box re-takes its own lease only when it expires, so instances wait up to 15 minutes, as today. **A later improvement** may shorten that, once a real emptiness proof exists for nested, rootfs and unit layouts; `wakeHostProven` skips those (`internal/activator/opset.go:437-453`).
-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.
+### 9.7 Clock skew
-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.
+Expiry now matters only for a box re-taking its own lease, which uses one clock. The margin is still bounded:
+- chrony (Amazon Time Sync) is required on every box;
+- the safety margin (5 s, `health.go:19`) must exceed twice the maximum offset, so the maximum allowed offset is 2 s;
+- each box publishes its chrony offset, and an alarm fires above 1 s (§20).
-### 9.9 Timeline
+### 9.8 Timeline
-These are estimates. Dev measures each one before any flagship region (§18).
+These are estimates; dev measures each one (§21).
-| Phase | Box terminated through the API | Box hung |
+| Phase | Box terminated through the API | Box hung after its boot grace |
|---|---|---|
-| 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 |
+| The load balancer stops new connections | 20 to 30 s | 20 to 30 s |
+| The group terminates the box | not needed | typically 1 to 2 min after it turns unhealthy |
+| EC2 reports `terminated`; the event arrives | 30 s to 2 min | 30 s to 2 min after the group's terminate |
+| First request: acquire, describe, takeover, restore | about a second, plus the restore | 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 |
+| Always-on workers, ticks, due wakes | one sweep (30 s or less) after confirmation; backoffs cancelled | the same |
+| Worst case, event lost | the next request's dial failure confirms at once; with no requests, view ageing (15 min) | 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).
+- **A hang inside the boot grace.** The group's grace period suppresses replacement after the box is in service (AWS documents this), so the box is down for the rest of the grace plus the hung-box time. The grace is kept as short as the measured boot (§10), and it is reported apart from the serving bound.
+- **A graceful termination** needs no takeover: the shutdown sleeps every instance and writes markers (`activator.go:5186-5194`).
## 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.
+Keep `internal/lbhealth`, with its six conditions (`internal/lbhealth/lbhealth.go:154-178`), and its endpoint (`internal/edge/lbhealth.go:21-39`). A **serving latch** replaces the claim's `SetHosting` caller (`internal/host/claimwiring.go:102-106`).
-- **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).
+- **Set** once all of these hold: `host.env` loaded; the first reconcile pass for the region done; the first edges file published with the box's role; and the termination consumer started.
+- **Cleared** first in shutdown (`activator.go:5190`).
+- A `drain` box stays healthy until it is removed, because it forwards. The `platform` box is not a target.
+- **The boot grace** is the measured boot time plus a small margin, starting at 8 minutes, since there is no enrolment. It is kept separate from the serving failure bound.
+- **Not added:** S3 reachability (S2 §6).
-## 11. Placement inputs and capacity
+## 11. Placement inputs, capacity and create refusals
-- **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.
+- **Published by each box:** headroom in its edges file (`internal/host/headroom.go:13-16`), whenever `CARLOS_REGION_HA` is on; its role; and its private address. The private address comes from plan 2a, split out of the claim code (§16.2).
+- **The console** reads live edges files and verifies identity records (`boxselect.go:147-174`). It publishes `Carlos/Region EligibleBoxes` (`internal/console/awsregionmetric.go:56-70`) from console start when `CARLOS_REGION_METRICS=cloudwatch`, instead of from `StartClaimRecoveryPass` (`internal/console/hostclaimops.go:44-61`). `regioncapacity.go` counts with the shared policy.
+- **The create door,** for an instance, a standalone sidecar, or a first route through domain attach, in an HA region:
+ - refuses with 503 and the approved no-capacity message when no serving box is eligible, alerting at most once per region per hour (A20);
+ - refuses a non-hibernating socket instance (§6.1);
+ - refuses a hostname with any predecessor object under its hibernate prefix: LTX files (the existing rail, `internal/console/createleftovers.go:53-75`), anything under `files/0/` (which holds the platform secrets), or a `lock.json` whose release marker names another lifetime (astra-1.14). The refusal names the leftover.
+- **Wakes are never refused for headroom.** Group membership is not an input.
## 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.
+Today the module makes one `aws_instance` and one `aws_eip` (`main.tf:536-587`). Group mode adds:
+- **A launch template,** as S2 §4: the same AMI, type, root volume with delete on termination, security group and profile; IMDSv2 with hop limit 1; an auto-assigned public IPv4 for cross-region dials. The user data names the deployment, bucket, region and AWS region.
+- **An Auto Scaling group:** `min = max = desired = box_count` (H5); at least two zones; health checks ELB plus EC2; the grace from §10; no instance refresh; `AZRebalance` suspended.
+- **A Network Load Balancer:** one subnet mapping per group zone. Zone A carries the region's existing EIP, as a standalone `aws_eip` with `prevent_destroy`. Other zones get new, unpublished EIPs. Cross-zone on; TCP 80 and 443; instance targets, so the client IP is kept; deregistration delay 30 s; health HTTP on 80 at `/.carlos/lb-health`, every 10 s, 2 healthy and 2 unhealthy.
+- **The security group:** 80, 443 and the backhaul port from the VPC CIDR.
+- **The termination rule and queue:** unchanged. **Alarms:** §20.
### 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).
+ - SSM `GetParameter` and `GetParametersByPath` on `/carlos/<deployment>/<region>/*` and `/shared/*`, with `kms:Decrypt` under the `ViaService` and `PARAMETER_ARN` conditions;
+ - the existing SSM Deny kept;
+ - an explicit HA statement for `ec2:DescribeInstances`;
+ - no Auto Scaling, ELB or EC2 write right.
+- **Console:** nothing new.
+- **Operator seeding:** `ssm:PutParameter` and the KMS actions (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.** This includes the nftables gate that keeps tenants away from IMDS credentials.
+2. **Configure.** Fetch the bootstrap binary and check its SHA-256 from SSM. Then `carlos system host-env write` (`internal/hostenv`, plan 2b), minus `CARLOS_HOST_CLAIM*`.
+3. **Install.** `carlos bootstrap`, then `carlos system install-channel` (`internal/host/installchannel.go`), without its guard and floor checks.
+4. **Start the agent.** No joining mode, enrolment or guard-arm.
-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.
+A failed step leaves the box never healthy, and the group replaces it.
-### 12.4 The platform box and the cut-over
+### 12.4 Hairpin (A21, builder-3)
-- **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.
+With client IP preserved, a connection from a box to its own region's NLB address that the NLB routes back to the same box fails. Callers on a box include the console, sidecars, webhooks and tenant code.
-### 12.5 Provider boundary
+So each box installs an nftables output rule that redirects TCP 80 and 443 destined to its region's ingress addresses (the NLB EIPs, from SSM) to its local edge. The tenant nftables gate applies the same redirect to tenant traffic. Client-IP preservation stays on. Dev verifies it from the agent, a tenant process and a sidecar.
-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.
+### 12.5 The platform box, the cut-over and the provider boundary
-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.
+- **The platform box** (IE, H24) stays in fixed mode with its own new EIP for the relay and MX. S2 §6's steps apply. It is not a target.
+- **The cut-over** costs a few minutes per region (S2 §9 step 3), announced, and measured on dev.
+- **The provider boundary.** The core assumes one object store with conditional writes, N hosts running `carlos`, and DNS. The AWS adapters are:
+ - the termination oracle and event source;
+ - box identity, and the instance id in the owner;
+ - the private address;
+ - the group and load balancer, in tofu only;
+ - the CloudWatch metric;
+ - the hairpin addresses.
+
+ Without the termination oracle, another box can never take a dead box's leases: its instances stay down until an operator restores the box. So off AWS an HA region is refused until a provider adapter exists, which is consistent with H26.
## 13. Retiring the old box (N-HA2)
-This is the sequence for UK, US and AU. IE differs only in step 4.
+This is the sequence for UK, US and AU; IE differs in step 5.
**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.
+1. The HA release runs on the old box and the console.
+2. `CARLOS_REGION_HA=1` is set on the old box. With one box every rule is a no-op beyond the markers and one restore per instance (§5.4).
+3. Readiness, from `carlos system region readiness <region>`, reports:
+ - every instance has a replica and a successful `files_published_at` (§8.4);
+ - no old-format lock (§9.4);
+ - no non-hibernating socket instance (§6.1).
+4. The group is built, healthy behind zone B's address, and rehearsed there, including the hairpin check.
**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.
+1. **Join.** Register the old box in the target groups as an ordinary member.
+2. **Drain.** `carlos system box role <old> drain`. The box stops waking, forwards everything to serving peers whatever their headroom (A20), and sleeps its awake instances one at a time:
+ - a graceful stop with a marker, a 5-second pause, then the next;
+ - a request for a host mid-stop waits for the stop, then goes to the host's preferred box, which restores it: a few seconds down per app;
+ - always-on workers move to their HRW box.
+
+ When nothing is awake, the box publishes `drained: true`, and its adopter takes its duties (§7.4).
+3. **Cut over.** Disassociate the region's EIP from the old box and add zone A's mapping with it (S2 §9 step 3). A few minutes down, announced.
+4. **Stop** (A19, astra-1.13). Deregister the old box, wait 30 seconds, and stop the EC2 instance. It holds no leases, its duties are adopted, and it is not a group member.
+5. **IE instead:** set role `platform`, deregister it, keep it running, and swap it to its new EIP, moving the relay and MX in the same window (S2 §6 and §9).
+6. **Accept** after seven days, then terminate the stopped box (not in IE).
+
+**Rollback inside the window:**
+1. Start the old box.
+2. Wait until it is healthy.
+3. Remove zone A's mapping, and wait until the EIP shows as unassociated.
+4. Associate the EIP with the old box.
+5. Set its role to `serve`. If the group is at fault, set the group boxes to `drain`.
-**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.
+Its local copies are older than the markers in S3, so each wake there restores. A few minutes down. Before step 3, rollback is just the role change. After acceptance, recovery is forward only. Dev rehearses this exact sequence.
-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 there is one extra box, stopped after step 4. Each region adds a load balancer (about $20 a month before traffic) and EIPs for its extra zones.
-**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. Moves and seed imports in HA regions (placeholder)
-## 14. S2 §8's single-box rows, restated (the old plan 2d)
+In this release the offline-move door refuses any move whose source or destination region is HA, and the seed-import door refuses an HA region. Both refusals come up front, with a message naming the region (astra-1.12). Rev 1's relaxed predicates are withdrawn.
-| Row | Status | Claim-free answer |
+Whether N-box moves and imports join this plan series is Paul's question (§22 Q1). If they do, they need their own source selection, files and timers, landing and promotion order, and rollback contract (astra-1.12).
+
+## 15. S2 §8's single-box rows, restated
+
+| Row | Status | 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;
+| Move door and `selectMoveBoxes` (`internal/console/apiinstancemove.go:687-713`, `boxselect.go:78-140`, `internal/host/movesphase1.go:502-518`) | Dropped | Phase 1 is deleted by R4a. Offline moves: §14. |
+| Seed import (`internal/console/seedfloor.go:25-29`, `:88-89`) | Refused | §14. |
+| `CheckOneBoxRegion` (`internal/hostfence/onebox.go:12-35`) | Dropped | Its callers are claim-only, deleted by R6. |
+| Warm cache (`activator.go:2302-2311`, `backend_exec.go:819-820`) | Built | §5. |
+| Hosts unique to one box (`internal/console/apiinstances.go:523-527`) | Rewrite | Show the box whose snapshot reports the host awake, or none. |
+| EIP list (`internal/console/view.go:178-237`, `server.go:1301-1376`) | Rewrite | The region ingress list (`CONSOLE_REGION_INGRESS`, from tofu) plus `PLATFORM_EDGE_IPS`. Copy review. |
+| Forwarding dial (`homemap.go:159-174`) | Keep 2a | The address source moves out of the claim code (`internal/host/edgesfile.go:983-988`). A box publishes only addresses IMDS reports (`:733-757`). |
+| `consoleBoxLabel` (`cmd/console/main.go:1719-1729`) | Holds | The console runs on the platform box only. |
+| Scoped restart, domain attach, economics, fleet listing, retention (`internal/console/apirestartscope.go:133-150`, `internal/console/domainattach.go:472-500`, `internal/console/economicspass.go:308-318`, `internal/status/fleet.go:158`, `internal/host/retention.go:36-37`) | Hold | Every box of a region, the platform box included (A13), holds every tenant route of it. Cross-region limits predate this spec. |
+| Platform routes reaching group boxes | Requirement | §6.1 excludes them from serving boxes. The platform box publishes them (`edgesfile.go:478-519`) and group boxes backhaul them. Tests cover it. |
+| Flagship tofu and scripts | Rewrite | The group, load balancer and platform box. Group boxes use §12.3. |
+
+## 16. What happens to existing dormant code
+
+### 16.1 Kept
+
+- `internal/lbhealth`; `internal/edge/lbhealth.go`; `privateDial` and `dialAddress`; `internal/edgesfile/private.go`;
+- `awsaddr.go` and `boxaddress.go`; `headroom.go`; `internal/boxid`; `boxrecord.go`; `boxreference.go` and `GroupBoxReference`;
+- `internal/boxchoice`;
+- `internal/termfence`, with `Box` cut to `{Ref, Cloud}`;
- `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.
+- `internal/hostenv`, minus the claim keys;
+- `installchannel.go`, minus its guard;
+- the termination rule and queue;
+- plan 2a's approved no-capacity copy.
-### 15.2 Rewritten
+### 16.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.
+- The `SetHosting` caller becomes the latch (§10).
+- The address source moves out of `edgesclaims.go`.
+- The role door (§4.4).
+- `nocapacity.go` and `regioncapacity.go`, and where the metric starts (§11).
+- `boxselect.go` keeps `liveEdges` and `verifiedRoster`.
-### 15.3 Handed to claims-cleanup R3 for deletion
+### 16.3 Handed to 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.
+- `internal/hostrelocate`, and `internal/host/relocat*.go`;
+- `internal/hostactors/awsmembership`, `internal/console/awsmembership.go`, `internal/console/enrollpass.go`, and `hostactors`' `autoenroll.go`, `membershipread.go` and `enrollment_confirmation.go` (or with R6);
+- `internal/host/joining.go`, `joinmode.go`, `joinroot.go`; `carlos system join`; `carlos-system-join.{service,path}`. `system apply` removes the installed units;
+- `internal/console/hostclaimexecutor.go` and the region-HA branches of `hostclaimops.go`;
+- `internal/host/edgesclaims.go`, after the address split;
+- `hostops/chosen.go`, plan 2a's `hostops/executor.go` additions, and `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
+### 16.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`.
+- R3 keeps `termfence`, `boxrecord.go`, `install-channel`, `CARLOS_REGION_HA`, `privateDial` and `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.
+- Changes to root verbs and units need a census card and an approval (AGENTS.md).
+
+## 17. Interactions
+
+- **Moves and seed imports:** refused in HA regions (§14).
+- **Nearest region and #199** (`origin/design-nearest-region-199`, rev 2): §5.3 closes the local-copy half with the lifetime in the marker. §11 refuses reused names with S3 leftovers in HA regions, including `files/0/` and the lock.
+- **Static sites; the edge asset cache; rootfs apps (#366):** unchanged, except that a box materializes images on its first wake there.
+- **`db pull`/`db query --at` and the cross-region db forward:** they read the replica, so any box of the region serves them.
+- **Litestream #284** (`origin/litestream-oom-284`): restores get more frequent, so land slice A before small group instances.
+- **The change index (#336):** one new scope, `control/box-roles`. Duty files are deliberately outside it. Edges deletions ride `control/edges`.
- **Housekeeper and certificates:** unchanged (S2 §6).
-## 17. Request budget
+## 18. Request budget (astra-1.16)
+
+S3 prices: LIST and PUT $0.005 per 1,000; GET $0.0004 per 1,000; DELETE free.
**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).
+- **S3:** unchanged, at about 3,300 to 3,500 today.
+- **Edges files:** the timed pass is unchanged, and due changes no longer touch edges files.
+- **Duty files:** at most 60 PUTs.
+- **SQS:** 180 long-poll receives (about $0.05 a month).
+- **EC2:** describes only on suspicion, at most one per instance per 10 seconds.
+- **The lease TTL** is unchanged (N-HA3).
+
+**Reader amplification** comes only from writes that bump `control/edges`: the timed passes, box start and stop, role changes, and the deletion of a dead box's file. Each makes every box in the deployment re-read at its next 30-second poll: one LIST per 1,000 keys, plus one GET per edges file (`homemap.go:456-491`). Readers coalesce, so the bound is 120 × (1 + B) requests per box per hour, for B boxes in the deployment. The timed passes already reach it today, so this spec adds none.
**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 |
+| Event | S3 requests |
+|---|---|
+| Wake, HA box, local copy kept | 1 GET + 1 PUT (acquire) |
+| Wake, HA box, restore | 1 GET + 1 PUT, plus the restore: up to 5 LISTs, plus 1 LIST per extra 1,000 L0 files, plus GETs, plus 1 manifest GET and its objects |
+| Wake, non-HA box (today) | 1 PUT; an expired lock costs 2 PUTs + 1 GET (`lease.go:193-195`, `s3/leaser.go:114`) |
+| Sleep, HA box | as today, + files publish if changed, + 1 PUT (marker) in place of a free DELETE, + at most one duty-file PUT a minute |
+| Probe of a held lease | 1 GET |
+| Takeover | 1 GET + 1 PUT + 1 describe |
+| Termination or drain transfer | 2 GETs + 1 PUT + 2 DELETEs |
+| Awake hour, snapshot plan | at most 4 publishes, none when unchanged |
+| Awake hour, continuous plan | up to 2 PUTs per write interval per file being written (§22 Q2) |
-**Example.** 10,000 warm wakes a day add 10,000 LISTs and 20,000 GETs: about $0.06 a day.
+**Example.** 10,000 sleep-and-wake cycles a day on HA boxes add 10,000 GETs and 10,000 PUTs: about $0.054 a day.
-## 18. Switches and rollout
+## 19. 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.
+- **Box:** `CARLOS_REGION_HA` gates the HA acquire, markers, restores, forwarding, duties, files sync, the latch, the hairpin redirect, headroom, the identity record and the private dial.
+- **Unconditional:** the owner format.
+- **Console:** `CARLOS_REGION_METRICS` (exists), `CONSOLE_REGION_INGRESS` (new), the role door, the readiness door and the HA refusals.
- **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.
+0. R3 (§16.3) lands.
+1. **The HA release.** Roll it dev boxes, dev console, check, flagship boxes, flagship console.
+2. **Dev's IE region** already has two boxes (`platform-infrastructure/dev/region-ie-b.tf`). Turn `CARLOS_REGION_HA` on for both together, before anything else, as the first N=2 test.
+3. **Each flagship old box** turns it on in turn; readiness then has to go green.
+4. **Per region:** infrastructure (§12) and retirement (§13). Dev, then UK, US, AU, and IE last.
-On dev, before any flagship region, run and time a terminate drill and a hang drill (§20).
+The terminate, hang and S3-loss drills run on dev first (§21).
-## 19. Observability and alerts
+## 20. 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.
+- The load balancer's `UnHealthyHostCount > 0` for 10 minutes; `HealthyHostCount < box_count` for 25 minutes.
+- `EligibleBoxes < box_count` for 25 minutes, missing as breaching; `GroupInServiceInstances < desired`.
+- The termination queue's `ApproximateAgeOfOldestMessage` over 10 minutes.
+- **Takeovers and transfers:** a metric and a log line each, with the host, the dead box, the instance id and the latency.
+- **Suspect holders:** any host refused for over 10 minutes for a lease whose owner is not confirmed dead. The runbook says terminate that box in its group (§9.5).
+- **Local copies set aside,** by reason: no marker, another box, a different lifetime, an identity change, a digest change, or `clean: false`.
+- **Files:** the oldest unpublished change over 5 minutes, or over two intervals on the snapshot plan; failed backfills.
+- **Clock:** a chrony offset over 1 s on any box.
+- **Over capacity:** a wake with no eligible box, at most once per region per hour.
+- The memory alarm, on the group dimension.
-## 20. Tests
+## 21. Tests
-### 20.1 The simulation
+### 21.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.
+- 2 to 5 boxes, each with local DB and files state and a release record;
+- one S3 with conditional writes, per-host replica chains, `lock.json` with markers, and duty files;
+- EC2's state machine, the group's reaction and its grace period;
+- a lossy termination queue.
-**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.
+**Actions:** requests, sleeps, kills, hangs, a hang just after the first healthy service, one box losing S3, agent crashes, concurrent cold wakes, drains, membership changes, recreated hostnames, and clock offsets up to the bound.
**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.
+- **I1, single writer.** Every replica or manifest write came from the lease holder of the moment, and no two writes for one host share a transaction id.
+- **I2, no stale serving.** A box serves a host only from S3's state, or from a copy whose marker proved it unchanged since this box released it.
+- **I3, no wrong acquisition.** No box acquires another box's lease without a release marker or a confirmed termination.
+- **I4, bounded forwarding.** At most two forward attempts, no onward forward, no cycle.
+- **I5, liveness.** After a termination, every host can be served within the modelled bound.
+- **I6, duties.** Every tick and due wake is delivered at least once while some serving box exists, and no transferred duty is lost when the adopter dies part way.
+- **I7, one key.** No host's instance key is minted twice.
+- **I8, lifetimes.** No copy is reused across lifetimes.
+
+**Mutation checks.** Each of these must make the sweep fail:
+- keep a copy without the marker;
+- let expiry authorize another box;
+- accept `shutting-down`;
+- delete the source duty file before the adopter's PUT succeeds;
+- mint before the restore;
+- let a forwarded request be forwarded again.
One 3,000-seed sweep per revision, run serially at nice 19.
-### 20.2 Other tests
+### 21.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.
+ - the marker: its JSON is accepted by litestream's decoder and read as expired by `LockState` and `leaseFree`;
+ - each keep and restore reason of §5.3;
+ - the acquire table of §9.4;
+ - termination verification; the duty-file merge; HRW; the latch; the hairpin rule's generation.
+- **Against MinIO:** the HA acquire, the marker PUT, and the takeover.
- **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.
+ - terminate a box, measuring committed-write loss per replication class;
+ - hang one (`SIGSTOP` the agent; separately, black-hole its health port), including once just after its first healthy service;
+ - black-hole S3 for one box, then the runbook terminate;
+ - concurrent cold wakes;
+ - drain, stop and the rollback restart;
+ - the EIP cut-over;
+ - the hairpin from the agent, a tenant and a sidecar.
+
+## 22. Open questions for Paul
+
+1. **Do N-box offline moves and seed imports join this plan series?** They are refused in HA regions until they have their own contract (§14). *Recommendation:* a separate spec after the first HA region is accepted, since neither is needed to meet the failover goal.
+2. **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:* 10 seconds for app files on the top plan (about $2.60 a month at worst, a 10-second loss window), and 1 second for the H6 trio, which are small and rarely written.