carlos / platform Public

G6 design rev 3: answer Astra round 2 (unreviewed)

Fence: obligation queue, replication stopped at the latch, slice kill;
capacity counts per-app overlap; pool path binds region and pool.
Review budget spent; fence families go to Paul under stopping rule 2.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 6c21254cabc8b6d9108ccc4f4e0411a2939fc833 parent d4c4d84
4 files changed, +255 −120
  • docs/superpowers/reviews/CODEX-FINDINGS-G6-R2.md +83 −0
  • docs/superpowers/specs/2026-11-11-g6-pool-path-design.md +35 −9
  • docs/superpowers/specs/2026-11-11-g6-us-capacity-design.md +27 −17
  • docs/superpowers/specs/2026-11-11-g6-write-fence-design.md +110 −94

CI cancelled — superseded by a newer push — run details

Intent

Human

<task-notification> <task-id>bh9tjv42d</task-id> <tool-use-id>toolu_01NSvZBF2SpnwNqgyPczxYWg</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/64640e60-2586-4892-aa4d-d341a15a1881/tasks/bh9tjv42d.output</output-file> <status>completed</status> <summary>Background command "Confirm push; run Astra round 2" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 44.8 g CO₂e (5,090,621 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-g6, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-G6-R2.md b/docs/superpowers/reviews/CODEX-FINDINGS-G6-R2.md
new file mode 100644
index 000000000..f2759eff9
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-G6-R2.md
@@ -0,0 +1,83 @@
+| Prior finding | Disposition | Round 2 result |
+|---|---|---|
+| G6-1.1 | partly | WAL observation added, but continuous changes reset its timer; G6-2.1. |
+| G6-1.2 | partly | Upload-completion timestamp removed, but capture can still erase outstanding-write age; G6-2.1. |
+| G6-1.3 | partly | Cancellation covers a newly selected fenced finalization, not an ordinary finalization already blocked; G6-2.3. |
+| G6-1.4 | fixed | Awake-state guard prevents duplicate stops; proposed `Done()` ends the watcher. |
+| G6-1.5 | partly | Immediate kill proposed, but it targets the wrong cgroup and does not establish the claimed acknowledgement boundary; G6-2.2–2.4. |
+| G6-1.6 | fixed | Numeric template pin and matching observation precede replacement. |
+| G6-1.7 | fixed | Rollback drains and removes before reducing `box_count`. |
+| G6-1.8 | fixed | HA app creation requires a person; manifest creation remains person-only. |
+| G6-1.9 | fixed | App-row intent distinguishes HA creation from unrelated existing apps. |
+| G6-1.10 | partly | Overlap included, but its concurrency and supported-size assumptions remain incorrect; G6-2.6–2.7. |
+| G6-1.11 | partly | Running and maintenance promises corrected; the new idle-outage row remains inaccurate; G6-2.9. |
+| G6-1.12 | fixed | App-create endpoint corrected to `/new`. |
+
+Reviewed `design-g6` at `d4c4d8419aaf5437f6630550ab1c8dfc994ae142`, round 2, FINAL. Litestream citations refer to v0.5.14.
+
+**G6-2.1 — P1 — Write fence §3.1: the revised timers still lose outstanding-write age**
+
+- **Invariant:** An unreplicated commit’s age must survive further writes and local capture.
+- **Claim:** `tW` and the sampled capture history bound lost commits to 33 seconds.
+- **Evidence:** The spec defines `tW` as when the WAL **last** changed without `L` advancing (`write-fence-design.md:76-90`). With capture blocked and writes every second, `tW` resets every second while `L = R`; neither condition trips. Separately, a commit at t=0 captured at t=29 stops satisfying the capture-stall condition and starts the capture timer at t=29. A hung upload then permits fencing around t=60. A one-second capture interval is not a capture-duration bound: Litestream runs synchronous capture and backs off after errors (`db.go:2696-2715`).
+- **Fix:** Preserve the earliest unresolved WAL observation through subsequent changes and its eventual capture, clearing it only when replication proves coverage. Add continuous-write capture-stall and delayed-capture-then-hung-upload witnesses.
+
+**G6-2.2 — P1 — Write fence §3.2 step 3: `KillHost` does not kill HA instance processes**
+
+- **Invariant:** Fence termination must cover the actual containment of every writer.
+- **Claim:** Calling the existing `KillHost` immediately kills the HA host’s writers.
+- **Evidence:** HA requires nested layout (`internal/activator/hawake.go:149-171`). Nested generations start through systemd (`genbackend.go:299-307`) in `instancectl.SliceName(host)` (`internal/instancectl/gen.go:65-72`). `KillHost` instead opens the agent’s `carlos-exec@<host>` cgroup and returns success when it is absent (`internal/activator/genbackend.go:666-707`). That can leave the HA instance running; `haHostEmpty` subsequently examines the different systemd slice (`harelease.go:50-72`).
+- **Fix:** Specify a root-authorized kill of the actual host slice, covering all generations and roles and preventing racing starts. Keep the whole-slice emptiness proof. Test nested HA processes with the exec cgroup absent.
+
+**G6-2.3 — P1 — Write fence §3.2 steps 2–4: an existing stop cannot switch while blocked**
+
+- **Invariant:** Fence cancellation must interrupt shutdown already in progress without duplicating finalization.
+- **Claim:** Reading `e.fenced` before each wait makes an ordinary stop switch promptly to killing and fenced release.
+- **Evidence:** A fence can arrive after the check: the stop may already be receiving from `startDone` (`internal/activator/activator.go:4852-4853`), joining operations (`opset.go:152-159`), or draining the process (`activator.go:4953-4960`). It cannot reread the flag until that operation returns. Worse, ordinary `finalize` holds `finMu` while `SyncAndWait` waits behind the hung upload (`internal/lease/release.go:225-235`; Litestream `replica.go:134-136`). Selecting a new finalizer later does not cancel that existing wait.
+- **Fix:** Define a fence signal that interrupts active waits and cancels replication independently of acquiring `finMu`. Preserve one finalization owner. Test fencing after each wait has begun, including after ordinary finalization enters `SyncAndWait`.
+
+**G6-2.4 — P1 — Write fence §§3.2, 4–5: asynchronous killing cannot guarantee zero acknowledgements after the log line**
+
+- **Invariant:** The acknowledgement boundary must match the enforcement boundary.
+- **Claim:** Every request in flight at the fence fails without acknowledgement; no 2xx follows the fence line.
+- **Evidence:** The proposed sequence logs at the lease latch, then schedules the watcher and stop before killing (`write-fence-design.md:90-92,117-140`). Already admitted requests execute `proxy.ServeHTTP` outside the admission lock (`internal/activator/activator.go:6565-6577`). They can commit and return success between the latch and kill. Killing also cannot retract a response already buffered downstream.
+- **Fix:** Distinguish admission refusal, writer cessation and client receipt. Include the bounded cessation interval in the loss guarantee and revise the exit assertions accordingly, or specify an additional response-enforcement mechanism. Exercise the latch-to-kill interleaving explicitly.
+
+**G6-2.5 — P1 — Pool path §§3.1–3.2: HA placement can change before enable**
+
+- **Invariant:** A born-HA app’s chosen region and pool must remain coherent before and after manifest creation.
+- **Claim:** Immutable `ha_pool` leaves nothing new to race, and the HA app cannot change region.
+- **Evidence:** CLI app creation leaves the manifest absent. `appPolicy` treats absence as unpooled and unrestricted (`internal/console/regioncandidates.go:289-294,313-321`); `setAppRegion` therefore permits changing the row’s region (`appregionset.go:314-358`). The proposed refusal applies only when the manifest identifies an HA pool (`pool-path-design.md:131-135`). Enable subsequently copies the old pool into the new region. Instance creation also accepts an explicit region instead of the app default (`apiinstances.go:1871-1888`), while the proposed manifest sets no regional restriction.
+- **Fix:** Enforce the born-HA region/pool binding from the app row at both region-change doors, including before enable. Validate it again during enable and constrain instance placement to that binding. Test sequential and concurrent create → region-change → enable.
+
+**G6-2.6 — P1 — Capacity §3: one release agent does not bound tenant overlap concurrency**
+
+- **Invariant:** Survivor capacity must include every permitted simultaneous generation.
+- **Claim:** Counting one extra copy of the largest app bounds promote overlap.
+- **Evidence:** Rollout scheduling is per account/app, not globally serialized (`internal/rollout/policy.go:14-15`). Each app’s configurable `SwapConcurrency` controls concurrent dispatch (`policy.go:42-43`; `scheduler.go:61-75`), and the API permits values above one (`internal/console/apiswap.go:67-76`). Three standard instances with concurrency three need `300 + 6 × 512 = 3372 MiB`, exceeding the medium’s 2840 MiB despite fitting the advertised three-standard envelope.
+- **Fix:** Calculate overlap from permitted per-app concurrency across the pool, or enforce the stated single-overlap restriction. Include that maximum workload in the capacity witness.
+
+**G6-2.7 — P2 — Capacity §§2–5: the size table and mixed-size arithmetic are incomplete**
+
+- **Invariant:** Every advertised workload must satisfy the stated memory formula.
+- **Claim:** A medium supports a first app of any size and one large plus one standard with overlap.
+- **Evidence:** `xlarge` is a supported 2048 MiB size (`internal/cgroup/sizes.go:21`); one with overlap requires `300 + 2 × 2048 = 4396 MiB`. The mixed-size table entry requires `300 + 1024 + 512 + 1024 = 2860 MiB`, exceeding 2840.
+- **Fix:** Include `xlarge`, qualify “any size,” and remove or correct the mixed-size recommendation. State the enforceable admission envelope before first-app selection.
+
+**G6-2.8 — P2 — Pool path §3.1 step 2: unconditional pool equality breaks existing operator-managed apps**
+
+- **Invariant:** Legacy manifests retain their existing update behavior.
+- **Claim:** Any manifest whose pool differs from `apps.ha_pool` returns 409.
+- **Evidence:** Existing operator-managed manifests have nonempty pools, including the canaries identified in pool-path §1, but their pre-existing app rows have no HA creation intent. The proposed comparison therefore rejects their enable updates. Today those updates preserve Pool and Regions (`internal/console/apiinstances.go:3592-3597`).
+- **Fix:** Apply the intent-equality rule only to apps carrying born-HA intent. Preserve legacy operator-managed manifests and test updates to both HA and non-HA named pools.
+
+**G6-2.9 — P2 — Pool path §4: the idle-storage-outage promise still overstates unavailability**
+
+- **Invariant:** Published outage behavior must match the serving and recovery paths.
+- **Claim:** An idle app becomes unavailable until its server is replaced when storage connectivity fails.
+- **Evidence:** Without pending writes the proposed fence does not trip. Serving checks lease health, not storage reachability (`internal/console/../activator/haleaseloss.go:95-103`), so requests can still succeed before renewal failure. Write-fence §4 also explicitly permits recovery after storage returns through the owed marker and reacquire path, without replacing the server.
+- **Fix:** Describe refusal after lease failure and recovery when storage returns; reserve operator termination for a holder that cannot recover.
+
+The outstanding-write-age, writer-cessation and release-cancellation families remain unresolved across both rounds. The final-round budget is exhausted; no round 3.
+
+Verdict: NOT READY
\ No newline at end of file
diff --git a/docs/superpowers/specs/2026-11-11-g6-pool-path-design.md b/docs/superpowers/specs/2026-11-11-g6-pool-path-design.md
index 7a2a5ada5..3b24c03eb 100644
--- a/docs/superpowers/specs/2026-11-11-g6-pool-path-design.md
+++ b/docs/superpowers/specs/2026-11-11-g6-pool-path-design.md
@@ -1,4 +1,4 @@
-# G6 slice 3: the pool path, born-HA apps for allowed accounts (design, rev 2, 2026-11-11)
+# G6 slice 3: the pool path, born-HA apps for allowed accounts (design, rev 3, 2026-11-11)
Design only. Paul approves before any build, and every user-facing string in
§5 goes through Paul's copy review before it is written into code or docs.
@@ -6,6 +6,8 @@ Parent: region HA spec `2026-10-26-region-ha-without-claims-design.md`
(**RHA §n**), especially §23 (B10, born HA only in a named HA pool). Line
citations are to `origin/main` at 01d6ca78.
+Rev 3 (not reviewed; the two-round budget is spent) answers Astra round 2 (`CODEX-FINDINGS-G6-R2.md`): the row's region and pool are bound at both region doors and into the manifest's `Regions` (G6-2.5); the pool-equality rule applies only to born-HA apps (G6-2.8); the idle storage row is corrected (G6-2.9).
+
Rev 2 answers Astra round 1 (`docs/superpowers/reviews/CODEX-FINDINGS-G6-R1.md`): the HA choice is stored on the app row and the manifest is written only by the existing person-only enable door (G6-1.8, G6-1.9); the promise table matches the handover exceptions and the fence's condition (G6-1.11); the route is `/new` (G6-1.12).
**Paul's rulings (2026-11-11, via 8a3d302):** the first app is a fresh create
@@ -99,14 +101,32 @@ manifests, so no new door writes standing creation policy.
`os.ErrNotExist` branch, `apiinstances.go:3573-3576`): it sets
`Pool = ha_pool` from the live app row (by `AppIncarnation`, so a trashed
and recreated name never inherits it) after re-checking `haPoolAllowed`.
- An existing manifest whose pool differs from the row's `ha_pool` answers
- 409 and changes nothing. On update, Pool stays untouched as today
+ It also sets `Regions = [row region]`, so an instance create naming any
+ other region is refused by the manifest's existing regional restriction
+ (instance create accepts an explicit region, `apiinstances.go:1871-1888`).
+ Before writing, it re-checks that the row's region is still in
+ `CONSOLE_HA_REGIONS` with `ha_pool` in its `ha_pools`; otherwise 409.
+ For an app whose row carries `ha_pool`, an existing manifest whose pool
+ differs answers 409 and changes nothing. Apps without `ha_pool` (every
+ legacy and operator-managed app, the canaries included) keep today's
+ behaviour exactly (G6-2.8). On update, Pool stays untouched as today
(`apiinstances.go:3592`).
3. **Instance creates** stamp `Pool` from the manifest and are born HA by
- B10, with `haPoolAllowed` checked again at the create door (§2). Enable and
- create already serialise on the manifest's ETag (create-only and
- conditional writes); the row's `ha_pool` never changes after insert, so
- there is nothing new to race.
+ B10, with `haPoolAllowed` checked again at the create door (§2).
+4. **Region binding** (G6-2.5). An app whose row carries `ha_pool` cannot
+ change region, before or after enable: both region doors (`PUT .../region`,
+ `appregionset.go:187` and `setAppRegion`, `:314-358`, and the settings
+ form) refuse with 409 (§5 string 8) when the row has `ha_pool`, reading the
+ row, not the manifest (a missing manifest reads as unpooled,
+ `regioncandidates.go:289-294`). The check sits in `SetAppRegion`'s
+ conditional update, so a create, region change and enable racing each other
+ all see the same row.
+5. **Swap concurrency.** The swap door (`apiswap.go:67-76`) refuses a
+ concurrency above 1 for an app whose row has `ha_pool` (capacity card §3).
+
+Enable and instance create already serialise on the manifest's ETag
+(create-only and conditional writes), and the row's `ha_pool` never changes
+after insert.
CLI: `carlos apps create <app> --region us --ha` (a signed-in person). Then
`carlos instances enable` (or a first `carlos deploy`, which enables as the
@@ -153,7 +173,7 @@ The facts the §5 strings must state, each from a measured or specified bound:
| Planned work: a release, a member replaced or removed | most requests wait a few seconds, then succeed. Some still get 503 with `Retry-After: 10` for those seconds: bodies over 64 KiB or of unknown length, requests another box already forwarded (most cross-region ones), edge-local and tunnel calls, and requests after the member starts closing connections. Keep-alive connections close, event streams reconnect, WebSockets older than 60 s close, always-on workers pause for a few minutes | `docs/region-ha-runbook.md:147-158`, RHA §25 |
| A server dies without warning | requests get 503 with `Retry-After` until another server takes over; **up to about 15 minutes** until storage fencing exists | RHA §9.8 |
| A server loses its storage connection while the app is writing | the app stops (503) about 30 seconds after its writes stop reaching storage; writes from the last ~35 seconds can be lost | fence spec §4 |
-| A server loses its storage connection while the app is idle | nothing is lost; the app is unavailable until the server is replaced (RHA §9.5, page at about 10 minutes) | RHA §9.5, fence spec §4 |
+| A server loses its storage connection while the app is idle | nothing is lost. The app keeps answering until its lease renewal fails (within about 5 minutes), then answers 503 with `Retry-After`. When storage returns it recovers by itself; if storage never returns to that server, an operator replaces it (paged at about 10 minutes) | RHA §6.7, §9.5, fence spec §4 |
| A server dies | writes from about the last second can be lost | RHA §5.3 |
| The whole region fails | not covered | out of scope |
| Existing apps | cannot be moved into HA yet | §3.3 |
@@ -172,6 +192,7 @@ follow the house voice: plain, no em dashes.
7. Settings status line: `High availability is on in %s.`
8. Region change refused for an HA app (409): `this app has high availability on, so its region can't be changed.`
9. CLI flag help for `--ha`: `turn on high availability (needs --region; only for accounts that have it)`
+11. Swap concurrency refused for an HA app (400): `apps with high availability on swap one instance at a time.`
10. Docs page `docs/site/high-availability.md`, short: the §4 table in prose, written with the writing pipeline after the strings above are approved, and reviewed in the same copy pass.
The checkbox string (2) leaves out the storage and write-loss rows on purpose;
@@ -189,7 +210,12 @@ tests):
- app create with `ha`: person only (an allowlisted account's Publish
credential gets 403 and writes nothing); explicit region required;
unscoped region refused; `ha_pool` stored in the same insert;
-- enable: first create takes `Pool` from the live row; a recreated name does
+- enable: first create takes `Pool` and `Regions` from the live row; a
+ legacy app with a named pool updates exactly as today;
+- region change refused for a born-HA app before and after enable, including
+ create, region change and enable racing;
+- swap concurrency above 1 refused for a born-HA app;
+- enable: a recreated name does
not inherit it; an existing manifest with another pool is 409; a removed
account is refused at enable and at instance create;
- web form: checkbox hidden for unlisted accounts, disabled for a non-HA
diff --git a/docs/superpowers/specs/2026-11-11-g6-us-capacity-design.md b/docs/superpowers/specs/2026-11-11-g6-us-capacity-design.md
index 27f81e0d6..d2dec8ac1 100644
--- a/docs/superpowers/specs/2026-11-11-g6-us-capacity-design.md
+++ b/docs/superpowers/specs/2026-11-11-g6-us-capacity-design.md
@@ -1,4 +1,6 @@
-# G6 slice 1: capacity of the flagship US HA group (design, rev 2, 2026-11-11)
+# G6 slice 1: capacity of the flagship US HA group (design, rev 3, 2026-11-11)
+
+Rev 3 (not reviewed; the two-round budget is spent) answers Astra round 2 (`CODEX-FINDINGS-G6-R2.md`): overlap is counted per app at its swap concurrency, and pool apps are held to concurrency 1 (G6-2.6); `xlarge` and the mixed-size arithmetic are corrected (G6-2.7).
Rev 2 answers Astra round 1 (`docs/superpowers/reviews/CODEX-FINDINGS-G6-R1.md`): the launch template version pin and observation in §6 (G6-1.6), a drained rollback (G6-1.7), and the promote overlap counted in §3 and §5 (G6-1.10).
@@ -30,7 +32,8 @@ size must a member be, what does it cost, and how is a change applied?
| adi-knitting (fixed, not in the pool) | `t4g.small`, 59 awake, memory available falling 75% to 70% (daily average) over a week | edges file, CloudWatch |
Per-instance memory ceilings are the cgroup sizes (`internal/cgroup/sizes.go:18-20`):
-`small` 256 MiB, `standard` 512 MiB (the default, `cgroup.go:105`), `large` 1 GiB.
+`small` 256 MiB, `standard` 512 MiB (the default, `cgroup.go:105`), `large` 1 GiB,
+`xlarge` 2 GiB (`sizes.go:21`).
`memory.max` equals `MemorySwapMax`, so an instance never exceeds its size.
## 3. The rule
@@ -49,15 +52,22 @@ one box.
| Member type | `mem_total` (est.) | Usable | Fits besides the canaries |
|---|---|---|---|
-| t4g.small (now) | 1858 MiB | ~1190 MiB | one `standard` app (512) with ~380 MiB spare; **not** one `large` app |
-| t4g.medium | ~3800 MiB | ~2840 MiB | four `standard`, or two `large`; with one promote overlap (one extra copy of the largest app): three `standard`, or one `large` plus one `standard` |
-| t4g.large | ~7750 MiB | ~6200 MiB | eleven `standard`, or five `large` |
-
-A promote can run an old and a new generation of the same app at once, each
-under its own memory limit (`internal/instancectl/gen.go:75-80`). So the sum
-counts **one extra copy of the largest app** that may be promoted while the
-group is down to one member (a release and a replace never run together under
-one release agent, so one overlap at a time is the bound).
+| t4g.small (now) | 1858 MiB | ~1190 MiB | one `standard` app without an overlap (812); **not** with one (1324) |
+| t4g.medium | ~3800 MiB | ~2840 MiB | with each app's overlap: one `large` (2348), or two `standard` (2348); **not** one `xlarge` (4396) |
+| t4g.large | ~7750 MiB | ~6200 MiB | with each app's overlap: one `xlarge` (4396), or two `large` (4396), or five `standard` (5420) |
+
+**Promote overlap.** A promote can run an old and a new generation of the
+same app at once, each under its own memory limit
+(`internal/instancectl/gen.go:75-80`). Rollouts are scheduled per app, not
+globally (`internal/rollout/policy.go:14-15`), and an app's `SwapConcurrency`
+(`policy.go:42-43`, `scheduler.go:61-75`, settable above 1 through
+`internal/console/apiswap.go:67-76`) lets several of its instances swap at
+once. So the sum counts, for every pool app, **its instances' sizes times
+(1 + its swap concurrency)**, assuming every app promotes at once while one
+member serves. To keep that bounded, the swap door refuses a concurrency above
+1 for an app whose row carries a born-HA pool (pool path §3.1), with the
+operator text going through copy review. The figures in the table use
+concurrency 1: each app counts twice.
The medium and large `mem_total` values are estimated at the small's ratio
(91% of nominal); the first medium member's edges file gives the real number,
@@ -87,13 +97,13 @@ unplanned death during a replace, or in any one-member moment.
**2 × t4g.medium (+$24.53 a month), applied before the first app is created.**
-- It carries the canaries plus a first app of any size (one `large`
- instance, or up to three `standard`) **including** one promote overlap
- (`300 + 2 × 1024 = 2348 ≤ 2840`), so the choice of first app (still open)
- does not reopen this card. Two `large` apps plus an overlap (3372 MiB) do
- not fit; that is the trigger below.
+- It carries the canaries plus a first app of one `large` instance, or two
+ `standard`, each with its promote overlap (`300 + 2 × 1024 = 2348 ≤ 2840`).
+ That covers every first app up to `large`. An `xlarge` first app needs
+ t4g.large (`300 + 2 × 2048 = 4396`); the card then applies with that type
+ instead, at $101.31 a month.
- The trigger for the next step is written down now: when the §3 sum for the
- pool passes the medium's 2840 MiB, the next resize is due (t4g.large, or a
+ pool passes the medium's 2840 MiB (with every app counted twice), the next resize is due (t4g.large, or a
third member if the extra redundancy is wanted then).
If Paul prefers to spend nothing yet: 2 × t4g.small fits a single `standard`
diff --git a/docs/superpowers/specs/2026-11-11-g6-write-fence-design.md b/docs/superpowers/specs/2026-11-11-g6-write-fence-design.md
index 234a1bb96..eaa9fb274 100644
--- a/docs/superpowers/specs/2026-11-11-g6-write-fence-design.md
+++ b/docs/superpowers/specs/2026-11-11-g6-write-fence-design.md
@@ -1,4 +1,4 @@
-# G6 slice 2: the minimal write fence (F-C) (design, rev 2, 2026-11-11)
+# G6 slice 2: the minimal write fence (F-C) (design, rev 3, 2026-11-11)
Design only. Paul approves before any build. Parent: region HA spec
`2026-10-26-region-ha-without-claims-design.md` (**RHA §n**). Evidence:
@@ -8,6 +8,8 @@ Line citations are to `origin/main` at 01d6ca78.
Rev 2 answers Astra round 1 (`docs/superpowers/reviews/CODEX-FINDINGS-G6-R1.md`): the trip condition now tracks the oldest outstanding capture and WAL changes litestream has not captured (G6-1.1, G6-1.2); a fenced holder kills its writers at once instead of draining (G6-1.5); the stop is started only from awake and the watcher ends with the replicator (G6-1.4); a fenced release cancels and joins replication before its marker (G6-1.3).
+**Rev 3 (not reviewed; the two-round budget is spent)** answers Astra round 2 (`CODEX-FINDINGS-G6-R2.md`): an obligation queue keeps the oldest unresolved write's age through later writes and captures (G6-2.1); the fence kills the host's systemd slice through the root path, not the exec cgroup (G6-2.2); replication is stopped at the latch, outside `finMu`, and the kill runs from the watcher, so no blocked stop has to notice anything (G6-2.3); the bound now includes the latch-to-kill interval and makes no zero-acknowledgement claim (G6-2.4). The same three families drew findings in both rounds (stopping rule 2); §8 puts the choice to Paul.
+
**Paul's ruling (2026-11-11, via 8a3d302, approving Fable 5.2 §3 decision 2):**
a holder whose replica sync fails for about 30 s stops serving (503 with
`Retry-After`) and releases unclean. This spec builds exactly that and nothing
@@ -73,29 +75,39 @@ second** until the replicator closes. Each run reads only memory and one
check, because a failed sync zeroes the position, `replica.go:139-145`);
3. `W` = the `-wal` file's size and modification time.
-It keeps a short history of `(t, L)` samples and the time `tW` at which `W`
-last changed without `L` advancing at the same sample. Then:
-
-- **Outstanding capture.** `t_first` = the time of the earliest sample with
- `L > R`. Samples older than that had `L ≤ R`, so every transaction captured
- before `t_first − 1 s` is in the store. A transaction not in the store was
- captured after the previous sample, and committed at most one capture
- interval (1 s) earlier. So every unreplicated commit is younger than
- `now − t_first + 2 s`. This uses the capture boundary, not the time a sync
- finished, which can lag its target (G6-1.2).
-- **Capture stall.** If `W` changed and `L` has not advanced since `tW`,
- SQLite has committed frames litestream has not captured (G6-1.1). The check
- cannot know which commits those are, so it treats `tW` as the oldest
- outstanding commit. A `stat` that fails counts as a change (conservative).
-- **Trip:** if `now − t_first > 30 s`, or `now − tW > 30 s`: under `rn.mu`,
- `loseLocked(ErrReplicaStale)` and log once:
- `lease: <path>: replication has not reached transaction <R+1> for <age> (local <L>, wal <changed|captured>); standing down (write fence)`.
-
-An idle instance has `L = R` and an unchanged WAL, so it is never fenced; its
-lease renewal handles an outage as today. A hung upload (the F-A case) never
-raises `R`, so it trips like an error. Litestream's own checkpoints advance
-`L` in the same capture, so they do not count as a stall; an application
-checkpoint cannot pass litestream's read lock (`db.go`, `rtx`).
+**The obligation queue** (G6-2.1). Each run that finds `W` changed since the
+previous run appends an obligation `{t: now, txid: unknown}`. Each run that
+finds `L` advanced assigns `txid = L` to every obligation still unknown
+(frames that changed the WAL before this capture are in transactions up to
+`L`). Obligations are removed from the front only when `R ≥ txid`. A run that
+finds `L > R` with the queue empty (captured before the first sample) appends
+`{t: now, txid: L}`. A failed `stat` appends an obligation as if `W` changed.
+
+The oldest obligation's `t` is therefore never reset by later writes, by a
+late capture, or by a slow upload: it goes only when replication proves its
+transaction is in the store. A commit not in the store changed the WAL no
+later than the run after it, so it is no older than `now − t_oldest + 1 s`.
+
+**Trip:** if the queue is non-empty and `now − t_oldest > 30 s`: under
+`rn.mu`, `loseLocked(ErrReplicaStale)`, then (outside `rn.mu` and outside
+`finMu`) `Replica.Stop(true)` (litestream `replica.go:118-130`), which cancels
+the monitor's context, aborts an in-flight upload and joins the monitor
+goroutine. Log once:
+`lease: <path>: a write has waited <age> to reach storage (local <L>, stored <R>); standing down (write fence)`.
+
+Stopping replication at the latch, in the lease package, is what makes a
+release that is already running unblock (G6-2.3): an ordinary `finalize`
+waiting in `SyncAndWait` behind the hung monitor sync (`release.go:225-235`,
+litestream `replica.go:134-136`) gets `syncMu` once the monitor's sync
+returns, makes its own attempt under its own release budget, fails while the
+store is down, and writes `clean: false` because `finishErr` includes
+`rn.Err()` (`release.go:254`). No second finalizer exists, so there is one
+finalization owner, as today. Uploads after the latch can only come from that
+bounded final attempt, which runs before the marker, never after it.
+
+An idle instance has an empty queue, so it is never fenced; its lease renewal
+handles an outage as today. A hung upload never raises `R`, so it trips like
+an error.
`ErrReplicaStale` is a new sentinel, distinct from `ErrLost`, so the journal
and metrics tell a fence from a lost lease. No caller tests
@@ -103,60 +115,46 @@ and metrics tell a fence from a lost lease. No caller tests
`internal/hostexec/rootbroker.go:795` is a different package's sentinel), so
every existing consumer treats the fence exactly as a lost lease.
-The 30 s, the 1 s check and the 1 s capture are constants with a test seam,
-not settings.
+The 30 s and the 1 s check are constants with a test seam, not settings.
-### 3.2 The fenced stop: kill, then release (internal/activator)
+### 3.2 Stopping the writers (internal/activator)
-Writes acknowledged after the fence would be lost anyway, so a fenced holder
-does not drain. A graceful stop deliberately lets in-flight requests and the
-instance's SIGTERM drain run for up to `actStopTimeout` (20 s), and shutdown
-can wait on respawns, sidecar starts and generation operations first
-(`activator.go:3418-3428`, `:4803-4960`; G6-1.5). The fenced stop instead:
+From the latch, admission refuses every new request at once through
+`servingError` (503, `Retry-After: 10`). Requests already admitted run
+`proxy.ServeHTTP` outside the admission lock (`activator.go:6565-6577`) and
+can still commit and answer until their process dies (G6-2.4). So the fence
+ends writers by killing them, from a goroutine that does not depend on the
+stop's progress:
1. **The watcher.** For each awake HA stream entry the activator starts one
goroutine that selects on `rep.Lost()` (`lease.go:545`) and on the
- replicator's end (a new `Done()` that closes when the replicator is
- finalized or abandoned, so a clean hibernation ends the watcher; G6-1.4).
- On `Lost()` with `errors.Is(rep.Err(), ErrReplicaStale)` it takes `a.mu`
- and calls `fenceStopLocked(e, rep)`.
-2. **`fenceStopLocked(e, rep)`**, under `a.mu`, is the only entry point, used
- by the watcher and by the request path when `servingError` returns
- `ErrReplicaStale`:
- - if `e.rep != rep`, it returns (another incarnation);
- - it sets `e.fenced = true` (idempotent);
- - if `e.state == actAwake`, it calls `beginStopLocked(e, StopFenced)`;
- - if the entry is already stopping (any reason), it starts nothing new
- (`beginStopLocked` has no state guard, `activator.go:3453-3467`); the
- running stop reads `e.fenced` before each of its waits and switches to
- step 3.
-3. **Kill.** A fenced stop cancels held legs and holds as `beginStopLocked`
- already does, then calls the exec backend's `KillHost` (`cgroup.kill` on
- the host's cgroup and wait until empty, `internal/activator/opset.go:172-177`)
- before anything else, with no SIGTERM drain, no next-due probe and no wait
- on respawns or generation operations. In-flight requests see their
- connection fail (the edge answers 502), not an acknowledgement. Kernels
- without `cgroup.kill` (`cgroup.ErrNoKill`) fall back to SIGKILL of every
- pid in the slice, then the existing empty-slice proof (`haHostEmpty`).
-4. **Fenced release.** `finishStop` keeps its rules (no release while a run,
- op, worker or stop is live; the slice must be empty). Then the replicator's
- new `finalizeFenced`:
- - `Replica.Stop(true)` (litestream `replica.go:118-130`) cancels the
- monitor's context, which aborts an in-flight upload, and joins the
- monitor goroutine, so no upload of this lifetime can start or finish
- after this returns (G6-1.3);
- - no final sync: the store is closed with an already-cancelled context, so
- `DB.Close`'s final `syncReplicaWithRetry` (`db.go:767-789`) makes no
- request;
- - the marker is written `clean: false` through the existing path, and a
- failed PUT becomes the existing owed release (RHA §5.2, `owed.go`).
-
- Today's ordinary HA release instead runs `SyncAndWait` first
- (`release.go:233-252`), which can wait behind a hung upload on litestream's
- unconditional `syncMu` (`replica.go:134-136`). The fenced path never calls
- it. The join's own bound is the HTTP client honouring context
- cancellation; the build's test proves a blocked upload releases within
- 5 s of the cancel.
+ replicator's end (a new `Done()`, closed when the replicator is finalized
+ or abandoned, so a clean hibernation ends the watcher). On `Lost()` with
+ `errors.Is(rep.Err(), ErrReplicaStale)`:
+ - under `a.mu`: if `e.rep != rep`, return; set `e.fenced = true`; if
+ `e.state == actAwake`, `beginStopLocked(e, StopFenced)`; if already
+ stopping, start nothing (`beginStopLocked` has no state guard,
+ `activator.go:3453-3467`);
+ - then, without `a.mu`, **kill the host's slice**.
+2. **The kill** (G6-2.2). HA hosts run nested (`hawake.go:149-171`): their
+ generations start through systemd in `instancectl.SliceName(host)`
+ (`genbackend.go:299-307`, `internal/instancectl/gen.go:65-72`), not in the
+ agent's `carlos-exec@<host>` cgroup that `KillHost` targets
+ (`genbackend.go:666-707`). The fence therefore asks instance control
+ (root) to SIGKILL every unit in that slice (`systemctl kill
+ --signal=SIGKILL <slice>`), all generations and roles, and returns when the
+ slice's cgroup is empty, the same proof `haHostEmpty` already reads
+ (`harelease.go:50-72`). The build adds this as one instance-control
+ operation beside the existing slice reads (`instancectl/size.go`).
+3. **No restarts.** While `e.fenced` is set, every start path for the entry
+ (respawn, sidecar start, generation start, swap) refuses, so a start that
+ races the kill cannot bring a writer back. The stop goroutine itself is
+ unchanged: its waits end because the processes are gone and replication is
+ stopped, and it then releases through the normal path (§3.1).
+
+The cessation bound is the latch-to-empty-slice interval, `K`. It is measured,
+not assumed: the unit test asserts `K < 2 s` with a fake instance control, and
+the drill records it.
### 3.3 Only the stream class in an HA pool (cli.go, registry)
@@ -183,10 +181,10 @@ For a stream instance on an HA box:
| Event | Before | After |
|---|---|---|
| Box dies | about 1 s of writes lost (RHA §5.3) | unchanged |
-| Box loses the store, with writes arriving | every write acknowledged until the next renewal fails: 0 to about 5 min | at most the writes committed in the 33 s before the fence (30 s + 2 s capture + 1 s check); requests after it get 503 with `Retry-After: 10`; requests in flight at the fence fail without an acknowledgement |
+| Box loses the store, with writes arriving | every write acknowledged until the next renewal fails: 0 to about 5 min | at most the writes committed from about 31 s before the fence line to the moment the slice is empty (`K`, about 2 s); new requests get 503 with `Retry-After: 10` from the fence line; a request admitted before it may still be acknowledged until its process dies |
| Box loses the store, idle | nothing lost; lease renewal handles it | unchanged |
| Store outage shorter than 30 s | nothing lost | unchanged |
-| Store outage longer than 30 s, with writes, no renewal inside it | nothing lost: the sync catches up when the store returns | **the instance is killed, and the unsynced tail (≤ 33 s) is lost** when the unclean marker lands and the instance restores from the store; the local copy is set aside as `<db>.stale` (RHA §5.3), so an operator can still recover it by hand |
+| Store outage longer than 30 s, with writes, no renewal inside it | nothing lost: the sync catches up when the store returns | **the instance is killed, and the unsynced tail (about 31 s + `K`) is lost** when the unclean marker lands and the instance restores from the store; the local copy is set aside as `<db>.stale` (RHA §5.3), so an operator can still recover it by hand |
The last row is the price Paul's ruling accepts: a bounded loss in place of an
unbounded one. Without the late flush (deferred), a fenced holder cannot hand
@@ -212,28 +210,34 @@ Unit (no AWS, run under `-run`), with the seam clock:
unreplicated capture; no writes never trips;
- **slow-then-hung** (G6-1.2): an upload that succeeds at 29 s for a target
captured at 0 s, then a hung upload while writes continue, trips 30 s after
- the first capture the slow upload did not cover, not 30 s after its finish;
- - **capture stall** (G6-1.1): SQLite keeps committing while litestream's
- capture is blocked (a test seam on the capture), so `L` stays equal to `R`;
- the WAL change trips it at 30 s;
+ the oldest write the slow upload did not cover;
+ - **continuous writes with capture blocked** (G6-2.1): SQLite commits every
+ second while capture is blocked (`L = R`); trips 30 s after the first
+ blocked write, not reset by later writes;
+ - **delayed capture then hung upload** (G6-2.1): a write at 0 s captured at
+ 29 s, then the upload hangs; trips at about 30 s, not 59 s;
- a failed `stat` counts as a change; the latch is permanent; the fence is
off for batched, daily and non-HA leases;
- - **fenced finalize** (G6-1.3): a blocked upload is cancelled and joined
- within 5 s; no upload call starts after `finalizeFenced` returns; the marker
- is `clean: false`; a failing marker PUT is queued as owed and lands when the
+ - **release already blocked** (G6-2.3): an ordinary `finalize` waiting in
+ `SyncAndWait` behind a hung upload completes within its release budget
+ after the latch; the marker is `clean: false`; no upload starts after the
+ marker PUT; a failing marker PUT is queued as owed and lands when the
fake store recovers; the next acquire restores and sets the local copy aside.
- `internal/activator`, modelled on `haleaseloss_test.go` (`lossTestRep`,
`assertLostResponse`, `TestHALostLeaseAnswersImmediately`):
- `ErrReplicaStale` answers 503, `Retry-After: 10`, `X-Carlos-Holder: none`
with no proxy;
- - **request versus watcher** (G6-1.4): both reach `fenceStopLocked` for one
- entry; exactly one stop runs and one release is written;
- - an ordinary stop already running when the fence trips switches to the kill
- and does not start a second stop;
+ - **request versus watcher** (G6-1.4): both see the fence for one entry;
+ exactly one stop runs and one release is written;
+ - an ordinary stop already blocked in each of its waits (start-done, op
+ join, process drain) when the fence trips: the kill still runs, the stop
+ completes, no second stop starts (G6-2.3);
+ - the kill targets `SliceName(host)` with the exec cgroup absent, and a
+ respawn racing it is refused (G6-2.2);
- a clean hibernation ends the watcher (no goroutine left, no stop);
- - **writers after the fence** (G6-1.5): an in-flight write request and a
- worker writing every 100 ms both stop within one second of the fence; the
- in-flight request gets no 2xx.
+ - **latch-to-kill** (G6-2.4): an in-flight write request and a worker
+ writing every 100 ms both stop within `K < 2 s` of the latch; new requests
+ after the latch get 503.
- `cli`: the rail refuses `batched` and `daily` on an HA route and allows them
on a non-HA route.
@@ -243,11 +247,10 @@ the fault harness with its 35-minute expiry timer), on the dev IE group, pool
entries:
1. Cut outbound 443 on the holder for 10 minutes.
2. **Pass:** the fence line appears between t0+30 s and t0+35 s; from it every
- request gets 503 with `Retry-After: 10` or a connection failure, with no
- hangs and no 2xx; acknowledged and lost writes (probe acks against
- `/ranges`) were all committed in the 35 s before the fence line, and number
- at most 36 (was 131); the host's slice is empty within 2 s of the fence
- line; after the fault ends the unclean marker lands and the fixture serves
+ request started after it gets 503 with `Retry-After: 10`, with no hangs;
+ acknowledged and lost writes (probe acks against `/ranges`) were all
+ committed between 31 s before the fence line and the slice-empty line, and
+ number at most 35 (was 131); `K` (fence line to slice empty) is under 2 s; after the fault ends the unclean marker lands and the fixture serves
again within the bound of RHA §9.8; no other box takes the lease before the
marker or a terminate; the F-A, F-B and F-D rows of the rerun still pass.
3. Two controls in the same window: a 20 s cut with writes (no fence, 0 lost)
@@ -267,3 +270,16 @@ AWS, and a self-hoster's store needs the same margin.
Late flush before release (the redesign F-C named), storage fencing (N-HA9),
batched and daily classes in a pool, automatic replacement of a box that lost
the store (RHA §9.5), and the W5 tolerance question.
+
+## 8. For Paul (stopping rule 2)
+
+The outstanding-write age, writer cessation and release cancellation drew
+findings in both Astra rounds. Rev 3 answers round 2 but is unreviewed. Options:
+
+1. **Approve rev 3 with a one-pass spot check of §3.1-§3.2 by Fable** before
+ the build (the held-floor-capability precedent), then the drill decides.
+ Recommended: the mechanism is now small (a queue, a stop call, a slice
+ kill), and drill 4 measures the bound directly.
+2. **Cut the precision:** keep §3 but state the bound only as measured by the
+ drill, not derived, and drop the capture-stall half (a stalled capture is
+ a local-disk fault, not the S3 loss F-C was about).