carlos / platform Public

G6 design rev 2: answer Astra round 1

Fence tracks capture boundary and WAL stalls, kills writers, joins
replication before the unclean marker. Capacity pins the launch template
and drains on rollback. Pool path stores the HA choice on the app row.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev d4c4d8419aaf5437f6630550ab1c8dfc994ae142 parent b5f825d
4 files changed, +318 −117
  • docs/superpowers/reviews/CODEX-FINDINGS-G6-R1.md +75 −0
  • docs/superpowers/specs/2026-11-11-g6-pool-path-design.md +59 −27
  • docs/superpowers/specs/2026-11-11-g6-us-capacity-design.md +44 −24
  • docs/superpowers/specs/2026-11-11-g6-write-fence-design.md +140 −66

CI failed — run details

Intent

Human

<task-notification> <task-id>b44h6ltqh</task-id> <tool-use-id>toolu_01F2cUyekWzyPnNRwxNeRJYS</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/64640e60-2586-4892-aa4d-d341a15a1881/tasks/b44h6ltqh.output</output-file> <status>completed</status> <summary>Background command "Run Astra review round 1" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 34.9 g CO₂e (3,705,846 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-R1.md b/docs/superpowers/reviews/CODEX-FINDINGS-G6-R1.md
new file mode 100644
index 000000000..1f9253f4a
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-G6-R1.md
@@ -0,0 +1,75 @@
+Reviewed `design-g6` at `b5f825d9be1ba057d32120f5bb67283418c73492`, round 1. Litestream references below are to `github.com/benbjohnson/litestream@v0.5.14`.
+
+**G6-1.1 — P1 — Write fence §3.1: pending excludes uncaptured SQLite writes**
+
+- **Claim:** `DB.Pos().TXID > synced` identifies locally committed transactions absent from storage.
+- **Evidence:** Litestream `db.go:559-587` reads the latest local LTX position, not SQLite’s committed WAL position. WAL capture happens separately (`db.go:1165-1207`). If capture stalls or fails while the app keeps writing, local and replica TXIDs can remain equal. `Replica.Sync` can then record successful no-op syncs (`replica.go:157-179`). The fence never trips.
+- **Fix:** Include WAL-capture health and unrepresented commits in the fence’s invariant. Treat inability to establish capture progress conservatively. Add a witness where SQLite continues committing while local capture is blocked or failing.
+
+**G6-1.2 — P1 — Write fence §§3.1, 4–5: sync completion does not establish the 35-second loss bound**
+
+- **Claim:** Every unsynced commit occurred after `LastSuccessfulSyncAt()`.
+- **Evidence:** Litestream captures `dpos` before uploading (`replica.go:157-175`) and timestamps success afterward (`replica.go:179`, `db.go:618-621`). A sync can capture its target at t=0, finish at t=29, and reset the fence while writes acknowledged since t=1 remain pending. If the next upload hangs, fencing around t=60–65 can lose writes almost a minute old.
+- **Fix:** Base the loss bound on the capture boundary covered by confirmed replication, or on the oldest outstanding write, rather than upload completion. Test a successful slow upload followed by a hung upload while writes continue. Update the bound and exit assertions consistently.
+
+**G6-1.3 — P1 — Write fence §§2–3, 5: a hung upload can prevent release and owed-marker creation**
+
+- **Claim:** Latching the fence reuses existing paths to release unclean and retry the marker.
+- **Evidence:** `internal/lease/release.go:233-252` calls `db.SyncAndWait` before closing the store. Litestream’s `Replica.Sync` takes an unconditional mutex (`replica.go:134-136`); a final sync waits behind an already-hung background upload despite its context deadline. The client timeout is 24 hours (`s3/replica_client.go:365-366`). Renewal cancellation does not cancel the independently owned Litestream background work. No marker is attempted until finalization completes (`internal/lease/release.go:279-285`).
+- **Fix:** Specify how fence shutdown cancels and joins outstanding replication before attempting the unclean marker, preserving the rule that uploads cannot follow release. Extend the hung-sync test through finalization, marker failure, owed retry and recovery—not just the error latch.
+
+**G6-1.4 — P1 — Write fence §3.2: incarnation identity does not prevent duplicate stops**
+
+- **Claim:** The watcher may call `beginStopLocked` whenever the entry is still the same incarnation.
+- **Evidence:** A request can start stopping that same entry first (`internal/activator/haleaseloss.go:103-110`). `beginStopLocked` has no state guard: it replaces `e.stopped` and launches another stop goroutine (`internal/activator/activator.go:3453-3467`). Both callers can therefore stop and finalize the same entry concurrently. Also, normal renewal shutdown does not close `Lost()` (`internal/lease/health.go:301-311`), so a watcher waiting only on loss survives ordinary hibernation.
+- **Fix:** Under `a.mu`, verify entry and replica identity and start a stop only from `actAwake`; latch loss without restarting an existing stop. Cancel the watcher on lifecycle completion. Add request-versus-watcher, intentional-stop-versus-loss, and clean-hibernation tests.
+
+**G6-1.5 — P1 — Write fence §§3.2, 5: starting a graceful stop does not stop acknowledgements at the fence**
+
+- **Claim:** The watcher stops every writer promptly enough that all lost acknowledgements precede the fence line.
+- **Evidence:** `beginStopLocked` deliberately leaves in-flight requests to the graceful drain (`internal/activator/activator.go:3422-3428`). Shutdown can wait for respawn, sidecar starts and generation operations before stopping the main process (`:4803-4875`), then run a five-second next-due probe and a twenty-second process stop (`:4936-4960`). Existing requests and background writers can continue committing after the fence line.
+- **Fix:** Define and enforce the cessation boundary for admitted requests and background writers. Either make fence shutdown satisfy the stated acknowledgement bound or explicitly include the stopping interval in the guarantee. Test an in-flight write and a worker that continues writing during graceful shutdown.
+
+**G6-1.6 — P1 — Capacity §6: the resize does not select the new launch template**
+
+- **Claim:** Changing `instance_type` and `box_count` together launches a medium, and subsequent replacements use that template.
+- **Evidence:** The template takes `var.instance_type` (`infra/modules/region-host/group.tf:196`), but the ASG separately pins `var.group_launch_template_version` (`:252-255`). Step 1 leaves that pin unchanged, so scale-out launches another small. After correcting the pin, step 0’s old provider observation no longer matches; preflight checks the exact template (`internal/grouproll/engine.go:854-856,927-932`).
+- **Fix:** Create the medium template, explicitly pin its numeric version before or with scale-out, and obtain the matching provider observation before `replace`. Record the actual apply counts and verify each launched member’s type.
+
+**G6-1.7 — P1 — Capacity §6 rollback: reducing `box_count` bypasses the drain**
+
+- **Claim:** Before step 3, rollback reverts `box_count` to two and then removes the medium member.
+- **Evidence:** The module sets desired capacity directly from `box_count` (`infra/modules/region-host/group.tf:241-243`), so that apply initiates scale-in before the selected member is drained. Afterward, `remove` refuses because it must leave two members (`internal/grouproll/depart.go:120-122`).
+- **Fix:** Keep the group at three while restoring the intended template pin and matching observation. Drain and remove the selected medium through the verb, then set `box_count = 2` with no instance change.
+
+**G6-1.8 — P1 — Pool path §3.1: app creation bypasses the human-only enable boundary**
+
+- **Claim:** Adding the manifest write to `handleAPICreateApp` is equivalent to the enable door’s create.
+- **Evidence:** App creation admits account-scoped Publish service credentials (`internal/console/routedecls.go:489`, `apicli.go:416-429`). Manifest enable explicitly excludes every service role (`routedecls.go:612`) and calls `apiPerson` (`apiinstances.go:3486-3488`). The reason is that enabling instances grants standing creation policy (`apicli.go:337-343`). An account allowlist does not preserve this principal boundary.
+- **Fix:** Require a human principal for the HA option before any write, retaining ordinary service app creation. Test that an allowlisted account’s Publish credential cannot create the HA manifest.
+
+**G6-1.9 — P1 — Pool path §3.1 step 4: retry cannot distinguish partial creation from an existing app**
+
+- **Claim:** “App exists, no manifest” identifies an interrupted HA create that a retry may complete.
+- **Evidence:** Ordinary app creation does not create an instances manifest; enable creates it later (`internal/console/apiinstances.go:3573-3576`). Existing app names currently return `claimTaken` (`internal/console/server.go:5337-5343`). The proposed exception therefore also accepts an unrelated existing app, potentially with a different region, placement or existing routes. This exposes the existing-app HA conversion that §3.3 excludes.
+- **Fix:** Persist HA creation intent tied to the app lifetime and exact requested region/pool. Resume only that operation; refuse unrelated existing apps. Serialize completion against enable and instance creation, and test concurrent plain enable, changed-region retries and lost success responses.
+
+**G6-1.10 — P2 — Capacity §§3, 5: the advertised promote margin does not fit two large instances**
+
+- **Claim:** A medium carries two large instances plus the canaries and leaves room for promote overlap.
+- **Evidence:** The card allocates 2,840 MiB usable and 300 MiB to canaries. Two large instances plus one overlapping large generation require `300 + 3 × 1024 = 3372 MiB`. Large is 1,024 MiB (`internal/cgroup/sizes.go:20`), and generation memory limits are applied separately (`internal/instancectl/gen.go:75-80`).
+- **Fix:** Include the maximum permitted simultaneous overlap in the sizing formula and admission envelope. Qualify the two-large recommendation or choose capacity that supports its promised overlap. Exercise that complete workload in the capacity witness.
+
+**G6-1.11 — P2 — Pool path §§4–5: the draft promises exceed the supported behavior**
+
+- **Claim:** The app runs on two servers; releases and maintenance do not interrupt it; losing storage stops it within about thirty seconds.
+- **Evidence:** RHA §7.2 assigns execution to one lease holder. Planned handover still returns 503 for several request classes and closes some connections (`docs/region-ha-runbook.md:149-158`). The proposed fence intentionally does not trip for an idle instance with no pending writes (write-fence §3.1).
+- **Fix:** Before copy review, state that another member can take over, preserve the documented handover exceptions, and qualify the storage-outage timing with the pending-write condition. This is factual scope, not wording style.
+
+**G6-1.12 — P2 — Pool path §3.1: the API route is incorrect**
+
+- **Claim:** `handleAPICreateApp` serves `POST /api/cli/apps/{account}`.
+- **Evidence:** Its registered route is `POST /api/cli/apps/{account}/new` (`internal/console/routedecls.go:489`).
+- **Fix:** Correct the endpoint and target the registered route in the forged-request and retry tests.
+
+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 590cf3949..7a2a5ada5 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 1, 2026-11-11)
+# G6 slice 3: the pool path, born-HA apps for allowed accounts (design, rev 2, 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 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
in pool `ha` on flagship US, with no migration; creates in the pool sit behind
a per-account allowlist; the copy states what HA does and does not promise,
@@ -70,25 +72,47 @@ too; the dev list names the dev canary account.
### 3.1 API and CLI
-`POST /api/cli/apps/{account}` (`handleAPICreateApp`, `internal/console/apicli.go:411`)
-takes an optional `"ha": true`. With it:
-1. `region` is required and must be explicit (not `@auto`), in
- `CONSOLE_HA_REGIONS` and scoped with a non-empty `ha_pools`; otherwise 400
- with the §5 "not in this region" sentence.
-2. `haPoolAllowed` must hold for the region's pool; otherwise 403 as above.
-3. The console creates the app with that region (the existing region path,
- `newAppRegionReq`), then writes the app's instances manifest create-only,
- with the default domain and `Pool` = the region's first `ha_pools` entry
- (`ha` on the flagship). This is the enable door's own create, with the pool
- supplied by the console instead of by an operator.
-4. If the manifest write fails after the app exists, the answer is 500 naming
- the half-done state, and a retry of the same request (app exists, no
- manifest) completes it. A retry when a manifest already exists with a
- different pool is 409.
-
-CLI: `carlos apps create <app> --region us --ha`. Nothing else in the CLI
-changes; `carlos deploy` into the app then creates the default instance, which
-the manifest makes born HA (`haCreate(us, ha)`), as the canaries showed in G5.
+The choice is stored on the app and acted on by the door that already owns
+manifests, so no new door writes standing creation policy.
+
+1. **App create.** `POST /api/cli/apps/{account}/new` (`handleAPICreateApp`,
+ `internal/console/apicli.go:411`, route `routedecls.go:489`) takes an
+ optional `"ha": true`. That route admits Publish service credentials; the
+ HA option does not. With `ha`:
+ - the caller must be a person (`apiPerson`, as the enable door,
+ `apiinstances.go:3486-3488`); a service credential gets 403 before any
+ write, and its plain creates are unchanged;
+ - `region` is required and explicit (not `@auto`), in
+ `CONSOLE_HA_REGIONS` and scoped with a non-empty `ha_pools`; otherwise
+ 400 (§5);
+ - `haPoolAllowed` must hold for the region's pool; otherwise 403 (§2);
+ - the app row is inserted as today, in the same statement with a new
+ column `ha_pool` (on the `apps` table, `store.go:828-840`, beside
+ `region`) set to the region's first `ha_pools` entry (`ha` on the
+ flagship). One insert, so there is no half-created state to resume.
+ Existing app names still answer `claimTaken` (`server.go:5337-5343`);
+ there is no path that adds `ha_pool` to an existing app (that is the
+ deferred migration).
+2. **Enable.** The existing person-only door `PUT .../{app}/instances-manifest`
+ (`handleAPIInstanceEnable`, `routedecls.go:612`) is the only writer of the
+ manifest's pool, and only on the manifest's first create (the
+ `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
+ (`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.
+
+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
+person) writes the manifest with the pool, and the default instance is born
+HA (`haCreate(us, ha)`), as the canaries showed in G5. A Publish credential
+can deploy to the app afterwards, as to any app.
### 3.2 The web UI
@@ -100,7 +124,9 @@ pick has an HA pool:
- it is enabled only while the picked region supports HA (the picker's region
list gains an `ha` boolean; `regionpicker.go`); the server checks everything
again (§3.1);
-- the form posts `ha=1`, and the handler runs the §3.1 steps.
+- the form posts `ha=1`; `handleNewApp` runs §3.1 step 1 (the web session is
+ a person) and then the enable door's create in the same request, so the app
+ is ready to deploy.
App settings (`templates/app_settings.html`) shows one read-only line for an
app whose manifest pool is a scoped HA pool: the §5 status sentence. The
@@ -123,9 +149,11 @@ The facts the §5 strings must state, each from a measured or specified bound:
| Situation | What the app sees | Source |
|---|---|---|
-| Planned work: a release, a member replaced or removed | requests wait a few seconds, then succeed; no errors | G5 exit bar (holds ≤ 10 s, 0 non-2xx), RHA §25 |
+| Normal running | the app runs on one server at a time; another server in the group can take it over | RHA §6.2, §7.1 |
+| 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 | the app stops answering (503) within about 30 seconds; writes from the last ~35 seconds before that can be lost | fence spec §4 |
+| 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 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 |
@@ -136,9 +164,9 @@ These go to Paul's copy review before the build writes any of them. Drafts
follow the house voice: plain, no em dashes.
1. Checkbox label: `High availability`
-2. Checkbox explainer: `Runs this app on two servers in this region. Releases and server maintenance don't interrupt it. If a server fails without warning, the app can be unavailable for up to 15 minutes while another server takes over.`
+2. Checkbox explainer: `Keeps a second server in this region ready to take over this app. During releases and server maintenance most requests wait a few seconds instead of failing. If a server fails without warning, the app can be unavailable for up to 15 minutes while another server takes over.`
3. Docs link text: `What high availability covers`
-4. Refusal, account not allowed (403 `ha-pool-not-allowed`): `high availability isn't available for this account yet.`
+4. Refusal, account not allowed, or a service credential asked for it (403 `ha-pool-not-allowed`): `high availability isn't available for this account yet.`
5. Refusal, region without HA (400): `high availability isn't available in %s.` (region label, e.g. `N. Virginia (US)`)
6. Refusal, `--ha` without an explicit region (400): `choose a region to turn on high availability.`
7. Settings status line: `High availability is on in %s.`
@@ -158,8 +186,12 @@ tests):
- `haPoolAllowed` at each create door for a scoped pool: listed account
passes, unlisted gets 403 `ha-pool-not-allowed` before any bucket write,
non-member gets 404; legacy creates and unscoped regions unchanged;
-- app create with `ha`: explicit region required; unscoped region refused; the
- manifest is written with the pool; the retry rules of §3.1 step 4;
+- 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
+ 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
region, server rejects a forged `ha=1`;
- approved-copy tests for the §5 strings once Paul approves them (the pattern of
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 cbc729cb8..27f81e0d6 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 1, 2026-11-11)
+# G6 slice 1: capacity of the flagship US HA group (design, rev 2, 2026-11-11)
+
+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).
Design only. Paul approves before any apply. Parent: region HA spec
`2026-10-26-region-ha-without-claims-design.md` (cited **RHA §n**), the roll
@@ -48,9 +50,15 @@ 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` |
+| 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).
+
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,
and the card records it.
@@ -79,47 +87,59 @@ 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 any first app up to two `large` instances, so
- the choice of first app (still open) does not reopen this card.
-- It leaves room for a promote that briefly runs an old and a new process of
- the same app (counted at twice its size).
+- 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.
- 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
third member if the extra redundancy is wanted then).
If Paul prefers to spend nothing yet: 2 × t4g.small fits a single `standard`
-first app (§3), and the card applies only once a second app, a `large` app,
-or a promote overlap is in prospect. The cost of being wrong is OOM on the
+first app without a promote overlap (§3: `300 + 512 = 812`; with an overlap
+`1324 > 1190`), and the card applies once a second app, a `large` app, or a
+promote while one member serves is in prospect. The cost of being wrong is OOM on the
survivor during a replace, which is the moment G6 exists to make safe, so this
is not the recommendation.
## 6. How it is applied (a resize = add a member)
-The module sets `min = max = desired = box_count` (`infra/modules/region-host/group.tf:241-243`),
-and `instance_type` feeds the launch template (`variables.tf:16`). Running
-members never change type in place. Per Paul's G5 ruling, a resize adds a
-member first, so that at least two members serve at every step:
+The module sets `min = max = desired = box_count` (`infra/modules/region-host/group.tf:241-243`).
+`instance_type` feeds the launch template resource (`group.tf:196`), but the
+group launches the version pinned by `group_launch_template_version`
+(`group.tf:252-255`, `variables.tf:408`), so a type change only takes effect
+with a re-pin. The verb's preflight refuses unless the operator's provider
+observation matches the pinned template exactly (`internal/grouproll/engine.go:852-856`,
+`:927-932`), and an observation needs a member on that template (G5 lesson:
+"after a re-pin the verb can't run until a member exists on the new LT").
+Running members never change type in place. Per Paul's G5 ruling, a resize
+adds a member first, so at least two members serve at every step:
| Step | Who | What | Expected counts / result |
|---|---|---|---|
-| 0 | release agent | Pin-back if the group's LT and the observation differ (as every G5 roll needed). | 0/1/0, standing approval |
-| 1 | carloku-infrastructure PR | `instance_type = "t4g.medium"` and `box_count = 3` for `host_us_group`, targeted. A new LT version with the type change, ASG sizes 3. **First-of-kind apply: needs a GO** (Fable process rules, Paul 2026-11-11). | 0/2/0; the group launches one medium member; the two smalls are untouched |
-| 2 | operator | Wait for the medium member to pass the lifecycle hook and publish its edges file; record its `mem_total_mib`. | 3 members serving |
-| 3 | verb | `carlos system group replace --member <small A>`: drained; its replacement boots on the new LT (medium). | holds ≤ 10 s, 0 non-2xx (G5 bar) |
-| 4 | verb | `carlos system group remove --member <small B>`: drained scale-in (verb §3, `remove`). | holds ≤ 10 s, 0 non-2xx; 2 medium members |
-| 5 | carloku-infrastructure PR | `box_count = 2` to match the live group. | 0/1/0, no instance change, standing approval |
+| 0 | release agent | If the group's pinned version and the observation differ (every G5 roll needed this), pin back first. | 0/1/0, standing approval |
+| 1 | carloku-infrastructure PR, targeted | `instance_type = "t4g.medium"` (the template resource gains version N+1), `group_launch_template_version = N+1`, `box_count = 3`. **First-of-kind apply: needs a GO.** | 0/2/0 (template, group); the group launches one member from N+1; the two small members are untouched |
+| 2 | operator | Check the new member's type is t4g.medium (`describe-auto-scaling-groups`), wait for the lifecycle hook and its edges file, record `mem_total_mib`. Then `carlos system group probe start` against it and write the observation for template N+1. | 3 members serving; observation matches N+1 |
+| 3 | verb | `carlos system group replace --member <small A>`: drained; the replacement launches from N+1. Check its type. | holds ≤ 10 s, 0 non-2xx (G5 bar) |
+| 4 | verb | `carlos system group remove --member <small B>`: drained scale-in; the runbook's rule (at least two members remain) holds. | holds ≤ 10 s, 0 non-2xx; 2 medium members |
+| 5 | carloku-infrastructure PR | `box_count = 2` to match the live group (runbook: set `box_count` after `remove`). | 0/1/0, no instance change, standing approval |
The capacity alarm fires once per launch until the damping pin (4fe12300,
v0.34.46) reaches the flagship; that is expected noise, not a finding.
Steps 1 to 5 run in one flagship window under the #421 lock, with the G5
probe running against the canaries. The exit test: **one medium member
-carries the canaries plus a `large` heldwitness load through step 4's remove,
-the capacity alarm is quiet after the last launch, and the probe shows 0
-non-2xx.**
-
-Rollback before step 3: revert step 1 (box_count 2 and t4g.small), then
-`remove` the medium member. After step 3, roll forward.
+carries the canaries plus a `large` heldwitness load and one promote of it
+through step 4's remove, the capacity alarm is quiet after the last launch,
+and the probe shows 0 non-2xx.**
+
+**Rollback** never lowers `box_count` while a member is undrained, because
+an apply that lowers desired starts an undrained scale-in.
+- Before step 3: pin back to version N (0/1/0; the template resource keeps
+ N+1, unused), write the observation for N, then `remove` the medium member
+ through the verb (three members, so two remain), then `box_count = 2`.
+- After step 3: roll forward.
## 7. Provider boundary
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 9d4d3ac89..234a1bb96 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 1, 2026-11-11)
+# G6 slice 2: the minimal write fence (F-C) (design, rev 2, 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:
@@ -6,6 +6,8 @@ Design only. Paul approves before any build. Parent: region HA spec
`~/.cache/region-ha-next/G2-RERUN-RESULTS.md` (drill 4 rerun, v0.34.14).
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).
+
**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
@@ -50,7 +52,9 @@ minutes, set by where the cut falls against the renewal. RHA §5.3 promises
`Replica.Sync` (`replica.go:179`). `Replica.Pos()` and `DB.Pos()` give the
replicated and local transaction ids. A failed sync resets the replica
position to zero (`replica.go:139-145`). Nothing in the platform reads any of
- them.
+ them. The fence does not use `LastSuccessfulSyncAt`: a sync reads its target
+ position before uploading and stamps success after, so the timestamp can lag
+ the oldest outstanding write (G6-1.2).
- **The stream case is known at wake.** For an HA lease with sync interval 0
the activator sets the 1 s WAL monitor (`internal/activator/activator.go:3335`).
@@ -59,17 +63,39 @@ minutes, set by where the cut falls against the renewal. RHA §5.3 promises
### 3.1 The fence (internal/lease)
When `Held.Replicate` starts a replicator for an **HA lease in the stream
-class** (sync interval 0), it also starts a fence check that runs every 5 s
-until the replicator closes:
-
-1. `synced` = the highest non-zero `Replica.Pos().TXID` seen so far (kept by the
- check, because a failed sync zeroes the position);
-2. `pending` = `DB.Pos().TXID > synced`, that is, transactions committed
- locally and not yet in the store;
-3. `since` = the later of `LastSuccessfulSyncAt()` and the replicator's start;
-4. **if `pending` and `now − since > 30 s`:** under `rn.mu`, `loseLocked(ErrReplicaStale)`
- and log once:
- `lease: <path>: replica sync has not succeeded for <age> with transactions <synced+1>-<db> unsynced; standing down (write fence)`.
+class** (sync interval 0), it also starts a fence check that runs **every
+second** until the replicator closes. Each run reads only memory and one
+`stat`:
+
+1. `L` = `DB.Pos().TXID`, the newest transaction litestream has captured
+ locally into an LTX file (litestream `db.go:559-587`);
+2. `R` = the highest non-zero `Replica.Pos().TXID` seen so far (kept by the
+ 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`).
`ErrReplicaStale` is a new sentinel, distinct from `ErrLost`, so the journal
and metrics tell a fence from a lost lease. No caller tests
@@ -77,31 +103,60 @@ 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.
-Why these inputs:
-- An idle instance during an outage has nothing pending, so it is never fenced.
- Its lease renewal handles the outage as today.
-- A sync that hangs (the F-A case: litestream's background upload can block
- for up to its 24 h HTTP timeout) never records a success, so it trips the
- fence like an error does.
-- Every commit not yet in the store happened after `since`, so at the moment
- the fence trips, all acknowledged-but-unsynced writes are from the last
- `30 s + 5 s` (one check interval). That is the bound.
-
-The 30 s and 5 s are constants with a test seam, not settings. A self-hoster
-with a slow store gets the same bound; §6 says what that costs.
-
-### 3.2 Stopping every writer promptly (internal/activator)
-
-Requests are fenced at once through `servingError`. Background writers
-(always-on workers, ticks, sidecars) are caught today only by the sweep, every
-`min(Idle/4, 30 s)` (`activator.go:5401-5406`). That could stretch the window.
-So for each awake HA entry the activator waits on `rep.Lost()`
-(`lease.go:545`) and, when it fires, takes `a.mu` and calls
-`beginStopLocked(e, StopLeaseLost)` if the entry is still the same incarnation.
-That reuses the existing stop, which stops the process, its co-spawned
-sidecar, workers and holds, and requires the host slice to be empty before
-release (`harelease.go`, `haHostEmpty`). The same goroutine helps lease loss
-too: today a lease lost while no request arrives also waits for the sweep.
+The 30 s, the 1 s check and the 1 s capture are constants with a test seam,
+not settings.
+
+### 3.2 The fenced stop: kill, then release (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:
+
+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.
### 3.3 Only the stream class in an HA pool (cli.go, registry)
@@ -128,10 +183,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 of the last 35 s before the fence; then 503 with `Retry-After: 10` |
+| 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, 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 stops, and the unsynced tail (≤ 35 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 (≤ 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 |
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
@@ -143,25 +198,42 @@ without a terminate, which is the drill 4 rerun's behaviour after its fault
ended. If the box never gets the store back, RHA §9.5 is unchanged: the
suspect-holder page at L+10 and the runbook terminate.
-RHA §5.5 gains one sentence: "On an HA box, a stream instance whose replica
-sync has not succeeded for 30 seconds while it has unsynced writes stops
-serving and releases unclean, so a storage outage loses at most about the last
-35 seconds of acknowledged writes."
+RHA §5.5 gains one sentence: "On an HA box, a stream instance whose
+replication has fallen more than 30 seconds behind its local writes stops at
+once and releases unclean, so a storage outage loses at most about the last
+35 seconds of acknowledged writes. An instance with nothing unsynced is not
+affected."
## 5. Tests and the exit test
-Unit (no AWS, run under `-run`):
-- `internal/lease`: with `SetReplicaClientForTest` (`export_test.go:34`) and a
- failing upload, a pending transaction trips `ErrReplicaStale` after 30 s on
- the seam clock; no pending transaction never trips; a sync that blocks trips;
- a success at 29 s resets the age; the latch is permanent; the fence is off for
- batched, daily and non-HA leases.
+Unit (no AWS, run under `-run`), with the seam clock:
+- `internal/lease`, with `SetReplicaClientForTest` (`export_test.go:34`):
+ - a failing upload with writes trips `ErrReplicaStale` 30 s after the first
+ 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;
+ - 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
+ fake store recovers; the next acquire restores and sets the local copy aside.
- `internal/activator`, modelled on `haleaseloss_test.go` (`lossTestRep`,
- `assertLostResponse`, `TestHALostLeaseAnswersImmediately`): a replicator whose
- `Err()` becomes `ErrReplicaStale` answers 503, `Retry-After: 10`,
- `X-Carlos-Holder: none` with no proxy; the release marker is `clean: false`;
- a worker-only entry is stopped by the `Lost()` watcher without a request or
- sweep.
+ `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;
+ - 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.
- `cli`: the rail refuses `batched` and `daily` on an HA route and allows them
on a non-HA route.
@@ -170,22 +242,24 @@ the fault harness with its 35-minute expiry timer), on the dev IE group, pool
`hapair`, fixture `g2-stream` written to about once a second through both
entries:
1. Cut outbound 443 on the holder for 10 minutes.
-2. **Pass:** the fence line appears between t0+30 s and t0+40 s; from it every
- request gets 503 with `Retry-After: 10` and no hangs; acknowledged and lost
- writes (probe acks against `/ranges`) are all from the 35 s before the fence
- line, and number at most 40 (was 131); 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; F-A, F-B and F-D
- rows of the rerun still pass.
+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
+ 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)
and a 2-minute cut with the fixture idle (no fence).
## 6. Provider boundary and cost
-Core only. The fence reads litestream's in-memory positions and timestamps;
-it makes no request and adds no S3 cost. It behaves the same on MinIO or any
-S3-compatible store. A store slower than 30 s per sync under load would fence
-spuriously; the drill's 20 s control and the dev metrics show the margin on
+Core only. The fence reads litestream's in-memory positions and one `stat`
+of the WAL per second per awake HA stream instance; it makes no request and
+adds no S3 cost. It behaves the same on MinIO or any
+S3-compatible store. A store whose uploads fall more than 30 s behind under load
+would fence spuriously; the drill's 20 s control and the dev metrics show the margin on
AWS, and a self-hoster's store needs the same margin.
## 7. Out of scope