carlos / platform Public

plan: G6 write fence rev 3, fallback A after Astra round 2

Drops the root fence (freeze, kill, /fence, /unfence, generation
identity). Keeps the lease queue, Fenced() event and replica gate;
the activator stands down through the ordinary lease-lost stop from
replicator start. Bound taken from the stop path: 30 s common case,
110 s worst bounded case after the fence line.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev b5de9f054aeb67a5c4ddc2caff44fdf5c4c2fb66 parent 111faa5
1 file changed, +148 −234
  • docs/superpowers/plans/2026-11-12-g6-write-fence.md +148 −234

CI passed — run details

Intent

Human

<paseo-system version="1" kind="agent-message" source-agent-id="8a3d302a-eac7-407c-b61c-f5ccc66b5544" message-id="ac66a0e0-8f52-4654-bd73-59da03887ccc"> Agent manager 8a3d302: agreed, A. Build it as you describe, update the spec texts. I&apos;m telling Paul now that the open deck&apos;s &quot;about 35 seconds&quot; becomes &quot;about a minute&quot;; don&apos;t touch the open review. If his result still says 35 s, put the corrected string in the supplementary review with the two new ids. </paseo-system>

Human

<task-notification> <task-id>b19kcmcn5</task-id> <tool-use-id>toolu_01Exj2jtFX9Qp6bbuuc5rwzV</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/1be65f1d-61c8-4308-afb1-2c756edd9c6e/tasks/b19kcmcn5.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 1 Astra review" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 19.8 g CO₂e (2,360,528 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on g6-fence, 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/plans/2026-11-12-g6-write-fence.md b/docs/superpowers/plans/2026-11-12-g6-write-fence.md
index 45bd716df..6690a117a 100644
--- a/docs/superpowers/plans/2026-11-12-g6-write-fence.md
+++ b/docs/superpowers/plans/2026-11-12-g6-write-fence.md
@@ -1,98 +1,112 @@
-# G6 Write Fence (F-C) Implementation Plan (rev 2, ruling B)
+# G6 Write Fence (F-C) Implementation Plan (rev 3, fallback A)
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-**Goal:** An HA stream-class holder whose oldest unreplicated write is more than 30 s old stops serving at once (503, `Retry-After: 10`), has its host slice frozen and killed by root in the kernel, stays frozen until a newer acquisition of that host unfences it, and releases unclean.
+**Goal:** An HA stream-class holder whose oldest unreplicated write is more than 30 s old refuses every new request at once (503, `Retry-After: 10`), stops through its ordinary lease-lost stop, and releases unclean.
-**Architecture:** `internal/lease` runs a 1 s fence goroutine per HA stream replicator. It keeps an obligation queue (the oldest WAL change not yet proven stored), and at the 30 s limit fires a write-fence event once, whatever the renewer has already latched: it closes `Fenced()`, latches `ErrReplicaStale` on the renewer if nothing else is latched, and closes a gate on the replica client that cancels and refuses every replica call except the one finalization's. `internal/activator` attaches a watcher as soon as the wake has a replicator; on the event it cancels a wake in progress or begins the lease-loss stop of an awake entry, and asks root to fence the host with the acquisition's lock generation. `internal/instancectl` `POST /fence` writes `cgroup.freeze=1` and then `cgroup.kill` on the host slice's cgroup and waits for it to empty; a reaper keeps killing anything that enters the frozen slice. `POST /unfence`, sent by the agent after every HA acquire with the new generation, serialises with any fence, refuses a stale generation, kills what is left and thaws. Root does no start accounting. `carlos route --replication` refuses `batched` and `daily` on an HA route.
+**Architecture:** `internal/lease` runs a 1 s fence goroutine per HA stream replicator. It keeps an obligation queue (the oldest WAL change not yet proven stored). At the 30 s limit it fires a write-fence event once, whatever the renewer has already latched: it closes `Fenced()`, latches `ErrReplicaStale` on the renewer if nothing is latched yet, and closes a gate on the replica client that cancels and refuses every replica call except the one finalization's. `internal/activator` attaches a watcher as soon as the wake has a replicator. On the event it sets `e.writeFenced` (admission answers 503 at once) and either cancels a wake in progress or begins the ordinary `StopLeaseLost` stop of an awake entry. It kills nothing itself; the existing stop ends the processes. `carlos route --replication` refuses `batched` and `daily` on an HA route. Root and instance control are unchanged.
-**Tech Stack:** Go; litestream v0.5.14 (embedded); `github.com/superfly/ltx` v0.5.1; systemd 257, kernel 6.12 (Debian 13 boxes); cgroup v2 freezer and `cgroup.kill`.
+**Tech Stack:** Go; litestream v0.5.14 (embedded); `github.com/superfly/ltx` v0.5.1.
-**Spec:** `docs/superpowers/specs/2026-11-11-g6-write-fence-design.md` rev 3.1 (Paul approved the build 2026-11-12, option 1). Writer cessation is now ruling B (below), which replaces §3.2 step 3's start refusal. Findings answered: `docs/superpowers/reviews/CODEX-FINDINGS-G6-R1.md`, `CODEX-FINDINGS-G6-R2.md`, `FABLE-SPOTCHECK-G6-FENCE.md`, and this plan's round 1, `CODEX-FINDINGS-G6-FENCE-PLAN-R1.md` (plan P1-1 to P1-6, P2-7, P2-8). `§n` is the fence spec's; `RHA §n` is `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md`.
+**Spec:** `docs/superpowers/specs/2026-11-11-g6-write-fence-design.md` rev 3.1, rewritten to rev 4 (fallback A) by Task 5: §3.2 loses the root kill, §4's bound becomes the ordinary stop's. `§n` is the fence spec's; `RHA §n` is `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md`. Findings answered: `CODEX-FINDINGS-G6-R1.md`, `CODEX-FINDINGS-G6-R2.md`, `FABLE-SPOTCHECK-G6-FENCE.md`, `CODEX-FINDINGS-G6-FENCE-PLAN-R1.md`, `CODEX-FINDINGS-G6-FENCE-PLAN-R2.md` (all under `docs/superpowers/reviews/`).
**Review history:**
-- Plan round 1 (Astra, 041a7317): NOT READY, 6 P1 + 2 P2, in the outstanding-write-age, release-cancellation and writer-cessation families plus incarnation ownership. Stopping rule 2 went to the agent manager. **Ruling B (8a3d302, 2026-11-12):** writer cessation is enforced once, in the kernel (freeze, then kill); root does no start accounting; thaw only on an unfence carrying a newer acquisition's identity, after any fence call has finished; fix the two lease-side P1s and the watcher attach; fix both P2s. Revised here.
-- **Round 2 is the last.** A P1 in round 2 in the same family sends the fence to **fallback A**: the latch plus the ordinary lease-lost stop, with no root fence, and a bound of about a minute.
+- Spec rounds 1 and 2 (Astra): NOT READY; the outstanding-write-age, writer-cessation and release-cancellation families recurred. Fable spot check of rev 3: READY AFTER FIXES. Paul approved the build (option 1).
+- Plan round 1 (Astra, 041a7317): NOT READY, 6 P1 + 2 P2. Under stopping rule 2 the agent manager ruled **B** (8a3d302, 2026-11-12): freeze and kill in the kernel, generation-ordered unfence. Rev 2 implemented B.
+- Plan round 2 (Astra, 20c60191, the last round): NOT READY, 3 P1, all writer cessation. A frozen slice can stall PID 1 without bound: instance control dies with the slice frozen, unfence drops the reaper, and an absent slice or a missing freezer gives no barrier. Round 2 resolved P1-1, P1-2, P1-5, P1-6, P2-7 and P2-8 and found no blocker in the replica-client gate.
+- **Fallback A**, per the agent manager's pre-agreed rule: the lease side stays; the root fence is dropped; writers end through the ordinary lease-lost stop. **No further plan round.** The per-task reviews (stopping rule 3: termination and production storage) and the whole-branch review are the gate.
-**Ruling B mapped to findings:** P1-1 → Task 1 (initial obligation). P1-2 → Task 2 (event independent of the renewer), Task 4 (watcher on `Fenced()`). P1-3, P1-4 → Task 3 (freeze makes queued jobs, `try-restart`, respawns and in-flight starts execute nothing; the reaper kills them). P1-5 → Task 4 (attach at replicator start, cancel a waking entry). P1-6 → Tasks 3 and 4 (lock-generation identity, serialised unfence, stale fence refused). P2-7 → Task 2 (filesystem coverage reader). P2-8 → Task 5 (subprocess test on an HA route).
+**Findings mapped:** plan P1-1 → Task 1 (initial obligation). P1-2 → Task 2 (`Fenced()` independent of the renewer) and Task 3 (watcher on `Fenced()`). P1-3, P1-4 and round 2's P1s → gone with the root fence. P1-5 → Task 3 (attach at replicator start). P1-6 → gone (no root fence to go stale). P2-7 → Task 2 (filesystem coverage reader). P2-8 → Task 4 (subprocess test).
+
+## How the ordinary stop ends the writers (the bound under A)
+
+Read from `Service.stop` (`internal/activator/activator.go:4827`) at 45421e61. After `beginStopLocked` (`:3478-3515`), the stop goroutine runs in order:
+
+1. **Sidecar start join** (`:4904-4925`): waits for a sidecar start already in flight. With generations on it waits for that start to finish, which is bounded by the supervisor's `instancectl.DeadlineControl`, **30 s** (`:3812`, `client.go:27`); with generations off, at most `sidecarStartJoinWait`, **5 s** (`:947`).
+2. **Operation join** (`:4934`, `opset.go:127-162`): cancels and joins swap members, a restore and a live resize, at most `opJoinBound` = `DeadlineControl + actStopTimeout` = **50 s** (`opset.go:101`). Empty set: returns at once.
+3. **Sidecar stop** (`:4942-4949`): `sidecarStopTimeout`, **5 s** (`:939`).
+4. **Next-due probe** (`:4995-5006`), not for workers: **5 s**.
+5. **Main process stop** (`:5012-5019`): `proc.Stop` within `actStopTimeout`, 20 s (`:3472`). For a nested unit this is a `systemctl stop` (`unitproc.go:281-306`): systemd sends SIGTERM to the main process and SIGKILLs the whole unit when **`TimeoutStopSec=20`** passes (`KillMode=mixed`, `TimeoutStopFailureMode=kill`, `carlos-instance-gen@.service:43-47`; the same 20 s in every `carlos-instance*@` unit). systemd keeps that timer even when the agent's own 20 s client budget ends first.
+
+So every main process is dead at the latest:
+- **Common case** (no swap and no sidecar start in flight at the fence): 5 + 5 + 20 = **30 s** after the stop begins. A process that honours SIGTERM ends at its own drain, which the code expects to be about 10 s (`:3470`).
+- **Worst bounded case** (a sidecar start and a swap both in flight): 30 + 50 + 5 + 5 + 20 = **110 s**.
+
+A waking entry is cancelled instead; `cleanupFailedWake` (`maintenance.go:377`) stops what the wake started on the same 20 s budget. A rootfs resident's generations are already killed at the lease loss by the existing watch (`rootfs_service.go:904-1060`), because the event closes `Lost()` whenever the renewer had nothing latched.
+
+**The bound.** From the fence line, admission refuses every new request (`servingError`, `stateless.go:258`), so a client can be told "stored" only by a request admitted before the line. Lost acknowledged writes are therefore those committed from **32 s before the fence line** until the request in flight at the line finishes, and no later than its process's death: within **30 s** of the fence line in the common case, **110 s** at the worst bounded case. At the drill's rate of about one write a second, that is at most 32 writes plus the requests in flight at the line. Unacknowledged writes, by background work inside the process, can continue until the process dies, and are discarded with the local copy at the unclean restore.
## Spec corrections (verified against this tree, 45421e61)
-1. **Line drift.** The spec cites `origin/main` 01d6ca78. Re-verify each cite before editing (main was merged at aa319b01). At 3d332f24: `servingError` `internal/activator/stateless.go:258`; `Replicator.Err`/`Lost` `internal/lease/lease.go:563`/`:569`; `finishErr` `release.go:254`; HA stream's 1 s monitor and `retainDatabase` `activator.go:3386-3393`; the publisher open `activator.go:3399-3405` → `hafiles.go:338` (`hostfiles.Open`, a store GET); `installProcLocked` after `doWake` returns `activator.go:2326`; `beginStopLocked` `activator.go:3478-3515`; `wake` stores `e.wakeCancel` `activator.go:2146-2150`; `KillHost` `genbackend.go:684-717`; `SliceName` `internal/instancectl/names.go:166`; `hostSliceEmpty` `harelease.go:50-72`; the stop's waits `activator.go:4904-4925`, `:4934`, `:5012-5019`.
-2. **`StopFenced` already exists** (`cmd.go:26`, the moves/layout fence's member-facing text; `a.fences` is the moves fence). The write fence stops with **`StopLeaseLost`**, so every consumer treats it as a lost lease (`haleaseloss.go:100-101`, `rootfs_service.go:1139`). The activator flag is `e.writeFenced`.
-3. **§3.2 step 3 (mark under `/start`'s lock, refuse every role's start) is replaced by ruling B.** `/start` has no single per-host lock, and a refusal cannot reach work already handed to systemd: `start --no-block` returns once the job is queued (`cmd.go:119`, `rootfs.go:1119`), and egress revocation restarts units through `try-restart` (`egress.go:503`). Freezing the slice's cgroup covers all of them in one place: a process that enters a frozen cgroup executes nothing. Root keeps an entry refusal at `/start`, `/seed`, `/cmd`, `/tty` and in the egress restart for a fenced host, for liveness (item 12), not correctness.
+1. **Line drift.** The spec cites 01d6ca78; re-verify each cite before editing. At 45421e61: `servingError` `stateless.go:258`; `Replicator.Err`/`Lost` `lease.go:563`/`:569`; `finishErr` `release.go:254`; HA stream's 1 s monitor and `retainDatabase` `activator.go:3386-3393`; the publisher open `activator.go:3399-3405` → `hafiles.go:338` (a store GET); `installProcLocked` after `doWake` returns `activator.go:2326`; `wake` stores `e.wakeCancel` `activator.go:2146-2150`.
+2. **`StopFenced` already exists** (`cmd.go:26`, the moves/layout fence's member-facing text). The write fence stops with **`StopLeaseLost`**; the activator flag is `e.writeFenced`.
+3. **The root kill (§3.2 steps 2-3) is dropped (fallback A).** Writers end through the ordinary stop above; nothing new runs as root.
4. **`Replica.MonitorEnabled = false` and `Replica.Stop(true)` are not safe from the fence goroutine**: `Replica.Start` reads the one and writes `r.cancel` inside `DB.init` under `db.mu` (`replica.go:94-110`), which init holds while it calls the store (`db.go:1406-1446` from `:1739-1746`). Replaced by a **gate on the replica client** (Task 2). `DB.Close` inside `finalize` still stops and joins the monitor (`db.go:791`). Stricter than F5: compaction and snapshot uploads after the event are refused.
5. **The newest L0 LTX header carries the WAL range and salts** (`ltx` v0.5.1 `ltx.go:188-191`; litestream reads them, `db.go:1510-1525`). A size-only comparison is wrong after a WAL restart (SQLite reuses the WAL without truncating it after litestream's PASSIVE checkpoints, `db.go:32-35`, `:1290-1335`). Coverage uses the salts and the frame at the captured end, on any run with unresolved obligations.
6. **A missing `-wal` is a state, not a failed `stat`**, and a WAL with no frames (≤ 32 bytes) is covered. Otherwise every HA stream instance with no database is fenced 30 s after it wakes.
7. **`DB.Pos` reads the newest LTX file on a cache miss** (`db.go:559-590`). Local, no S3 request.
-8. **The fence event is not the renewer's error.** §3.1 latches through `loseLocked`, which keeps only the first error (`health.go:137-142`). A renewal failure first (`health.go:278`) would then hide the fence (plan P1-2). The event has its own channel; the renewer gets `ErrReplicaStale` only if nothing is latched yet.
-9. **§3.2's watcher starts too late.** `installProcLocked` runs after `doWake` returns, while replication starts before the publisher open, which can block on the store (plan P1-5). The watcher attaches right after `retainDatabase`.
-10. **Identity of an acquisition: the lock's generation.** `classifyAndTake` writes `view.Lock.Generation + 1` under `If-Match` (`legacytake.go:102-115`), a release rewrites the lock as a marker that keeps the generation (`release.go:58-86`, `hafresh/lock.go:69-74`), and nothing deletes an HA lock (`TestHAReleaseAndCloseNeverDelete`). So within a host's prefix each acquisition has its own number, and a later acquisition always has a higher one. The ETag is unique but unordered; the owner string (box, pid) is unordered across boxes and re-acquires.
-11. **Residuals the build states in code comments and spec §9**: (a) a write that lands between a capture's WAL read and the next sample, when that capture finishes after the sample, then a capture stall and no further writes, is not fenced (rule A); (b) a rolled-back transaction that spilled frames, then idleness, fences spuriously; (c) a wake whose first replica sync cannot reach the store within 30 s and whose WAL has unproven frames is fenced even with no new writes; (d) if an HA lock is ever deleted and recreated (generation back to 1) while this box holds a fence record for the host at a higher generation, unfence is refused and the host stays frozen on this box until a reboot (fail closed); (e) a fenced host that never comes back to this box leaves an empty frozen slice and its reaper until a reboot.
-12. **A frozen slice can stall the system manager.** Checked on systemd 257 with a user-manager slice (2026-11-12): after `cgroup.freeze=1`, a `--no-block` start into the slice never ran; `cgroup.kill` emptied the slice (`populated 0`) and the slice cgroup stayed with `freeze 1`; a later start into it never ran either, and a kill removed it; after a thaw nothing ran. While a spawned child sat frozen before its exec, `systemctl --user show` against that manager failed or hung until the kill. systemd 257 spawns into the target cgroup and waits for the child's exec, so on a box the same would stall PID 1. Hence the reaper (Task 3), which kills anything that enters a fenced slice at once (inotify on `cgroup.events`, 100 ms poll fallback), and the entry refusals in item 3, which keep root's own starts from reaching systemd. Each unit's `ExecStopPost=carlos instance-exit` (`carlos-instance-gen@.service:38`) is such a spawn: it is killed, so a fenced unit's advisory exit record is not written. The drill measures the stall (After merge).
-13. **cgroup v2 is not pinned in code or infra.** `internal/cgroup` checks `CGROUP2_SUPER_MAGIC` and opens `cgroup.kill` per cgroup it uses (`strict_linux.go:182`, `:268`; `cleanup_linux.go:39`, `:116`; `ErrNoKill`, `cleanup.go:10`). The infra selects Debian 13's official AMI (`ami_name_pattern` `debian-13-arm64-*`, owner 136693071363, `infra/modules/region-host/variables.tf:154-165`, used by fixed boxes `main.tf:16-17` and group members `group.tf:7`) and sets no kernel command line. systemd 257 on that image boots the unified hierarchy unless a legacy override is forced; nothing forces it. That is a default, not a guarantee, so the fence op fails closed (Task 3).
- **Live check (controller, read-only SSM, 2026-11-12 ~21:55Z, all 15 running carlos boxes: flagship US fixed host, both US HA group members, IE, demo-box-1, bakeoff box-1, UK, AU; dev dev-ie, both dev-ie-group members, dev-ie-b, r10r-box, demo-box-1, dev-uk):** every box reports `fs=cgroup2fs`, kernel 6.12.x (deb13 cloud-arm64, 6.12.96 to 6.12.116), and `cgroup.freeze` and `cgroup.kill` present on `/sys/fs/cgroup/system.slice` and `/sys/fs/cgroup/carlos.slice`. Output: `~/.cache/g6-build/cgcheck.out`.
+8. **The fence event is not the renewer's error.** `loseLocked` keeps only the first error (`health.go:137-142`); a renewal failure first (`health.go:278`) would hide the fence. The event has its own channel; the renewer gets `ErrReplicaStale` only if nothing is latched yet.
+9. **§3.2's watcher starts too late.** `installProcLocked` runs after `doWake` returns, while replication starts before the publisher open, which can block on the store. The watcher attaches right after `retainDatabase`.
+10. **Residuals, stated in code comments and spec rev 4:** (a) a write that lands between a capture's WAL read and the next sample, when that capture finishes after the sample, then a capture stall and no further writes, is not fenced (rule A); (b) a rolled-back transaction that spilled frames, then idleness, fences spuriously; (c) a wake whose first replica sync cannot reach the store within 30 s and whose WAL has unproven frames is fenced even with no new writes.
## Global Constraints
-- Paul's rulings 2026-11-12: US capacity 2 x t4g.medium; pool allowlist is the env list `CONSOLE_HA_POOL_ACCOUNTS` (unset/empty = nobody); the create checkbox text names the 15-minute bound. Fence ~30 s. Fresh create, no migration. (Only the fence is this plan's.)
-- Ruling B (8a3d302, 2026-11-12): freeze then kill in the kernel; no start accounting in root; thaw only on an unfence with a newer acquisition's identity, after any fence call has finished; a stale fence is refused.
-- Fence values, verbatim from the spec: check every **1 s**; trip when the queue is non-empty and `now - t_oldest > 30 s`; the oldest lost write is at most **32 s** old at the fence line; drill `K` (fence line to every main process dead) **under 2 s**; drill loss **at most 36**. The 30 s and 1 s are constants with a test seam, not settings.
-- Journal lines (not copy-gated): lease `lease: <path>: a write has waited <age> to reach storage (local <L>, stored <R>); standing down (write fence)`; root `instance-control: <host>: write fence: generation <g>: froze and killed <slice>`, `...: <slice> empty after <d>`, `...: cannot freeze <slice>: <err>; killing without a freeze (writers started after the kill are not stopped by root)`; agent `activator: <host>: write fence: ...`.
-- COPY: no user- or operator-facing string goes into code or docs until Paul approves it. This plan's one string is `cli.route.replication_ha_refusal`; Task 5 uses `COPY-PENDING:cli.route.replication_ha_refusal host=%s`, tests assert on the constant, Task 7 swaps in the approved text from `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-g6/copy-review/result.json` (do not commit that directory). No em dashes in copy; curly quotes in user-facing text.
-- Tests: targeted only, `go test ./internal/<pkg>/ -run 'TestX|TestY' -count=1`; never `go test ./...`, never `-race` sweeps; CI on amadan runs everything. `internal/activator`, `internal/instancectl` and `internal/lease` (its lock fixture is an HTTP server) run with the sandbox OFF and `TMPDIR=$(mktemp -d /tmp/g/<task>.XXXX)`; remove that exact directory afterwards, never a glob in `/tmp/g`, `/tmp`, `$TMPDIR` or `~/.cache`. `GOCACHE` stays at its default. `GOFLAGS=-buildvcs=false` if VCS stamping errors appear. No test writes a real `/sys/fs/cgroup` file: cgroup files are behind a seam with a temp-dir root.
-- Cross-compile any task touching a package linked into the CLI: `GOOS=darwin go build . && GOOS=windows go build .`. Freeze and kill code is `_linux.go` with an `_other.go` stub answering "unsupported" (fail closed).
+- Paul's rulings 2026-11-12: US capacity 2 x t4g.medium; pool allowlist `CONSOLE_HA_POOL_ACCOUNTS` (unset/empty = nobody); the create checkbox names the 15-minute bound. Fence ~30 s. Fresh create, no migration. (Only the fence is this plan's.)
+- Fallback A (agent manager, 2026-11-12): no root or instance-control change; writers end through the ordinary lease-lost stop.
+- Fence values: check every **1 s**; trip when the queue is non-empty and `now - t_oldest > 30 s`; the oldest lost write is at most **32 s** old at the fence line. The 30 s and 1 s are constants with a test seam, not settings.
+- Journal lines (not copy-gated): `lease: <path>: a write has waited <age> to reach storage (local <L>, stored <R>); standing down (write fence)`; `activator: <host>: write fence: standing down` (with `wake cancelled` or `stopping` as the case is).
+- COPY: nothing user- or operator-facing goes into code or docs until Paul approves it. This plan's one string is `cli.route.replication_ha_refusal`: Task 4 uses `COPY-PENDING:cli.route.replication_ha_refusal host=%s`, tests assert on the constant, Task 6 swaps in the approved text from `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-g6/copy-review/result.json` (do not commit that directory). No em dashes in copy; curly quotes in user-facing text.
+- Tests: targeted only, `go test ./internal/<pkg>/ -run 'TestX|TestY' -count=1`; never `go test ./...`, never `-race` sweeps; CI on amadan runs everything. `internal/activator` and `internal/lease` (its lock fixture is an HTTP server) run with the sandbox OFF and `TMPDIR=$(mktemp -d /tmp/g/<task>.XXXX)`; remove that exact directory afterwards, never a glob in `/tmp/g`, `/tmp`, `$TMPDIR` or `~/.cache`. `GOCACHE` stays at its default. `GOFLAGS=-buildvcs=false` if VCS stamping errors appear.
+- Cross-compile any task touching a package linked into the CLI: `GOOS=darwin go build . && GOOS=windows go build .`.
- Mutation checks only on refusal, termination and lifecycle paths, at most ~10 per task, each a targeted `-run`; revert each one.
- Commit subjects under 80 characters, body after a blank line. Implementers never create or remove worktrees, never `git worktree prune`, never `git stash`, never push, never touch amadan.
-- Census: every package here is in the root binary's `go list -deps .`; Task 6 runs `make census-card` / `make census-propose NAME=g6-fence CLAIMS=<file>` and commits the overlay. Astra decides.
-- Wire shapes are additive. No new sqlite columns. Provider-neutral core: no AWS calls; the fence makes no request and adds no S3 cost.
+- Census: `internal/lease`, `internal/activator` and the root package are in the root binary's `go list -deps .`; Task 5 runs `make census-card` / `make census-propose NAME=g6-fence CLAIMS=<file>`. Astra decides.
+- Wire shapes additive; no new sqlite columns; no AWS calls (the fence makes no request and adds no S3 cost).
- Do not touch `internal/hafresh/acquire.go` (`DecideAcquire`): branch `ha-unclean-marker-waits` owns it.
## Review Focus
-1. **An HA stream instance with no database, or with an empty WAL and no writes.** Never fenced. (Task 1 `TestFenceQueueMissingWALIsAState`; Task 2 `TestWriteFenceNoDatabaseNeverTrips`.)
+1. **An HA stream instance with no database, or an empty WAL and no writes.** Never fenced. (Task 1 `TestFenceQueueMissingWALIsAState`; Task 2 `TestWriteFenceNoDatabaseNeverTrips`.)
2. **A WAL restarted after a checkpoint (length unchanged, new salts), one write, then idle, store healthy.** Never fenced. (Task 1 `TestWalCovered`; Task 2 `TestWriteFenceCheckpointRestartThenIdle`.)
3. **A store outage shorter than 30 s with writes.** No fence. (Task 1 `TestFenceQueueOutageUnder30s`; Task 2 `TestWriteFenceShortOutageNoTrip`.)
-4. **A fenced host woken again on the same box after the store returns.** The new acquire's unfence (higher generation) kills what is left and thaws before any start; an older fence arriving afterwards is refused. (Task 3 `TestUnfenceThawsOnlyForANewerGeneration`, `TestStaleFenceIsRefused`; Task 4 `TestHAAcquireUnfencesWithItsGeneration`.)
-5. **An operator sets `--replication stream` or `""` on an HA route, or `batched` on a non-HA route.** Allowed; only `batched`/`daily` on HA refused, through the real command. (Task 5.)
+4. **The fence trips while the wake is still opening the files publisher against a dead store.** The wake is cancelled and cleaned up once; nobody starts a second stop. (Task 3 `TestWriteFenceDuringABlockedPublisherOpen`.)
+5. **An operator sets `--replication stream` or `""` on an HA route, or `batched` on a non-HA route.** Allowed; only `batched`/`daily` on HA refused, through the real command. (Task 4.)
---
### Task 1: The obligation queue (internal/lease, pure)
-**Corrections for this task (read first):**
-- A missing WAL is `walState{exists: false}`; only a `stat` error that is not `os.ErrNotExist` sets `statErr` (Spec corrections 6).
-- **Initial obligation (plan P1-1).** The first sample is a baseline for change detection, but if that sample's WAL exists with frames (`size > 32`) and coverage is not proven (`covered()` false), it appends `{t: now, unknown}`. Missing or frameless WALs append nothing.
-- Resolution by `covered` (rule C) runs on any run with unknown obligations. Do not compare file size alone.
-- TXID 0 is a real resolved value (an empty WAL resolves to `L`, which may be 0); keep `known` separate.
+Unchanged from rev 2 (round 2 resolved P1-1 here).
-**Files:**
-- Create: `internal/lease/fence.go`
-- Test: `internal/lease/fence_queue_test.go` (`package lease`)
-
-**Interfaces:**
-- Produces (used by Task 2):
- - `var ErrReplicaStale = errors.New("lease: a write has waited too long to reach storage (write fence)")` (distinct from `ErrLost`)
- - `const fenceTick = time.Second`, `const fenceLimit = 30 * time.Second`
- - `type walState struct { exists bool; size int64; mod time.Time }`
- - `type fenceSample struct { L uint64; lOK bool; R uint64; W walState; statErr error }`
- - `type fenceObligation struct { t time.Time; txid uint64; known bool }`
- - `type fenceQueue struct { ob []fenceObligation; w walState; haveW bool; l, r uint64 }`
- - `func (q *fenceQueue) step(now time.Time, s fenceSample, covered func() (uint64, bool)) (trip bool)`
- - `func (q *fenceQueue) oldest() (time.Time, bool)`; `positions() (l, r uint64)`; `anyUnknown() bool`
- - `func walCovered(w walState, walHdr, frameAtEnd []byte, h *ltx.Header, l uint64) (txid uint64, ok bool)`
-
-- [ ] **Step 1: Write the failing tests.** Helper `run(q, t0, k, sample, covered)` calls `q.step(t0.Add(k*time.Second), ...)`; every scenario has a baseline sample at `k=0`; a write is a `W` change.
- - `TestFenceQueueFailingUploadTrips`: baseline `L=R=1`, WAL frameless; `k>=1` W changes, `L=1+k`, `covered` `(L,true)`, `R=1`. False for `k<=31`, true at `k==32`.
+**Corrections for this task (read first):**
+- A missing WAL is `walState{exists: false}`; only a `stat` error that is not `os.ErrNotExist` sets `statErr`.
+- **Initial obligation (plan P1-1):** the first sample is a baseline for change detection, but if its WAL exists with frames (`size > 32`) and `covered()` is false, it appends `{t: now, unknown}`. Missing or frameless WALs append nothing.
+- Rule C (`covered`) runs on any run with unknown obligations. Never compare file size alone.
+- TXID 0 is a real resolved value; keep `known` separate.
+
+**Files:** Create `internal/lease/fence.go`; test `internal/lease/fence_queue_test.go` (`package lease`).
+
+**Interfaces (produces, used by Task 2):**
+- `var ErrReplicaStale = errors.New("lease: a write has waited too long to reach storage (write fence)")` (distinct from `ErrLost`)
+- `const fenceTick = time.Second`, `const fenceLimit = 30 * time.Second`, `const walHeaderSize = 32`
+- `type walState struct { exists bool; size int64; mod time.Time }`
+- `type fenceSample struct { L uint64; lOK bool; R uint64; W walState; statErr error }`
+- `type fenceObligation struct { t time.Time; txid uint64; known bool }`
+- `type fenceQueue struct { ob []fenceObligation; w walState; haveW bool; l, r uint64 }`
+- `func (q *fenceQueue) step(now time.Time, s fenceSample, covered func() (uint64, bool)) (trip bool)`; `oldest() (time.Time, bool)`; `positions() (l, r uint64)`; `anyUnknown() bool`
+- `func walCovered(w walState, walHdr, frameAtEnd []byte, h *ltx.Header, l uint64) (txid uint64, ok bool)`
+
+- [ ] **Step 1: Write the failing tests.** Helper `run(q, t0, k, sample, covered)` calls `q.step(t0.Add(k*time.Second), ...)`; every scenario has a baseline at `k=0`; a write is a `W` change.
+ - `TestFenceQueueFailingUploadTrips`: baseline `L=R=1`, frameless; `k>=1` W changes, `L=1+k`, `covered` `(L,true)`, `R=1`. False for `k<=31`, true at `k==32`.
- `TestFenceQueueNoWritesNeverTrips`: `L=R=5`, W constant, `covered` `(5,true)`, 300 runs never true.
- `TestFenceQueueSlowThenHung` (G6-1.2): baseline `L=R=1`, `covered` `(1,true)` at `k=0` only, false after; `k>=1` W changes, `L=1+k`; `R=1` until `k=29`, then `R=3`. False through `k=32`, true at `k==33`.
- - `TestFenceQueueContinuousWritesCaptureBlocked` (G6-2.1): `L=R=5`, W changes every run from `k=1`, `covered` false from `k=1`. True first at `k==32`.
+ - `TestFenceQueueContinuousWritesCaptureBlocked` (G6-2.1): `L=R=5`, W changes from `k=1`, `covered` false from `k=1`. True first at `k==32`.
- `TestFenceQueueDelayedCaptureThenHungUpload` (G6-2.1): `L=R=5`; W changes at `k=1` only; `L=6` from `k=29` (`covered` false before, `(6,true)` from 29); `R=5`. True first at `k==32`.
- `TestFenceQueueSameRunWrite` (Fable F2): `L=R=5`; at `k=1` W changes and `L=6`; `covered` false; `R=6` from `k=2`. True first at `k==32`. Variant `covered` `(6,true)` at `k=1`: never true through `k=120`.
- `TestFenceQueueFailedStatIsAChange`: `L=R=5`; `statErr` every run from `k=1`; `covered` fails the test if called on a run with `statErr`. True first at `k==32`.
- `TestFenceQueueMissingWALIsAState`: W `{exists:false}`, `L=R=0`, 120 runs never true. Variant: frameless at baseline, missing from `k=1`, `covered` `(0,true)`: never true.
- `TestFenceQueueCapturedBeforeFirstSample`: baseline `L=7, R=5`, nothing changes. True first at `k==31`. Variant `R=7` from `k=3`: never true.
- - `TestFenceQueueUncapturedBeforeFirstSample` (plan P1-1, the exact witness): baseline `L=R=0`, WAL exists with `size = 32 + 2*(4096+24)`, `covered` false every run (no LTX: initialization hangs), W never changes. True first at `k==31`. Variants never true through `k=120`: same WAL with `covered` `(0,true)`; WAL missing; WAL `size == 32`.
+ - `TestFenceQueueUncapturedBeforeFirstSample` (plan P1-1): baseline `L=R=0`, WAL `size = 32 + 2*(4096+24)`, `covered` false every run, W never changes. True first at `k==31`. Never true through `k=120` when `covered` is `(0,true)`, the WAL is missing, or `size == 32`.
- `TestFenceQueueOutageUnder30s`: `L` and W advance every run, `covered` `(L,true)`; `R` frozen for `k=1..20`, then `R=L`. Never true through `k=120`.
- `TestWalCovered` (table; WAL header salts at bytes 16..23 big-endian, frame header salts at 8..15): WAL missing → `(l,true)`; `size <= 32` → `(l,true)`; frames and `h == nil` → false; WAL salts ≠ `h.WALSalt1/2` → false; `size <= h.WALOffset+h.WALSize` → `(h.MaxTXID,true)`; frame at end with current salts → false; frame at end with other salts → `(h.MaxTXID,true)`; `frameAtEnd` shorter than 24 bytes → no frame → `(h.MaxTXID,true)`.
@@ -141,251 +155,153 @@ func (q *fenceQueue) step(now time.Time, s fenceSample, covered func() (uint64,
}
```
-`walHeaderSize = 32`. `walCovered` implements the table. Comment residuals (a) and (b) of Spec corrections 11 on rules A and C. Each run appends at most one obligation; the goroutine exits at the trip, so the queue stays near 32 entries.
+`walCovered` implements the table. Comment residuals (a) and (b) on rules A and C. Each run appends at most one obligation and the goroutine exits at the trip, so the queue stays near 32 entries.
- [ ] **Step 4: Run to see them pass** (same command).
-
- [ ] **Step 5: Mutation checks** (revert each): drop rule A → `TestFenceQueueSlowThenHung` trips at 32; drop rule C → the covered variant of `TestFenceQueueSameRunWrite` fails; drop the first-sample obligation → `TestFenceQueueUncapturedBeforeFirstSample` fails; `>` to `>=` → `TestFenceQueueFailingUploadTrips` fails at 31; missing WAL as a stat error → `TestFenceQueueMissingWALIsAState` fails.
-
-- [ ] **Step 6: Commit.** `git add internal/lease/fence.go internal/lease/fence_queue_test.go && git commit -m "lease: write fence obligation queue (G6 F-C)"`
+- [ ] **Step 6: Commit.** `git commit -m "lease: write fence obligation queue (G6 F-C)"`
---
### Task 2: The fence event on the replicator (lease wiring, gate, release)
+Rev 2 minus the generation identity (nothing under A needs it).
+
**Corrections for this task (read first):**
-- **The event is independent of the renewer (plan P1-2).** At the trip: close `r.fenced` (once), close the gate (once), and latch `ErrReplicaStale` on the renewer only when `rn.err == nil && !rn.stopped`. The trip fires even when renewal already failed with `ErrLost`, and is what unblocks a `finalize` stuck behind `syncMu` in that case.
+- **The event is independent of the renewer (plan P1-2).** At the trip, once: close `r.fenced`, close the gate, and latch `ErrReplicaStale` on the renewer only when `rn.err == nil && !rn.stopped`. The trip fires even when renewal already failed, and it is what unblocks a `finalize` stuck behind `syncMu`.
- Do not write `Replica.MonitorEnabled` or call `Replica.Stop` (Spec corrections 4).
- `Done()` closes at the **end** of `finalize` (and in non-HA `Close`/`Abandon`), never at its start.
- `finalize` never joins the fence goroutine; the goroutine holds none of `rn.mu`, `finMu`, `syncMu` while waiting.
-- Arm only in `Held.Replicate` when `h.ha && syncInterval == 0`. Install the gate on `db.Replica.Client` after `newStore`, before `store.Open` (`DB.Open` copies the client into the compactor). Keep `newStore`'s signature.
-- **Coverage reader (plan P2-7):** decide from the sample's `stat` first. WAL missing or `size <= 32`: answer `walCovered` without any read. No L0 LTX file (`MaxLTX` gives `min == 0`): `h = nil`, not an error. Reading the frame at the end: `io.EOF`/`io.ErrUnexpectedEOF` means no frame there (pass the short slice). Any other read or open error, or a WAL header shorter than 32 bytes (the file shrank since the `stat`), answers `(0, false)`.
+- Arm only in `Held.Replicate` when `h.ha && syncInterval == 0`. Install the gate on `db.Replica.Client` after `newStore`, before `store.Open`. Keep `newStore`'s signature.
+- **Coverage reader (plan P2-7):** decide from the sample's `stat` first. WAL missing or `size <= 32`: answer without any read. No L0 LTX file (`MaxLTX` gives `min == 0`): `h = nil`, not an error. `io.EOF`/`io.ErrUnexpectedEOF` at the trailing frame: no frame (pass the short slice). Any other read or open error, or a WAL header shorter than 32 bytes, answers `(0, false)`.
- `release.go` is also edited by branch `ha-unclean-marker-waits` (the comment above `finalize`). Keep this task's `finalize` edits to two lines.
-- No lease test asserts that the next acquire takes the unclean marker at once (that branch makes it wait).
+- No lease test asserts that the next acquire takes the unclean marker at once.
-**Files:**
-- Create: `internal/lease/fencerun.go` (sampler, coverage reader, goroutine, trip)
-- Create: `internal/lease/fencegate.go`
-- Modify: `internal/lease/lease.go` (`Replicator` fields; `Replicate`; `Close`; `Abandon`; `Done`; `Fenced`; `FenceArmed`; `Generation`), `internal/lease/ha.go` (`Held.Generation`)
-- Modify: `internal/lease/release.go` (`finalize`: tag and deferred `closeDone`)
-- Modify: `internal/lease/export_test.go`
-- Test: `internal/lease/fence_test.go` (`package lease_test`), `internal/lease/fencegate_test.go`, `internal/lease/fencerun_test.go` (`package lease`)
+**Files:** Create `internal/lease/fencerun.go`, `internal/lease/fencegate.go`; modify `internal/lease/lease.go` (`Replicator` fields, `Replicate`, `Close`, `Abandon`, `Done`, `Fenced`, `FenceArmed`), `internal/lease/release.go` (`finalize`), `internal/lease/export_test.go`; tests `internal/lease/fence_test.go` (`package lease_test`), `internal/lease/fencegate_test.go`, `internal/lease/fencerun_test.go` (`package lease`).
**Interfaces:**
- Consumes: Task 1.
-- Produces (used by Task 4):
- - `func (r *Replicator) Done() <-chan struct{}` (closed once the replicator is finalized or abandoned)
- - `func (r *Replicator) Fenced() <-chan struct{}` (closed once, at the write-fence event; never closed for an unarmed replicator)
- - `func (r *Replicator) FenceArmed() bool`
- - `func (h *Held) Generation() int64`, `func (r *Replicator) Generation() int64` (the lock generation this acquisition wrote, `rn.lease.Generation` at acquire; renewals keep it)
- - `lease.ErrReplicaStale` on `r.Err()` when nothing else was latched first.
+- Produces (used by Task 3): `func (r *Replicator) Done() <-chan struct{}`; `func (r *Replicator) Fenced() <-chan struct{}` (closed once, at the event; never for an unarmed replicator); `func (r *Replicator) FenceArmed() bool`; `lease.ErrReplicaStale` on `r.Err()` when nothing else was latched first.
- Internal: `type fenceGate` (`newFenceGate`, `close`); `withFinalization(ctx)`, `finalizing(ctx)`; `func (r *Replicator) runFence(walPath string, ticks <-chan time.Time, stop func(), sampled chan<- bool)`; `func readCoverage(walPath string, w walState, l uint64, header func() (*ltx.Header, error)) (uint64, bool)`; `func (r *Replicator) tripFence(q *fenceQueue, now time.Time)`.
- Seams (`export_test.go`): `SetFenceTicksForTest(ticks <-chan time.Time, sampled chan<- bool) (restore func())` (the tick value is `now`; after each sample the goroutine sends whether it tripped); `CaptureForTest(r) error` (`r.db.Sync`); `CheckpointForTest(r, mode) error` (`r.db.Checkpoint`).
-- [ ] **Step 1: Write the failing tests.** Helper `fencedReplicator(t, fx, client)` as before: `haHeld`, `SetReplicaClientForTest`, `SetMonitorInterval(time.Hour)`, unbuffered `ticks`/`sampled`, `Replicate(ctx, tempDB(t), 0)`; `step(k)` sends `t0+k s` and returns the `sampled` answer; no step after a trip. Clients: `lsfile` (healthy), `failingReplica` (errors while `down`), `hangingReplica` (an untagged `WriteLTXFile` signals `entered` and blocks until its context ends; every call errors while `down`; records `"replica write"`).
- - `TestWriteFenceArmedOnlyForHAStream`: HA+0 true; HA+5m, HA+24h false; legacy `AcquireTTL`+0 false. `r.Generation() == h.Generation()` and equals the lock body's generation (`lockView`).
+- [ ] **Step 1: Write the failing tests.** Helper `fencedReplicator(t, fx, client)`: `haHeld`, `SetReplicaClientForTest`, `SetMonitorInterval(time.Hour)`, unbuffered `ticks`/`sampled`, `Replicate(ctx, tempDB(t), 0)`; `step(k)` sends `t0+k s` and returns the `sampled` answer; no step after a trip. Clients: `lsfile` (healthy), `failingReplica` (errors while `down`), `hangingReplica` (an untagged `WriteLTXFile` signals `entered` and blocks until its context ends; every call errors while `down`; records `"replica write"`).
+ - `TestWriteFenceArmedOnlyForHAStream`: HA+0 true; HA+5m, HA+24h false; legacy `AcquireTTL`+0 false.
- `TestWriteFenceTripsWithFailingUploads`: `failingReplica` down; `step(0)`; each `k>=1` `addRows(1)`, `CaptureForTest`, `step(k)`. False through 31, true at 32. `r.Fenced()` closed; `errors.Is(r.Err(), lease.ErrReplicaStale)`, not `ErrLost`; 2 s later unchanged.
- - `TestWriteFenceFiresAfterAnEarlierLoss` (plan P1-2): `hangingReplica`; writes and a capture; wait for `entered`; latch `ErrLost` first (a short-TTL handle, `haHeldTTL`, whose renewal the fixture fails: `fx.FailNth` on the lock PUT; wait for `r.Lost()`); start `r.ReleaseMarker(5 s budget)` and see it blocked after the final-sync hook fires; drive steps to the trip. Assert `r.Fenced()` closes, `errors.Is(r.Err(), lease.ErrLost)` (first error kept), the gate cancelled the hung call, and `ReleaseMarker` returns within 8 s with the marker unclean or owed.
+ - `TestWriteFenceFiresAfterAnEarlierLoss` (plan P1-2): `hangingReplica`; writes and a capture; wait for `entered`; latch `ErrLost` first (`haHeldTTL` with a short TTL whose renewal the fixture fails, `fx.FailNth` on the lock PUT; wait for `r.Lost()`); start `r.ReleaseMarker(5 s budget)` and see it blocked after the final-sync hook fires; drive steps to the trip. `r.Fenced()` closes, `errors.Is(r.Err(), lease.ErrLost)` (first error kept), the hung call is cancelled, `ReleaseMarker` returns within 8 s with the marker unclean or owed.
- `TestWriteFenceIdleNeverTrips`: healthy, no writes, 120 steps false.
- - `TestWriteFenceNoDatabaseNeverTrips`: no database file, 60 steps false. Variant: database in WAL mode with no writes after `Replicate` and a frameless WAL: 60 steps false.
- - `TestWriteFenceUncapturedAtFirstLook` (plan P1-1, real files): `failingReplica` down and `SetMonitorInterval(time.Hour)`; `addRows(3)` before `Replicate` returns its first sample, no `CaptureForTest`; steps: true first at 31.
- - `TestWriteFenceCheckpointRestartThenIdle`: as rev 1 (RESTART checkpoint, salts change while length does not shrink; if the case is not reached, report it, do not weaken it); 60 steps false.
+ - `TestWriteFenceNoDatabaseNeverTrips`: no database file, 60 steps false. Variant: database in WAL mode, frameless WAL, no writes: 60 steps false.
+ - `TestWriteFenceUncapturedAtFirstLook` (plan P1-1, real files): `failingReplica` down; `addRows(3)` before the first sample, no capture; true first at 31.
+ - `TestWriteFenceCheckpointRestartThenIdle`: healthy; `addRows(50)`, `r.SyncAndWait`, `CheckpointForTest(r, litestream.CheckpointModeRestart)`; in one step interval `addRows(1)`, `CaptureForTest`, `r.SyncAndWait`; the WAL header salts changed while the file did not shrink (if the case is not reached, report it, do not weaken it); 60 further steps false.
- `TestWriteFenceShortOutageNoTrip`: down for steps 1-20 with writes and captures; up from 21 with `r.SyncAndWait` each step; through 80 false.
- - `TestWriteFenceUnblocksAReleaseAlreadyWaiting` (G6-1.3, G6-2.3): as rev 1: `hangingReplica`, `entered`, `step(0)`, final-sync hook, `fx.FailNextMatching("PUT", 503, isMarkerBody)`, `down`, `ReleaseMarker(5 s budget, Clean: true)`, blocked after 200 ms, steps 1 to 31 (trip at 31). Returns within 8 s with `*lease.ObligationError`; one pending obligation; `Done()` closed; no `"replica write"` after the marker attempt; the finalization's own sync reached the client once. Clear `down`; `RetryPending` nil; `Release.Clean == false`, `Release.TXID` the finalization's.
+ - `TestWriteFenceUnblocksAReleaseAlreadyWaiting` (G6-1.3, G6-2.3): `hangingReplica`; `addRows(5)`, `CaptureForTest`; wait for `entered`; `step(0)`; the final-sync hook signals; `fx.FailNextMatching("PUT", 503, isMarkerBody)`; set `down`; `ReleaseMarker(5 s budget, Clean: true)` blocked after 200 ms; steps 1 to 31 (trip at 31). It returns within 8 s with `*lease.ObligationError`; one pending obligation; `Done()` closed; no `"replica write"` after the marker attempt; the finalization's own sync reached the client once. Clear `down`; `RetryPending` nil; `Release.Clean == false`, `Release.TXID` the finalization's.
- `TestWriteFenceEndsWithTheReplicator`: `r.Close`; `Done()` closed; a further tick is not received within 500 ms; `Fenced()` still open.
- - `TestFenceGateRefusesAndCancels` (`package lease`): as rev 1 (untagged calls cancelled at `close` and refused after it with `ErrReplicaStale`; tagged calls pass; reader and iterator release their registration on `Close`).
- - `TestReadCoverage` (`package lease`, real files in a temp dir; `header` supplied by the test): WAL missing → `(l,true)` and `header` not called; WAL of 0 and of 32 bytes → `(l,true)`, `header` not called; frames and `header` answering nil → false; frames past the captured end with the current salts → false; stale-salt frame at the end → `(MaxTXID,true)`; file ending exactly at the captured end (EOF at the frame read) → `(MaxTXID,true)`; `header` returning an error → false; WAL truncated to 10 bytes after the `stat` → false.
+ - `TestFenceGateRefusesAndCancels` (`package lease`): untagged calls in flight are cancelled at `close` and refused after it with `ErrReplicaStale` without reaching the inner client; tagged calls pass; a reader from `OpenLTXFile` and an iterator from `LTXFiles` release their registration on `Close`.
+ - `TestReadCoverage` (`package lease`, real files, `header` supplied by the test): WAL missing → `(l,true)`, `header` not called; WAL of 0 and of 32 bytes → `(l,true)`, `header` not called; frames and `header` nil → false; frames past the captured end with the current salts → false; stale-salt frame at the end → `(MaxTXID,true)`; file ending exactly at the captured end → `(MaxTXID,true)`; `header` error → false; WAL truncated to 10 bytes after the `stat` → false.
- [ ] **Step 2: Run to see them fail.** Sandbox off: `TMPDIR=$(mktemp -d /tmp/g/fence2.XXXX) go test ./internal/lease/ -run 'TestWriteFence|TestFenceGate|TestReadCoverage' -count=1` → FAIL.
- [ ] **Step 3: Implement.**
- - `fencegate.go`: every `ReplicaClient` method admits through the gate (finalizing context passes; after `close`, `ErrReplicaStale`; otherwise a child context cancelled by `context.AfterFunc` on the gate, released when the call returns, or on `Close` of a returned reader or iterator). `Type`, `SetLogger` pass through.
- - `lease.go`: `Replicator` gains `gate *fenceGate`, `generation int64`, `done`, `fenced chan struct{}`, `doneOnce`, `fenceOnce sync.Once`. `Replicate` sets `generation` from the renewer's lease; when armed wraps the client before `store.Open` and starts `runFence(db.WALPath(), ...)`. `Close` and non-HA `Abandon` call `closeDone()` after `store.Close`.
+ - `fencegate.go`: every `ReplicaClient` method admits through the gate: a finalizing context passes; after `close`, `ErrReplicaStale`; otherwise a child context cancelled by `context.AfterFunc` on the gate, released when the call returns (or on `Close` of a returned reader or iterator). `Type`, `SetLogger` pass through.
+ - `lease.go`: `Replicator` gains `gate *fenceGate`, `done`, `fenced chan struct{}`, `doneOnce`, `fenceOnce sync.Once`. `Replicate` builds `done` for every replicator; when armed, wraps the client before `store.Open` and starts `runFence(db.WALPath(), ...)`. `Close` and non-HA `Abandon` call `closeDone()` after `store.Close`.
- `release.go` `finalize`: first line `ctx = withFinalization(ctx)`; after taking `finMu`, `defer r.closeDone()`.
- - `fencerun.go`: `runFence` loops on ticks and `r.done`; each tick samples (`r.db.Pos()`, `r.db.Replica.Pos()`, `os.Stat`), calls `q.step(tick, s, func() (uint64, bool) { return readCoverage(walPath, s.W, s.L, r.newestL0Header) })`, sends on `sampled` if set, and on a trip calls `tripFence` and returns. `tripFence`: `r.fenceOnce.Do`: close `r.fenced`, `r.gate.close()`, then under `rn.mu` latch `ErrReplicaStale` if `rn.err == nil && !rn.stopped`, then log the journal line. Comment residual (c).
-
-- [ ] **Step 4: Run to see them pass**, then the neighbours: same TMPDIR, `go test ./internal/lease/ -run 'TestWriteFence|TestFenceGate|TestReadCoverage|TestFenceQueue|TestWalCovered|TestNoReplicaWriteAfterTheMarker|TestStreamCaptureOneSecond|TestHARelease|TestCleanReleaseMarker|TestEveryFailedHAReleaseIsPersisted|TestFailedMarkerIsAnObligation' -count=1` → PASS. Remove the TMPDIR.
-
-- [ ] **Step 5: Cross-compile.**
-
-- [ ] **Step 6: Mutation checks** (revert each): gate the event on `rn.err == nil` → `TestWriteFenceFiresAfterAnEarlierLoss` fails; skip `gate.close()` → `TestWriteFenceUnblocksAReleaseAlreadyWaiting` hangs; close `done` at the start of `finalize` → same test fails; drop the finalization tag → "reached the client once" fails; arm for batched → `TestWriteFenceArmedOnlyForHAStream` fails; map EOF at the frame read to `(0,false)` → `TestReadCoverage` fails.
-
-- [ ] **Step 7: Commit.** `git commit -m "lease: arm the write fence on HA stream replicators"` with a body naming G6-1.3, G6-2.3, F6, plan P1-1, P1-2, P2-7.
-
----
-
-### Task 3: Root freezes and kills a fenced host (internal/instancectl)
-
-**Corrections for this task (read first):**
-- **Ruling B.** Writer cessation is the freeze. Root does **no** start accounting: no counters, no `startInSlice`, no wait for in-flight starts. Correctness must not rest on the entry refusals; they exist to keep root's own starts out of systemd (Spec corrections 12).
-- Freeze and kill the **slice's own cgroup**, `<CgroupRoot>/carlos.slice/carlos-instances.slice/<SliceName(host)>` (`SliceControlGroup`, `names.go:172`). Never freeze `carlos-instances.slice` (shared by every host). Not `systemctl freeze`/`kill`: root writes the kernel files, so the state lives in the kernel, not in systemd's bookkeeping.
-- **Order:** write the fence record, then `cgroup.freeze=1`, then `cgroup.kill`, then wait. A crash after the freeze always leaves a record.
-- **Fail closed** when the slice is not on cgroup2 (`Fstatfs` magic) or `cgroup.freeze` cannot be opened or written: log the "cannot freeze" line, write `cgroup.kill` if present, else `systemctl kill --signal=SIGKILL <slice>`, record `frozen: false`, answer 200 with `Frozen: false`. Bound in that case: acknowledged writes keep the 32 s + `K` bound (admission refused every request from the latch), but a writer started after the kill by a job already queued or in flight is not stopped by root; the agent's ordinary stop ends it (`actStopTimeout`, 20 s) and its local writes are discarded at the unclean restore.
-- **Absent slice cgroup**: no process ran in it, or systemd removed it. Write the record and answer `Empty: true, Frozen: false`, with no freeze; a later start creates the slice unfrozen, so the record makes every start refused at entry and the reaper is armed to freeze the slice cgroup the moment it appears (inotify on the parent directory, poll fallback).
-- `/fence` and `/unfence` are not wrapped in `claimAwareLegacy`.
-
-**Files:**
-- Create: `internal/instancectl/fence.go` (state, records, handlers, reaper, client methods), `internal/instancectl/fence_linux.go` (freeze, kill, events, inotify), `internal/instancectl/fence_other.go` (unsupported stubs)
-- Modify: `internal/instancectl/server.go` (`Server` gains `FenceDir string` (default `/run/carlos-control/fence`), `fence hostFences`, a `fenceFS` seam; `Handler()` registers `POST /fence`, `POST /unfence`; `handleStart`, `handleSeed` call `refuseFenced` after `parseRequest`; startup calls `s.resumeFences()`)
-- Modify: `internal/instancectl/cmd.go` (`startOneShot`: `refuseFenced` after `parseRequest`)
-- Modify: `internal/instancectl/egress.go` near `:497` (`restartRunning` skips a fenced host's units, logging it)
-- Test: `internal/instancectl/fence_test.go`
-
-**Interfaces:**
-- Produces (used by Task 4):
- - `type FenceResponse struct { Slice string `json:"slice"`; Frozen bool `json:"frozen"`; Empty bool `json:"empty"` }`
- - `var ErrHostFenced`, `ErrStaleFence`, `ErrStaleUnfence` (journal/HTTP text, not copy)
- - `const DeadlineFence = 45 * time.Second`
- - `func (c *Client) Fence(ctx context.Context, host string, generation int64) (FenceResponse, error)` (`POST /fence?host=&generation=`), `func (c *Client) Unfence(ctx context.Context, host string, generation int64) error` (`POST /unfence?host=&generation=`, `DeadlineFence`)
-- Internal:
- - `type fenceRecord struct { FencedGen int64 `json:"fenced_generation"`; LiveGen int64 `json:"live_generation"`; Fenced bool `json:"fenced"`; Frozen bool `json:"frozen"` }`, one file per host, `<FenceDir>/<provision.InstanceID(host)>.json`, written atomically (temp + rename); `FenceDir` is root's (0700).
- - `type hostFences struct { mu sync.Mutex; hosts map[string]*hostFenceState }`; `hostFenceState` has its own `sync.Mutex` held for a whole fence or unfence operation, the record, and the reaper's cancel.
- - `type fenceFS interface { Freeze(dir string, on bool) error; Kill(dir string) error; Events(dir string) (exists, populated bool, err error); Watch(ctx context.Context, dir string) <-chan struct{} }` (Linux: cgroup2 `Fstatfs` check, `cgroup.freeze`, `cgroup.kill`, `cgroup.events`, inotify; tests: a fake over a temp dir)
- - `func (s *Server) refuseFenced(w http.ResponseWriter, host string) bool` (409, `ErrHostFenced`)
-
-`handleFence(host, g)`: validate host (`ValidHostShape`) and `g > 0`, else 400 with nothing written. Take the host's operation mutex. If `g < rec.LiveGen` → 409 `ErrStaleFence`, nothing written (a newer acquisition owns the host). Write the record (`Fenced`, `FencedGen = g`). Freeze (or fail closed as above), kill, log the froze-and-killed line. Wait until `Events` says unpopulated, killing again on every repopulation (each unit's `ExecStopPost` spawn lands frozen), bounded by the request context: empty → `Empty: true`, log the empty line; deadline → 504, record kept. Start the host's reaper (if not running), then release the mutex.
-
-Reaper: while the record says `Fenced`, on every `Watch` signal or 100 ms tick, if populated, `Kill` and log once per burst; if the slice cgroup appears and is not frozen, `Freeze` then `Kill`. Ends at unfence.
-
-`handleUnfence(host, g)`: validate. Take the host's operation mutex (so it waits for a fence in progress). If `rec.Fenced` and `g <= rec.FencedGen` → 409 `ErrStaleUnfence`. If fenced: stop the reaper, `Kill`, wait unpopulated (bounded; on timeout 504, still fenced), `Freeze(false)`, log `...: generation <g>: thawed <slice>`. Set `Fenced = false`, `LiveGen = max(LiveGen, g)`, write the record. 200. An unfence on a host never fenced just records `LiveGen`.
-
-`resumeFences()` at service start: read every record in `FenceDir`; for each `Fenced` one, re-arm its reaper and re-freeze if the slice cgroup exists unfrozen. A slice cgroup under `carlos-instances.slice` that reads `cgroup.freeze 1` with no record is left frozen and logged (`frozen with no fence record; it stays frozen until an operator thaws it or the box reboots`): fail closed. Records are on `/run` (tmpfs): a reboot clears both them and every cgroup.
-
-- [ ] **Step 1: Write the failing tests** (fake `fenceFS`; fake `Systemctl`; `FenceDir` a temp dir):
- - `TestFenceFreezesThenKillsAndWaits`: slice populated; `POST /fence?host=shop.example.com&generation=7` → 200 `{Slice, Frozen: true, Empty: true}`; the fake's call order is record written, `Freeze(on)`, `Kill`, then events polled until the fake reports unpopulated after the kill; record `{FencedGen 7, Fenced, Frozen}`.
- - `TestFenceKillsEveryRepopulation`: the fake repopulates twice after the first kill (stop-post spawns); the op kills three times and answers once empty.
- - `TestFrozenSliceRunsNoQueuedStart` (plan P1-3, P1-4): after `/fence`, the fake simulates a queued `--no-block` job, an egress `try-restart` and a respawn each entering the slice (populated, frozen): the reaper kills each within 200 ms; no fake process "runs" (the fake records a process as run only if the slice is unfrozen when it enters). The egress asserter's `restartRunning` on the fenced host issues no `try-restart` and logs the skip.
- - `TestFenceFailsClosedWithoutAFreezer`: `Freeze` answers unsupported; `Kill` still written; 200 with `Frozen: false`; the cannot-freeze line logged. Variant `Kill` unsupported: `systemctl kill --signal=SIGKILL <slice>` is called.
- - `TestFenceAbsentSlice`: `Events` says absent → 200 `Empty: true, Frozen: false`, record `Fenced`; when the fake makes the slice cgroup appear, the reaper freezes then kills it.
- - `TestFenceRefusesBadInput`: `host=../x`, `generation` missing, 0 or not a number → 400, no fake call, no record.
- - `TestStaleFenceIsRefused` (plan P1-6): `/unfence?generation=8` on an unfenced host, then `/fence?generation=7` → 409 `ErrStaleFence`, no freeze, no kill.
- - `TestUnfenceThawsOnlyForANewerGeneration`: fenced at 7: `/unfence?generation=7` and `=6` → 409 `ErrStaleUnfence`, still frozen; `=8` → kill, wait, `Freeze(off)`, 200, record `{Fenced: false, LiveGen: 8}`; `/start` then reaches `systemctl start`.
- - `TestOldFenceAgainstNewAcquire` (plan P1-6, deterministic): a test hook pauses `/fence?generation=7` after the record write and before the kill; send `/unfence?generation=8`; it does not answer while the fence is paused; release the hook: the fence finishes (freeze, kill); then the unfence kills what is left and thaws; final record `{Fenced: false, LiveGen: 8}`. A second `/fence?generation=7` afterwards → 409, nothing written.
- - `TestFencedHostRefusedAtEntry`: after `/fence`, `/start` (run, sidecar, worker), `/seed`, `/cmd`, `/tty` answer 409 with `ErrHostFenced`'s text and the fake `Systemctl` sees no start. Build the queries from the existing tests of each path.
- - `TestResumeFencesAfterRestart`: a record `Fenced` at 7 and a fake slice unfrozen and populated; a new `Server` over the same `FenceDir` runs `resumeFences`: the slice is frozen and killed, the reaper armed, `/start` refused; `/unfence?generation=8` thaws. A frozen slice with no record stays frozen and is logged.
- - `TestClientFenceAndUnfence`: through `client_test.go`'s harness: generation is sent; 409s surface as errors carrying the text.
-
-- [ ] **Step 2: Run to see them fail.** Sandbox off: `TMPDIR=$(mktemp -d /tmp/g/fence3.XXXX) go test ./internal/instancectl/ -run 'TestFence|TestFrozenSlice|TestStaleFence|TestUnfence|TestOldFence|TestFencedHost|TestResumeFences|TestClientFence' -count=1` → FAIL.
-
-- [ ] **Step 3: Implement.** The Linux `fenceFS` opens the cgroup directory `O_DIRECTORY|O_NOFOLLOW` under `CgroupRoot`, checks `CGROUP2_SUPER_MAGIC` with `Fstatfs` (as `cleanup_linux.go:39` does), and writes `cgroup.freeze`/`cgroup.kill` with `openat`. Reuse `internal/cgroup` helpers where they fit; do not write `cgroup.kill` to any cgroup other than the host slice's.
-
-- [ ] **Step 4: Run to see them pass**, plus the start and egress paths: same TMPDIR, Step 2's command, then `go test ./internal/instancectl/ -run 'TestStart|TestSeed|TestCmd|TestTTY|TestEgress|TestRootfs' -count=1` → PASS. Remove the TMPDIR.
+ - `fencerun.go`: `runFence` loops on ticks and `r.done`; each tick samples (`r.db.Pos()`, `r.db.Replica.Pos()`, `os.Stat`), calls `q.step(tick, s, func() (uint64, bool) { return readCoverage(walPath, s.W, s.L, r.newestL0Header) })`, sends on `sampled` if set, and on a trip calls `tripFence` and returns. `tripFence`, under `r.fenceOnce`: close `r.fenced`, `r.gate.close()`, latch on the renewer as above, log the journal line. Comment residual (c).
+- [ ] **Step 4: Run to see them pass**, then the neighbours: `go test ./internal/lease/ -run 'TestWriteFence|TestFenceGate|TestReadCoverage|TestFenceQueue|TestWalCovered|TestNoReplicaWriteAfterTheMarker|TestStreamCaptureOneSecond|TestHARelease|TestCleanReleaseMarker|TestEveryFailedHAReleaseIsPersisted|TestFailedMarkerIsAnObligation' -count=1` → PASS. Remove the TMPDIR.
- [ ] **Step 5: Cross-compile.**
-
-- [ ] **Step 6: Mutation checks** (revert each): kill before freeze → `TestFenceFreezesThenKillsAndWaits` order fails; drop the reaper → `TestFrozenSliceRunsNoQueuedStart` fails; accept `g <= FencedGen` on unfence → `TestUnfenceThawsOnlyForANewerGeneration` fails; drop the `LiveGen` check on fence → `TestStaleFenceIsRefused` fails; release the host mutex before the kill → `TestOldFenceAgainstNewAcquire` fails; skip `resumeFences` → `TestResumeFencesAfterRestart` fails; return 502 without killing when the freeze fails → `TestFenceFailsClosedWithoutAFreezer` fails.
-
-- [ ] **Step 7: Commit.** `git commit -m "instancectl: write fence freezes and kills the host slice"` with a body: ruling B; generation identity; reaper; fail closed.
+- [ ] **Step 6: Mutation checks** (revert each): gate the event on `rn.err == nil` → `TestWriteFenceFiresAfterAnEarlierLoss` fails; skip `gate.close()` → `TestWriteFenceUnblocksAReleaseAlreadyWaiting` hangs; close `done` at the start of `finalize` → same test fails; drop the finalization tag → "reached the client once" fails; arm for batched → `TestWriteFenceArmedOnlyForHAStream` fails; EOF at the frame read as `(0,false)` → `TestReadCoverage` fails.
+- [ ] **Step 7: Commit.** `git commit -m "lease: arm the write fence on HA stream replicators"` (body: G6-1.3, G6-2.3, F6, plan P1-1, P1-2, P2-7).
---
-### Task 4: The activator watches, stops and fences (internal/activator)
+### Task 3: The activator stands down on the event (internal/activator)
**Corrections for this task (read first):**
+- **No kill, no root call.** The watcher only marks, refuses and starts the existing stop; the stop's own steps end the processes (see "How the ordinary stop ends the writers"). Do not add a `KillHost`, a `Control` method or any instancectl change.
- Stop with `StopLeaseLost`, never `StopFenced`. Begin a stop only from `actAwake`.
-- **Attach at replicator start (plan P1-5).** Right after `retainDatabase` returns a replicator in `doWake` (`activator.go:3389-3393`), before the publisher open. A waking entry is not stopped by the watcher: it sets `e.writeFenced` and calls `e.wakeCancel()`, so `doWake` fails and `cleanupFailedWake` stays the one stop owner. `installProcLocked` keeps an idempotent call for replicas installed on other paths.
-- **The watcher waits on `Fenced()` (plan P1-2)**, not on `Lost()` plus an error test, so it acts when the lease was already lost.
-- **Identity (plan P1-6):** the fence call carries `rep.Generation()`; the unfence after an HA acquire carries `held.Generation()`. The unfence is mandatory: if it fails, the acquire fails and the held lease is released with `held.ReleaseMarker(ctx, hafresh.Marker{})` (unclean, nothing was replicated), before any restore or start. Root orders an old fence against the new unfence (Task 3); the agent need not wait for its own fence RPC.
-- Not `KillHost` (`genbackend.go:684-717`, the exec cgroup).
-
-**Files:**
-- Create: `internal/activator/writefence.go`, `internal/activator/writefence_test.go`
-- Modify: `internal/activator/activator.go` (`actEntry` gains `writeFenced bool`, `fenceRep Rep`; `Service` gains `fenceWatchers sync.WaitGroup`; `doWake` attaches after `retainDatabase`; `installProcLocked` attaches idempotently)
-- Modify: `internal/activator/swapadmit.go:88-102` (`ownedLocked`: `case e.writeFenced: return errSwapLeaseLost` after the identity case)
-- Modify: `internal/activator/hawake.go:425-436` (unfence after the HA acquire)
-- Modify (test double): `internal/activator/unitproc_test.go` (`fakeControl.Fence`, `Unfence`, `fenceHook`, `unfenceErr`; calls recorded as `fence <host> <g>`, `unfence <host> <g>`)
+- **Attach at replicator start (plan P1-5):** right after `retainDatabase` returns a replicator in `doWake` (`activator.go:3389-3393`), before the publisher open. A waking entry is not stopped by the watcher: it sets `e.writeFenced` and calls `e.wakeCancel()`; `doWake` fails and `cleanupFailedWake` stays the one stop owner. `installProcLocked` attaches idempotently for replicas installed on other paths.
+- **Wait on `Fenced()` (plan P1-2)**, not on `Lost()` plus an error test, so it acts when the lease was already lost.
+- **Fast path:** `servingError` (`stateless.go:258`) answers `lease.ErrReplicaStale` when `e.writeFenced` is set, before reading `e.rep`; `ownedLocked` (`swapadmit.go:88-102`) answers `errSwapLeaseLost` for it right after the identity case, so waking callers refuse spawns too.
+
+**Files:** Create `internal/activator/writefence.go`, `internal/activator/writefence_test.go`; modify `internal/activator/activator.go` (`actEntry` gains `writeFenced bool`, `fenceRep Rep`; `Service` gains `fenceWatchers sync.WaitGroup`; `doWake` attaches after `retainDatabase`; `installProcLocked` attaches idempotently), `internal/activator/stateless.go` (`servingError`), `internal/activator/swapadmit.go` (`ownedLocked`).
**Interfaces:**
-- Consumes: Task 2 `Done`, `Fenced`, `FenceArmed`, `Generation`, `Held.Generation`; Task 3 `FenceResponse`, `Client.Fence`, `Client.Unfence`, `DeadlineFence`.
+- Consumes: Task 2 `Done`, `Fenced`, `FenceArmed`, `ErrReplicaStale`.
- Produces:
- - `type FenceControl interface { Fence(ctx context.Context, host string, generation int64) (instancectl.FenceResponse, error); Unfence(ctx context.Context, host string, generation int64) error }`; `var _ FenceControl = (*instancectl.Client)(nil)`
- - `type writeFenceRep interface { Fenced() <-chan struct{}; Done() <-chan struct{}; FenceArmed() bool; Generation() int64 }`; `var _ writeFenceRep = (*lease.Replicator)(nil)`
- - `type hostFencer interface { fenceHost(ctx context.Context, rt registry.Route, generation int64) (instancectl.FenceResponse, error); unfenceHost(ctx context.Context, rt registry.Route, generation int64) error }` on `*ExecBackend` (via `b.Control.(FenceControl)`; none is an error) and `*SplitBackend` (dispatch through `pick(rt)`)
+ - `type writeFenceRep interface { Fenced() <-chan struct{}; Done() <-chan struct{}; FenceArmed() bool }`; `var _ writeFenceRep = (*lease.Replicator)(nil)`
- `func (a *Service) watchWriteFenceLocked(e *actEntry, rep Rep)`: requires `rep.(writeFenceRep)` armed and an HA replica; returns if `e.fenceRep == rep`; sets `e.fenceRep = rep`, `a.fenceWatchers.Add(1)`, `go a.watchWriteFence(e, rep, w)`.
- - `func (a *Service) watchWriteFence(e *actEntry, rep Rep, w writeFenceRep)`: select `w.Done()` (return) or `w.Fenced()`. Under `a.mu`: if `a.entries[e.host] != e || e.fenceRep != rep`, return; `e.writeFenced = true`; `actAwake` → `beginStopLocked(e, StopLeaseLost)`; waking (`e.wakeCancel != nil` and not yet installed) → `e.wakeCancel()`; stopping → nothing; copy `e.route`. Off `a.mu`: log, `fenceHost(ctx with DeadlineFence, rt, w.Generation())`, log the answer (`frozen`, `empty`) or the error loudly; a `Frozen: false` answer is logged as the fail-closed case.
-
-- [ ] **Step 1: Write the failing tests.** Fixture: `haServiceEntry` with a `fenceTestRep` (embeds the entry's `Rep` and `haRep`, adds test-controlled `fenced`, `done` channels, `Generation() == 7`, `FenceArmed() == true`, an `Err` the test sets); swap it in under `a.mu`, call `watchWriteFenceLocked(e, rep)`. "Trip" = close `fenced`.
- - `TestWriteFenceAnswersLikeALostLease`: trip with `Err` `ErrReplicaStale` → `assertLostResponse`.
- - `TestWriteFenceActsAfterAnEarlierLoss` (plan P1-2): `Err` is `lease.ErrLost` and the entry already stopping on it; trip → `fence shop.example.com 7` is called; no second stop.
- - `TestWriteFenceRequestAndWatcherStopOnce` (G6-1.4): trip and a request concurrently: one stop, one marker write, one `fence` call.
- - `TestWriteFenceKillsDuringABlockedStop` (G6-2.3), subtests `start-done`, `op-join`, `process-drain`: as rev 1; the `fenceHook` releases the wait; stop completes within 10 s; `stopWhy` unchanged; no second stop.
- - `TestWriteFenceDuringABlockedPublisherOpen` (plan P1-5): a wake whose `FilesStore` GET blocks until its context ends (wrap the store in the fixture); while blocked, trip the real replicator's fence through the lease seams, or the `fenceTestRep` attached at the `retainDatabase` point (use a `retainDatabase` test seam returning it). Assert `fence <host> <g>` is called while the GET is still blocked, the wake fails with the cancelled context, `cleanupFailedWake` runs once, no `beginStopLocked` happened, and the entry ends asleep.
- - `TestWriteFenceKillTargetsTheSliceNotTheExecCgroup` (G6-2.2): `openHostCleanup` fails the test if called; trip; `fence` called.
- - `TestWriteFenceWatcherEndsOnCleanHibernation`: `stopForTest(e)`; `done` closed by the fake's `Finish`; `fenceWatchers.Wait()` within 5 s; no `fence`.
- - `TestWriteFenceRefusesSpawnsWhileWaking`: `e.writeFenced` → `ownedLocked(e, true)` is `errSwapLeaseLost`.
- - `TestHAAcquireUnfencesWithItsGeneration` (Review Focus 4): a fresh HA wake records `unfence <host> <lock generation>` (read from the fixture's lock body) before any `start`. With `unfenceErr` set: the wake fails, no `start` call, the lock holds an unclean marker, the entry is gone.
- - `TestWriteFenceLatchToKillWiring` (G6-2.4, wiring): as rev 1.
-
-- [ ] **Step 2: Run to see them fail.** Sandbox off: `TMPDIR=$(mktemp -d /tmp/g/fence4.XXXX) go test ./internal/activator/ -run 'TestWriteFence|TestHAAcquireUnfences' -count=1` → FAIL.
-
+ - `func (a *Service) watchWriteFence(e *actEntry, rep Rep, w writeFenceRep)`: select `w.Done()` (return) or `w.Fenced()`. Under `a.mu`: if `a.entries[e.host] != e || e.fenceRep != rep`, return; `e.writeFenced = true`; `actAwake` → `a.beginStopLocked(e, StopLeaseLost)`; waking (the wake has not installed this entry yet and `e.wakeCancel != nil`) → `e.wakeCancel()`; stopping → nothing. Log the journal line with the case.
+
+- [ ] **Step 1: Write the failing tests.** Fixture: `haServiceEntry` (`harelease_test.go:221`) with a `fenceTestRep` that embeds the entry's `Rep` and `haRep` (as `lossTestRep` does, `haleaseloss_test.go:21-42`) and adds test-controlled `fenced`, `done` channels, an `Err` the test sets and `FenceArmed() == true`; swap it in under `a.mu` and call `watchWriteFenceLocked(e, rep)`. "Trip" = close `fenced`.
+ - `TestWriteFenceAnswersLikeALostLease`: trip with `Err` still nil (the renewer had latched nothing yet in this fake) → `assertLostResponse(t, s)` (503, `Retry-After: 10`, `X-Carlos-Holder: none`, no proxy, within 1 s), by the `writeFenced` fast path.
+ - `TestWriteFenceActsAfterAnEarlierLoss` (plan P1-2): `Err` is `lease.ErrLost` and the entry already stopping on it; trip → `e.writeFenced` set, no second stop, `stopWhy` still `StopLeaseLost`.
+ - `TestWriteFenceRequestAndWatcherStopOnce` (G6-1.4): trip and a request concurrently: exactly one stop (count `beginStopLocked` through the fake rep's `ReleaseMarker`/`Finish` calls == 1), one marker write to the lock.
+ - `TestWriteFenceDuringABlockedStop` (G6-2.3), subtests `start-done`, `op-join`, `process-drain`: an ordinary `StopIdle` stop blocked in each wait (`a.joinWaiting` reports `"sidecar start"`; an operation member left running for `joinOps`; a process whose stop blocks until released). Trip: no second stop begins, `stopWhy` stays `StopIdle`, admission answers 503 at once; release the wait: the stop completes within 10 s and releases once.
+ - `TestWriteFenceDuringABlockedPublisherOpen` (plan P1-5, Review Focus 4): a wake whose `FilesStore` GET blocks until its context ends (wrap the fixture's store); a `retainDatabase` test seam returns the `fenceTestRep`; while the GET is blocked, trip. The GET returns on the cancelled context, the wake fails, `cleanupFailedWake` runs once, `beginStopLocked` never ran, the entry ends asleep, the lock holds an unclean marker.
+ - `TestWriteFenceWatcherEndsOnCleanHibernation`: `stopForTest(e)` (`StopIdle`); the fake's `Finish` closes `done`; `fenceWatchers.Wait()` returns within 5 s; one stop.
+ - `TestWriteFenceRefusesSpawnsWhileWaking`: with `e.writeFenced`, `a.ownedLocked(e, true)` is `errSwapLeaseLost`.
+ - `TestWriteFenceAttachesOnce`: `installProcLocked` after the `doWake` attach starts no second watcher (`fenceWatchers` count 1).
+
+- [ ] **Step 2: Run to see them fail.** Sandbox off: `TMPDIR=$(mktemp -d /tmp/g/fence3.XXXX) go test ./internal/activator/ -run 'TestWriteFence' -count=1` → FAIL.
- [ ] **Step 3: Implement** `writefence.go` and the edits listed.
-
-- [ ] **Step 4: Run to see them pass**, plus: `go test ./internal/activator/ -run 'TestHALost|TestHARelease|TestRestoreHA|TestHAWake|TestDrain|TestStreamCapture|TestHAFiles' -count=1` → PASS. Remove the TMPDIR.
-
+- [ ] **Step 4: Run to see them pass**, plus `go test ./internal/activator/ -run 'TestHALost|TestHARelease|TestRestoreHA|TestHAWake|TestDrain|TestStreamCapture|TestHAFiles' -count=1` → PASS. Remove the TMPDIR.
- [ ] **Step 5: Cross-compile.**
-
-- [ ] **Step 6: Mutation checks** (revert each): wait on `Lost()` and test the error → `TestWriteFenceActsAfterAnEarlierLoss` fails; attach only in `installProcLocked` → `TestWriteFenceDuringABlockedPublisherOpen` fails; `beginStopLocked` on a waking entry → same test fails (two owners); drop the `actAwake` guard → `TestWriteFenceRequestAndWatcherStopOnce` fails; ignore `Done()` → `TestWriteFenceWatcherEndsOnCleanHibernation` fails; make the unfence best effort → `TestHAAcquireUnfencesWithItsGeneration` fails.
-
-- [ ] **Step 7: Commit.** `git commit -m "activator: write fence watcher from replicator start"` with a body naming plan P1-2, P1-5, P1-6, G6-1.4, G6-2.2, G6-2.3.
+- [ ] **Step 6: Mutation checks** (revert each): wait on `Lost()` and test the error → `TestWriteFenceActsAfterAnEarlierLoss` and `TestWriteFenceAnswersLikeALostLease` fail; attach only in `installProcLocked` → `TestWriteFenceDuringABlockedPublisherOpen` fails; `beginStopLocked` on a waking entry → same test fails (two owners); drop the `actAwake` guard → `TestWriteFenceRequestAndWatcherStopOnce` fails; drop the `servingError` fast path → `TestWriteFenceAnswersLikeALostLease` fails; ignore `Done()` → `TestWriteFenceWatcherEndsOnCleanHibernation` fails.
+- [ ] **Step 7: Commit.** `git commit -m "activator: stand down on the write fence from replicator start"` (body: plan P1-2, P1-5, G6-1.4, G6-2.3; fallback A).
---
-### Task 5: The replication rail on HA routes (cli.go)
+### Task 4: The replication rail on HA routes (cli.go)
+
+Unchanged from rev 2 (round 2 resolved P2-8).
**Corrections for this task (read first):**
- Keep `replicationRail`'s signature; add a separate rail.
-- **The command must be proven to call it (plan P2-8):** a subprocess test on an HA route, in `TestRouteReplicationSetsAndClearsTheRung`'s shape (`route_replication_test.go:116`, `buildCarlos`, `carlosTestEnv`, `cmd.Dir` scratch).
+- **The command must be proven to call it (plan P2-8):** a subprocess test on an HA route in `TestRouteReplicationSetsAndClearsTheRung`'s shape (`route_replication_test.go:116`: `buildCarlos`, `carlosTestEnv`, `cmd.Dir` scratch).
- Existing HA routes with another class keep it; only setting `batched`/`daily` is refused.
-**Files:**
-- Modify: `cli.go` (`runRouteReplication` calls the new rail right after `replicationRail`, before the "already" check)
-- Test: `route_replication_test.go`
+**Files:** Modify `cli.go` (`runRouteReplication` calls the new rail right after `replicationRail`, before the "already" check); test `route_replication_test.go`.
-**Interfaces:**
-- Produces: `const routeReplicationHARefusalFmt = "COPY-PENDING:cli.route.replication_ha_refusal host=%s"`; `func replicationHARail(rt registry.Route, class string) error`.
+**Interfaces (produces):** `const routeReplicationHARefusalFmt = "COPY-PENDING:cli.route.replication_ha_refusal host=%s"`; `func replicationHARail(rt registry.Route, class string) error`.
- [ ] **Step 1: Write the failing tests.**
- `TestReplicationHARail`: HA + `batched`/`daily` → error text `fmt.Sprintf(routeReplicationHARefusalFmt, host)`; HA + `""`/`stream` → nil; non-HA, all four → nil.
- - `TestRouteReplicationRefusedOnAnHARoute` (subprocess): `carlos add -registry ... -hibernate <host>`; mark the row HA with `registry.Open(regPath)` + `SetHA(host)`; `carlos route -registry ... -host <host> -replication batched` exits non-zero, output contains `fmt.Sprintf(routeReplicationHARefusalFmt, host)`, the column is unchanged (`""`); the same for `daily`; `-replication stream` exits 0 and the column reads `stream`. If the HA row's write is refused by another door first (a forwarding or HA guard), assert the rail's text still appears for `batched`; if it cannot, report it, do not drop the test.
-
-- [ ] **Step 2: Run to see them fail.** `go test . -run 'TestReplicationHARail|TestRouteReplicationRefusedOnAnHARoute' -count=1` → FAIL.
-
+ - `TestRouteReplicationRefusedOnAnHARoute` (subprocess): `carlos add -registry ... -hibernate <host>`; `registry.Open(regPath)` + `SetHA(host)`; `route -replication batched` exits non-zero, output contains the formatted constant, the column stays `""`; the same for `daily`; `-replication stream` exits 0 and the column reads `stream`. If another door refuses the HA row's write first, report it; do not drop the test.
+- [ ] **Step 2: Run to see them fail.** `go test . -run 'TestReplicationHARail|TestRouteReplicationRefusedOnAnHARoute' -count=1`.
- [ ] **Step 3: Implement** the rail and the call.
-
- [ ] **Step 4: Run to see them pass**, with `TestRouteReplication|TestReplicationRail|TestRootfsReplication`.
-
- [ ] **Step 5: Cross-compile.**
-
-- [ ] **Step 6: Mutation checks**: drop the `rt.HA` condition → non-HA rows fail; remove the call from `runRouteReplication` → `TestRouteReplicationRefusedOnAnHARoute` fails.
-
+- [ ] **Step 6: Mutation checks:** drop the `rt.HA` condition → non-HA rows fail; remove the call from `runRouteReplication` → `TestRouteReplicationRefusedOnAnHARoute` fails.
- [ ] **Step 7: Commit.** `git commit -m "route: refuse batched and daily replication on HA routes (G6)"`
---
-### Task 6: Spec text and the census card
+### Task 5: Spec rev 4 (fallback A), RHA §5.5 and the census card
**Corrections for this task (read first):**
- Branch `ha-unclean-marker-waits` also edits the region HA spec. Change only §5.5 there.
-- Re-run `census-propose` with the same NAME if a later commit touches a census file (Task 7 will).
+- Use the figures in "How the ordinary stop ends the writers" with their citations; do not round them into a promise the code does not keep.
+- Re-run `census-propose` with the same NAME if a later commit touches a census file (Task 6 will).
-**Files:**
-- Modify: `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` (§5.5)
-- Modify: `docs/superpowers/specs/2026-11-11-g6-write-fence-design.md` (append `## 9. Build notes (plan 2026-11-12, ruling B)`)
-- Create (generated): `internal/provision/testdata/plan14-root-reads-g6-fence.tsv`, its chain line, `docs/superpowers/notes/census-proposal-g6-fence.md`
+**Files:** Modify `docs/superpowers/specs/2026-11-11-g6-write-fence-design.md`, `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` (§5.5); create (generated) `internal/provision/testdata/plan14-root-reads-g6-fence.tsv`, its chain line, `docs/superpowers/notes/census-proposal-g6-fence.md`.
-- [ ] **Step 1: RHA §5.5.** Add exactly: "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."
+- [ ] **Step 1: Rev 4 note** at the top of the fence spec, dated 2026-11-12: spec rounds 1-2 and the recurring families; plan round 1 and ruling B; plan round 2's finding that a frozen slice can stall PID 1 without bound (instance control dying with the slice frozen, unfence dropping the reaper, absent slice or missing freezer giving no barrier); fallback A per the agent manager's pre-agreed rule.
-- [ ] **Step 2: Fence spec §9.** One short paragraph each for Spec corrections 2 to 13 and ruling B (the freeze replaces §3.2 step 3; identity; fail closed and its bound; the system-manager stall and the reaper), in the spec's voice. Do not edit §1 to §8.
+- [ ] **Step 2: Rewrite §3.1's trip paragraph** for the event, the gate and the coverage reader (Spec corrections 4 to 8, residuals 10). **Rewrite §3.2** for A: the watcher attaches at replicator start; on the event it sets the fast path, cancels a waking entry or begins the ordinary `StopLeaseLost` stop; no root kill; the stop's steps and figures. **Rewrite §4's table rows** "Box loses the store, with writes arriving" and "Store outage longer than 30 s": new requests get 503 from the fence line; lost acknowledged writes are those committed from 32 s before the fence line until the requests in flight at the line finish, no later than the ordinary stop ends the processes, 30 s after the fence line in the common case and 110 s at the worst bounded case (a sidecar start and a swap in flight); unacknowledged background writes in that window are discarded at the unclean restore.
-- [ ] **Step 3: Census card.** `make census-card`; write `$TMPDIR/g6-fence-claims.tsv` (`<file>:<unit><TAB><claim>`), matched to the card's unit names. Claims: `handleFence`/`handleUnfence` (new: write `cgroup.freeze` and `cgroup.kill` and read `cgroup.events` of `SliceControlGroup(host)` under `CgroupRoot`, cgroup2-checked, for a host that passed `ValidHostShape`; the host and generation come from the agent's request; the generation only orders root's own decisions); fence records (new: root reads and writes JSON under `FenceDir`, a root-only 0700 directory on `/run`, keyed by `InstanceID(host)`; no agent-writable path); `resumeFences` (new: reads those records and the `cgroup.freeze` of slices under `carlos-instances.slice`); the reaper (new: inotify on the slice's `cgroup.events`); `refuseFenced`, `handleStart`, `handleSeed`, `startOneShot`, `restartRunning` (add refusals and a skip only); lease, activator and root-package units (agent-side, no root read added; `runRouteReplication` adds a refusal only).
+- [ ] **Step 3: §5 tests and exit test.** Replace the activator kill tests with Task 3's list. Drill 4 pass criteria change: `K` is the fence line to every main process of the fixture dead, through the ordinary stop; pass when `K` is **under 35 s** (the common-case stop bound of 30 s, plus 5 s margin; the drill keeps swaps and sidecar starts out of the window, and records any it finds, judged then against 110 s + 5 s). The lost-acknowledged-write limit stays **at most 36**: acknowledged writes come only from requests admitted before the fence line, so about 32 s of writes at the fixture's one a second plus the requests in flight at the line (two entries, so up to 2), plus 2 margin. All acknowledged and lost writes were committed between 32 s before the fence line and the writers-dead line. The rest of the exit test stays.
-- [ ] **Step 4: Propose and check.** `make census-propose NAME=g6-fence CLAIMS=$TMPDIR/g6-fence-claims.tsv`; `go test ./internal/provision/ -run 'TestPlan14RootReadCensus|TestCensusScopeIsTheRootBinary' -count=1` → PASS. Delete the claims file.
+- [ ] **Step 4: RHA §5.5.** Add exactly: "On an HA box, a stream instance whose replication has fallen more than 30 seconds behind its local writes refuses new requests at once and stops through its ordinary stop, releasing unclean. A storage outage then loses the writes acknowledged in about the last 32 seconds before that, plus those of requests already running; the stop ends its processes within 30 seconds, or within two minutes when a deploy or a sidecar start is under way. An instance with nothing unsynced is not affected."
-- [ ] **Step 5: Commit.** `git commit -m "G6 fence: RHA 5.5 sentence, build notes, census card"`
+- [ ] **Step 5: Census card.** `make census-card`; write `$TMPDIR/g6-fence-claims.tsv` (`<file>:<unit><TAB><claim>`) matched to the card's unit names. Scope: `internal/lease` and `internal/activator` units (agent-side code compiled into the root binary; no root read added; the fence reads the instance's own `-wal` and litestream's local LTX files, as litestream already does) and `cli.go` `runRouteReplication` (adds a refusal only). `make census-propose NAME=g6-fence CLAIMS=$TMPDIR/g6-fence-claims.tsv`; `go test ./internal/provision/ -run 'TestPlan14RootReadCensus|TestCensusScopeIsTheRootBinary' -count=1` → PASS. Delete the claims file.
+
+- [ ] **Step 6: Commit.** `git commit -m "G6 fence: spec rev 4 (fallback A), RHA 5.5, census card"`
---
-### Task 7: Wire the approved copy (waits on Paul's review)
+### Task 6: Wire the approved copy (waits on Paul's review)
+
+Unchanged.
**Corrections for this task (read first):**
- Start only when `result.json` exists at `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-g6/copy-review/result.json` with an approved entry for `cli.route.replication_ha_refusal`. Read it; never copy from the spec or `strings.json`.
@@ -394,10 +310,10 @@ Reaper: while the record says `Fenced`, on every `Watch` signal or 100 ms tick,
**Files:** Modify `cli.go`; create `approved_g6_fence_copy_test.go`; regenerate the census overlay and card.
-- [ ] **Step 1: Failing tests.** `TestG6FenceRefusalCopyIsApproved` (the constant equals the approved text, pinned literally; one `%s`; no `COPY-PENDING`, no em dash). `TestG6FenceNoPendingCopy` (no non-test root-package `.go` file contains `COPY-PENDING:cli.route.replication_ha_refusal`).
+- [ ] **Step 1: Failing tests.** `TestG6FenceRefusalCopyIsApproved` (the constant equals the approved text, pinned literally; one `%s`; no `COPY-PENDING`, no em dash); `TestG6FenceNoPendingCopy` (no non-test root-package `.go` file contains `COPY-PENDING:cli.route.replication_ha_refusal`).
- [ ] **Step 2: Run to see them fail.** `go test . -run 'TestG6Fence' -count=1`.
- [ ] **Step 3: Set the constant.**
-- [ ] **Step 4: Run to see them pass**, with Task 5's tests.
+- [ ] **Step 4: Run to see them pass**, with Task 4's tests.
- [ ] **Step 5: Re-propose the census** (same NAME and claims) and run the two census tests.
- [ ] **Step 6: Commit.** `git commit -m "route: approved copy for the HA replication refusal"`
@@ -405,15 +321,13 @@ Reaper: while the record says `Fenced`, on every `Watch` signal or 100 ms tick,
## After merge (not plan tasks)
-**Dev drill 4 rerun (the exit test; needs a #421 window and 8a3d302's GO).** `~/.cache/region-ha-next/G2-CARD.md` drill 4, the fault harness with its 35-minute expiry timer, on the dev IE group, pool `hapair`, fixture `g2-stream` written about once a second through both entries:
+**Dev drill 4 rerun (the exit test; needs a #421 window and 8a3d302's GO).** `~/.cache/region-ha-next/G2-CARD.md` drill 4, the fault harness with its 35-minute expiry timer, on the dev IE group, pool `hapair`, fixture `g2-stream` written about once a second through both entries, with no deploy or sidecar start in the window:
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 started after it gets 503 with `Retry-After: 10`, with no hangs; acknowledged and lost writes (probe acks against `/ranges`) were all committed between 32 s before the fence line and the writers-dead line, and number at most 36 (was 131); `K` (fence line to writers dead) is under 2 s; slice-empty is recorded; 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.
+2. **Pass:** the fence line appears between t0+30 s and t0+35 s; from it every 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 32 s before the fence line and the writers-dead line, and number at most 36 (was 131); `K` (fence line to every main process dead, through the ordinary stop: systemd's `Main process exited` lines) is under 35 s; slice-empty is recorded; after the fault ends the unclean marker lands and the fixture serves again within the bound of RHA §9.8 (read with the wait below); 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).
-Also record in the same window: root's `froze and killed` and `empty after` lines, `Frozen: true`; how long `systemctl is-system-running` / `systemctl show carlos-edge.service` take on the holder from the fence line until the slice stays empty (the system-manager stall, Spec corrections 12; anything over 1 s is reported, not waved through); that the unfence at the next acquire on that box thaws (`thawed` line) and the fixture starts.
-
**Flagship check (§3.3).** On a member, `carlos routes` shows the class of every pool `ha` route; expect none `batched` or `daily`.
-**With branch `ha-unclean-marker-waits`.** A fence always ends in an unclean marker (`finishErr` carries the renewer's error, `release.go:254`; the gate makes the final sync fail while the store is down), and at the event the renewer stops renewing when it latches (`health.go:193-214`), so the lock keeps its last renewal's expiry: about 9.4 to 15 minutes after the fence line. Today any marker is taken at once (`hafresh/acquire.go:87-89`). Once that branch lands, recovery after a fence is the later of the store's return (the owed marker lands) and that expiry, or 15 minutes after the marker lands if its rule counts from the marker's write. Requests get 503 with `Retry-After: 10` throughout. §4's "comes back without a terminate" still holds, later. The fenced slice stays frozen on the fenced box until a later acquire there unfences it with a higher generation; acquires elsewhere are unaffected. Shared files: `internal/lease/release.go` (two lines in `finalize` here; the comment above it there) and the region HA spec (§5.5 here; takeover time there). No test here asserts an immediate take of an unclean marker.
+**With branch `ha-unclean-marker-waits`.** A fence always ends in an unclean marker (`finishErr` carries the renewer's error, `release.go:254`; the gate makes the final sync fail while the store is down). At the event the renewer stops renewing if it latches (`health.go:193-214`), so the lock keeps its last renewal's expiry: about 9.4 to 15 minutes after the fence line. Today any marker is taken at once (`hafresh/acquire.go:87-89`). Once that branch lands, recovery after a fence is the later of the store's return (the owed marker lands) and that expiry, or 15 minutes after the marker lands if its rule counts from the marker's write. Requests get 503 with `Retry-After: 10` throughout. §4's "comes back without a terminate" still holds, later. Shared files: `internal/lease/release.go` (two lines in `finalize` here; the comment above it there) and the region HA spec (§5.5 here; takeover time there). No test here asserts an immediate take of an unclean marker.
-**Rollout.** Rides the next release (dev first, then flagship). Root's `/fence`/`/unfence` and their caller ship in one binary. A box running the old agent sends no fence and no unfence; a new root with no record never refuses an old agent's starts.
+**Rollout.** Rides the next release (dev first, then flagship). Agent-side only; no root or unit change.