plan: G6 write fence rev 2, ruling B after Astra round 1
Freeze then kill in the kernel, generation-ordered unfence, fence event independent of the renewer, watcher at replicator start, initial obligation, coverage reader and CLI test fixes. Records the live cgroup v2 check and the frozen-spawn stall seen on systemd 257.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/superpowers/plans/2026-11-12-g6-write-fence.md+225 −299
CI cancelled — superseded by a newer push — run details
Intent
<paseo-system version="1" kind="agent-message" source-agent-id="8a3d302a-eac7-407c-b61c-f5ccc66b5544" message-id="ba2a04a2-4c47-4376-9885-80ae6c4eaa47"> Agent manager 8a3d302: B. Writer cessation enforced once, in the kernel (cgroup.freeze then cgroup.kill on the host slice), thaw only on an unfence carrying the new acquisition's identity after the fence call finished; plus the two lease-side fixes and the watcher attached at replicator start. It keeps the ~35 s promise Paul accepted and removes the race family by construction, which is the right kind of fix (memory refuse-up-front-over-tolerating). Check first that every target box runs cgroup v2 with the freezer (dev and flagship, fixed boxes and group members) and say so in the plan. One more Astra round (2 of 3). If it finds a P1 in the same family, don't do a third fix: fall back to A (latch + lease-lost stop, bound about a minute, stated in the copy) and tell me. Keep the pool path going. </paseo-system>
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 19564d73b..45bd716df 100644 |
| --- a/docs/superpowers/plans/2026-11-12-g6-write-fence.md |
| +++ b/docs/superpowers/plans/2026-11-12-g6-write-fence.md |
| @@ -1,39 +1,47 @@ |
| -# G6 Write Fence (F-C) Implementation Plan |
| +# G6 Write Fence (F-C) Implementation Plan (rev 2, ruling B) |
| > **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 every process of its host slice SIGKILLed by root, refuses every new start in that slice until its next lease acquire, and releases unclean. |
| +**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. |
| -**Architecture:** `internal/lease` runs a 1 s fence goroutine per HA stream replicator. It keeps an obligation queue (oldest unreplicated WAL change, resolved only when the replica position proves it stored), latches `ErrReplicaStale` on the renewer at the 30 s limit, and closes a gate on the replica client that cancels and refuses every replica call except the one finalization's. `internal/activator` watches each HA stream entry's replicator: on the fence it begins the ordinary lease-loss stop (if still awake) and asks root to fence the host. `internal/instancectl` adds `POST /fence` (mark the host, SIGKILL its slice, wait for in-flight starts, kill again, wait for the slice to empty) and `POST /unfence` (cleared by the agent at the host's next HA acquire); every `systemctl start` in a host slice goes through one checked wrapper. `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), 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. |
| -**Tech Stack:** Go; litestream v0.5.14 (embedded); `github.com/superfly/ltx` v0.5.1; systemd 257 (Debian 13 boxes). |
| +**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`. |
| -**Spec:** `docs/superpowers/specs/2026-11-11-g6-write-fence-design.md` rev 3.1 (Paul approved the build 2026-11-12, option 1; Fable spot check READY AFTER FIXES, all applied). Findings it answers: `docs/superpowers/reviews/CODEX-FINDINGS-G6-R1.md` (G6-1.1 to 1.5), `CODEX-FINDINGS-G6-R2.md` (G6-2.1 to 2.4), `FABLE-SPOTCHECK-G6-FENCE.md` (F1 to F7). `§n` below 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 (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`. |
| -**Review history:** none yet. One Astra plan review round is planned (stopping rules: stop at the first round with no P1; apply its P2s without reopening). The fence families (outstanding-write age, writer cessation, release cancellation) already drew findings in two spec rounds: a plan finding in the same family is offered to Paul under stopping rule 2, not fixed a third time. |
| +**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 corrections (verified against this tree, 3d332f24) |
| +**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). |
| -1. **Line drift.** The spec cites `origin/main` 01d6ca78. Here: `servingError` is `internal/activator/stateless.go:258`; `Replicator.Err` `internal/lease/lease.go:563`, `Lost` `:569`; `finishErr` `release.go:254` (unchanged); HA stream's 1 s monitor `activator.go:3386-3388`; `beginStopLocked` `activator.go:3478-3515`; the proxy runs at `activator.go:6622`/`:6641`; `KillHost` `genbackend.go:684-717`; `SliceName` is `internal/instancectl/names.go:166` (`gen.go:65-72` is the drop-in's `Slice=` line); `hostSliceEmpty` `harelease.go:50-72`; the stop's waits are `activator.go:4904-4925` (sidecar start-done, with the `a.joinWaiting` test hook), `:4934` (`joinOps`), `:5012-5019` (process drain). |
| -2. **`StopFenced` already exists** (`internal/activator/cmd.go:26`): it is the moves/layout fence's member-facing run-interruption text ("stopped for a move or a layout change"), and `a.fences` is the moves fence. The write fence stops with **`StopLeaseLost`**, which is what §3.1 means by "every existing consumer treats the fence exactly as a lost lease" (`haleaseloss.go:100-101`, `rootfs_service.go:1139`). The activator flag is `e.writeFenced`, not `e.fenced`. |
| -3. **`/start` has no single per-host lock.** Starts take `legacyMu` (run), `genMu` (generations), `rootfsLocks`, the one-shot locks or none (seed). The root mark lives under a new `fenceMu`, and every host-slice `systemctl start` goes through one wrapper (`startInSlice`) that checks it, counts the start in flight, and is pinned by an AST guard test. The three start handlers also refuse a marked host at entry. |
| -4. **`Replica.MonitorEnabled = false` and `Replica.Stop(true)` are not safe from the fence goroutine.** `Replica.Start` reads `MonitorEnabled` and writes `r.cancel` (`replica.go:94-110`) inside `DB.init`, under `db.mu`, which init holds while it calls the store (`checkDatabaseBehindReplica`, `db.go:1406-1446`, from `newSyncExecutor`, `db.go:1739-1746`). The platform cannot take `db.mu`, so both writes race the very case F6 is about. Replaced by a **gate on the replica client** (Task 2): at the latch it cancels every in-flight replica call and refuses every later one, except calls made inside the one finalization (a context tag set by `finalize`). Effect: the hung upload returns and frees `syncMu` (G6-1.3, G6-2.3); a monitor a late `DB.init` restarts cannot hang (F6); `DB.Close` inside `finalize` still stops and joins the monitor itself (`db.go:791`). Stricter than F5: compaction and snapshot uploads after the latch are refused, not merely kept before the marker. |
| -5. **The newest L0 LTX header carries the WAL range and salts** (`ltx` v0.5.1 `Header.WALOffset`, `WALSize`, `WALSalt1`, `WALSalt2`, `ltx.go:188-191`; litestream itself reads them, `db.go:1510-1525`). **A size-only comparison is wrong**: SQLite restarts the WAL from offset 32 without truncating it after litestream's PASSIVE checkpoints (1000 pages, every minute: `db.go:32-35`, `:1290-1335`), so the file stays longer than the captured range. Resolution uses the salts and the frame header at the captured end (`walCovered`, Task 1), and runs on any run with unresolved obligations, not only a same-run capture; that also resolves a WAL created empty, or truncated by a TRUNCATE/RESTART checkpoint, with no commit. |
| -6. **A missing `-wal` file is a state, not a failed `stat`.** Read literally, §3.1 fences every HA stream instance that has no database (or has not opened one yet) 30 s after it wakes. Only a `stat` error other than "not exist" counts as a change. |
| -7. **`DB.Pos` is not memory only**: on a cache miss after each capture it reads the L0 directory and opens and verifies the newest LTX file (`db.go:559-590`). Still local, no S3 request. |
| -8. **Residuals the build states in code comments and the spec** (Task 6): (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, the cross-run analogue of F2; needs a capture to span a 1 s sample instant); (b) a rolled-back transaction that spilled frames into the WAL, then idleness, fences spuriously; (c) a wake whose first replica sync cannot reach the store within 30 s is fenced even with no writes (the stored position is unknown); (d) instance control keeps marks in memory: a restart of `carlos-instance-control` clears them (its in-flight starts die with it; `e.writeFenced` still refuses the agent's own spawns). |
| -9. **§5 files the same-run witness under `internal/activator`**; it is a lease test (Tasks 1 and 2). |
| -10. **§5's lease test "the next acquire restores and sets the local copy aside"** is not asserted in `internal/lease`: branch `ha-unclean-marker-waits` makes that acquire wait for the old lease's expiry, so an immediate-take assertion would break when both land. Restore and set-aside after an unclean marker are already pinned by `TestRestoreHARestoresOnEveryOtherReason` (`hawake_test.go:418`). |
| -11. **`systemctl kill --signal=SIGKILL <slice>` works on a slice**: checked on systemd 257 (the boxes run `debian-13-arm64-*`, `infra/modules/region-host/variables.tf:158`) with two units in a user-manager slice; both died, exit `failed`. |
| +## 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. |
| +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`. |
| ## 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.) |
| -- Fence values, verbatim from the spec: check every **1 s**; trip when the queue is non-empty and `now - t_oldest > 30 s`; bound: the oldest lost write is at most **32 s** old at the fence line; drill `K` (fence line to writers dead) **under 2 s**; drill loss **at most 36**. The 30 s and 1 s are constants with a test seam, not settings. |
| -- Journal line, exact (not copy-gated): `lease: <path>: a write has waited <age> to reach storage (local <L>, stored <R>); standing down (write fence)`. |
| -- COPY: no user- or operator-facing string goes into code or docs until Paul approves it. The review is OPEN; this plan's one string is `cli.route.replication_ha_refusal`. Task 5 uses a constant holding `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). Log lines are not copy-gated. 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. Socket-binding packages (`internal/activator`, `internal/instancectl`, `internal/lease`, whose 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 (`internal/lease`, `internal/activator`, `internal/instancectl`, the root package): `GOOS=darwin go build . && GOOS=windows go build .`. |
| +- 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). |
| - 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. |
| @@ -42,20 +50,21 @@ |
| ## Review Focus |
| -1. **An HA stream instance with no database, or one that opens an empty WAL and never writes.** Never fenced. (Task 1 `TestFenceQueueMissingWALIsAState`; Task 2 `TestWriteFenceNoDatabaseNeverTrips`.) |
| -2. **A WAL restarted after a checkpoint (file length unchanged, new salts), one write, then idle, with the store healthy.** Never fenced: the same-run obligation resolves through the salts. (Task 1 `TestWalCovered`; Task 2 `TestWriteFenceCheckpointRestartThenIdle`.) |
| -3. **A store outage shorter than 30 s with writes arriving.** No fence; replication catches up. (Task 1 `TestFenceQueueOutageUnder30s`; Task 2 `TestWriteFenceShortOutageNoTrip`.) |
| -4. **A fenced host woken again on the same box after the store returns.** Every start is refused until the new HA acquire clears the mark, then starts run. (Task 3 `TestUnfenceClearsTheMark`; Task 4 `TestHAAcquireClearsTheFenceMark`.) |
| -5. **An operator sets `--replication stream` or `""` on an HA route, or `batched` on a non-HA route.** Allowed; only `batched` and `daily` on an HA route are refused. (Task 5 `TestReplicationHARail`.) |
| +1. **An HA stream instance with no database, or with 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.) |
| --- |
| ### Task 1: The obligation queue (internal/lease, pure) |
| **Corrections for this task (read first):** |
| -- A missing WAL is `walState{exists: false}`, a value like any other; only a `stat` error that is not `os.ErrNotExist` sets `statErr` (Spec corrections 6). |
| -- Resolution by `covered` (rule C below) runs on any run with unknown obligations, not only a same-run capture (Spec corrections 5). Do not compare file size alone. |
| -- An obligation's TXID 0 is a real, resolved value (an empty WAL resolves to `L`, which may be 0). Keep `known` separate from `txid`. |
| +- 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. |
| **Files:** |
| - Create: `internal/lease/fence.go` |
| @@ -63,50 +72,41 @@ |
| **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`; does not wrap it) |
| + - `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 }` (`L` = `DB.Pos().TXID`, `lOK` false when `Pos` failed; `R` = `Replica.Pos().TXID`) |
| + - `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)`; `func (q *fenceQueue) positions() (l, r uint64)`; `func (q *fenceQueue) anyUnknown() 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** in `fence_queue_test.go`. A helper `run(q, t0, k, sample, covered)` calls `q.step(t0.Add(k*time.Second), ...)`. Every scenario starts with a baseline sample at `k=0`. Writes are modelled as a `W` change (`size` or `mod` differs from the previous sample). Assertions (spec values): |
| - - `TestFenceQueueFailingUploadTrips`: baseline `L=R=1`; for `k>=1` W changes, `L=1+k`, `covered` returns `(L, true)`, `R` stays 1. `step` is false for `k<=31` and true at `k==32` (first obligation at `t=1`; trips when `now-1 > 30`). |
| - - `TestFenceQueueNoWritesNeverTrips`: `L=R=5`, W constant, 300 runs, never true. |
| - - `TestFenceQueueSlowThenHung` (G6-1.2): baseline `L=R=1`; for `k>=1` W changes, `L=1+k`, `covered` returns false. `R=1` until `k=29`, then `R=3` (the TXID rule A gave the `t=1` obligation at `k=2`) and stays 3. False through `k=32`, true at `k==33`. (Without rule A it would trip at 32; with `LastSuccessfulSyncAt` semantics near 59.) |
| - - `TestFenceQueueContinuousWritesCaptureBlocked` (G6-2.1): `L=R=5` throughout; W changes every run from `k=1`; `covered` false. True first at `k==32`; later writes do not move it. |
| - - `TestFenceQueueDelayedCaptureThenHungUpload` (G6-2.1): `L=R=5`; W changes at `k=1` only; `L` becomes 6 at `k=29` (`covered` false before 29, `(6,true)` from 29); `R` stays 5. True first at `k==32`. |
| - - `TestFenceQueueSameRunWrite` (Fable F2): `L=R=5`; at `k=1` W changes and `L=6` in the same run; `covered` false; `R=6` from `k=2`; nothing changes after. True first at `k==32`. Variant `covered` returns `(6,true)` at `k=1`: never true through `k=120`. |
| - - `TestFenceQueueFailedStatIsAChange`: `L=R=5`; `statErr` non-nil every run from `k=1` (`covered` must not be called on a run whose `statErr` is set: the test's `covered` fails the test if called). True first at `k==32`. |
| - - `TestFenceQueueMissingWALIsAState`: W `{exists:false}` on every run, `L=R=0`, 120 runs never true. Variant: `exists` true at baseline, false 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. |
| - - `TestFenceQueueOutageUnder30s`: `L` advances and W changes every run, `covered` `(L,true)`; `R` frozen at its `k=0` value for `k=1..20`, then `R=L` each run: never true through `k=120`. |
| - - `TestWalCovered` (table; WAL header salts at bytes 16..23 big-endian, frame header salts at bytes 8..15): |
| - - WAL missing → `(l, true)`; |
| - - `size <= 32` → `(l, true)`; |
| - - frames present, `h == nil` → `false`; |
| - - WAL salts differ from `h.WALSalt1/2` → `false`; |
| - - `size <= h.WALOffset+h.WALSize` → `(h.MaxTXID, true)`; |
| - - frame at the end carries the WAL's current salts → `false`; |
| - - frame at the end carries other salts (a restarted WAL's stale frame) → `(h.MaxTXID, true)`; |
| - - `frameAtEnd` shorter than 24 bytes → treat as no frame → `(h.MaxTXID, true)`. |
| - |
| -- [ ] **Step 2: Run to see them fail** |
| - |
| -Run: `go test ./internal/lease/ -run 'TestFenceQueue|TestWalCovered' -count=1` |
| -Expected: FAIL (undefined: fenceQueue, walCovered). |
| - |
| -- [ ] **Step 3: Implement `fence.go`**. `step` is the one algorithm the tests do not pin in full; write it in this order: |
| +- [ ] **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`. |
| + - `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`. |
| + - `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`. |
| + - `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)`. |
| + |
| +- [ ] **Step 2: Run to see them fail.** `go test ./internal/lease/ -run 'TestFenceQueue|TestWalCovered' -count=1` → FAIL (undefined). |
| + |
| +- [ ] **Step 3: Implement `fence.go`.** `step`, in this order: |
| ```go |
| func (q *fenceQueue) step(now time.Time, s fenceSample, covered func() (uint64, bool)) bool { |
| if s.R > q.r { // a failed sync zeroes Replica.Pos; keep the highest seen |
| q.r = s.R |
| } |
| - changed := s.statErr != nil || (q.haveW && s.W != q.w) // first sample is a baseline |
| + first := !q.haveW && s.statErr == nil |
| + changed := s.statErr != nil || (q.haveW && s.W != q.w) |
| if s.statErr == nil { |
| q.w, q.haveW = s.W, true |
| } |
| @@ -119,7 +119,7 @@ func (q *fenceQueue) step(now time.Time, s fenceSample, covered func() (uint64, |
| } |
| q.l = s.L |
| } |
| - if changed { |
| + if changed || (first && s.W.exists && s.W.size > walHeaderSize) { // P1-1: frames at the first look are unproven |
| q.ob = append(q.ob, fenceObligation{t: now}) |
| } |
| if s.statErr == nil && q.anyUnknown() { // rule C: the WAL as it is now is all captured |
| @@ -134,344 +134,272 @@ func (q *fenceQueue) step(now time.Time, s fenceSample, covered func() (uint64, |
| for len(q.ob) > 0 && q.ob[0].known && q.r >= q.ob[0].txid { |
| q.ob = q.ob[1:] |
| } |
| - if len(q.ob) == 0 && q.l > q.r { // captured before the first sample, or after the queue emptied |
| + if len(q.ob) == 0 && q.l > q.r { // captured, not yet stored |
| q.ob = append(q.ob, fenceObligation{t: now, txid: q.l, known: true}) |
| } |
| return len(q.ob) > 0 && now.Sub(q.ob[0].t) > fenceLimit |
| } |
| ``` |
| -`walCovered` implements the table above (WAL missing or `size <= 32`: no frames). Comment the residuals (a) and (b) of Spec corrections 8 on rule A and rule C. The queue is bounded: each run appends at most one obligation and the goroutine exits at the trip (about 32 entries). |
| +`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. |
| -- [ ] **Step 4: Run to see them pass** |
| +- [ ] **Step 4: Run to see them pass** (same command). |
| -Run: `go test ./internal/lease/ -run 'TestFenceQueue|TestWalCovered' -count=1` |
| -Expected: PASS. |
| +- [ ] **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 5: Mutation checks** (revert each): drop rule A → `TestFenceQueueSlowThenHung` fails (trips at 32); drop rule C → the `TestFenceQueueSameRunWrite` covered variant fails; `>` to `>=` on the limit → `TestFenceQueueFailingUploadTrips` fails at 31; treat a missing WAL as a stat error → `TestFenceQueueMissingWALIsAState` fails. |
| - |
| -- [ ] **Step 6: Commit** |
| - |
| -```bash |
| -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 add internal/lease/fence.go internal/lease/fence_queue_test.go && git commit -m "lease: write fence obligation queue (G6 F-C)"` |
| --- |
| -### Task 2: The fence on the replicator (lease wiring, gate, release) |
| +### Task 2: The fence event on the replicator (lease wiring, gate, release) |
| **Corrections for this task (read first):** |
| -- Do **not** write `Replica.MonitorEnabled` or call `Replica.Stop` from the fence goroutine (Spec corrections 4). The gate is the mechanism. |
| -- `Done()` closes at the **end** of `finalize` (and in non-HA `Close`/`Abandon`), never at its start: the fence must keep running while an ordinary `finalize` is blocked in `SyncAndWait`, or G6-2.3 cannot be met. |
| -- `finalize` must never join the fence goroutine (F7). The fence goroutine holds none of `rn.mu`, `finMu`, `syncMu` while it waits. |
| -- Arm only in `Held.Replicate` when `h.ha && syncInterval == 0`. Install the gate on `db.Replica.Client` after `newStore` and **before** `store.Open` (`DB.Open` copies the client into the compactor, `db.go:735-737`). Do not change `newStore`'s signature (`Held.Checkpoint` and tests call it). |
| -- `internal/lease/release.go` is also edited by branch `ha-unclean-marker-waits` (the comment above `finalize`, `:217-224`). Keep this task's edits to `finalize` to two lines (the context tag and the deferred `closeDone`). |
| -- The lease test must not assert that the next acquire takes the unclean marker at once (Spec corrections 10). |
| +- **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. |
| +- 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)`. |
| +- `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). |
| **Files:** |
| -- Create: `internal/lease/fencerun.go` (sampler, goroutine, trip, `renewer` latch helper) |
| -- Create: `internal/lease/fencegate.go` (gate, finalization tag) |
| -- Modify: `internal/lease/lease.go` (`Replicator` fields, `Replicate`, `Close`, `Abandon`, `Done`, `FenceArmed`) |
| -- Modify: `internal/lease/release.go:225-261` (`finalize`) |
| -- Modify: `internal/lease/export_test.go` (seams) |
| -- Test: `internal/lease/fence_test.go` (`package lease_test`), `internal/lease/fencegate_test.go` (`package lease`) |
| +- 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`) |
| **Interfaces:** |
| -- Consumes: Task 1's `fenceQueue`, `fenceSample`, `walState`, `walCovered`, `ErrReplicaStale`, `fenceTick`, `fenceLimit`. |
| +- Consumes: Task 1. |
| - Produces (used by Task 4): |
| - - `func (r *Replicator) Done() <-chan struct{}` (closed once the replicator is finalized or abandoned, every replicator kind) |
| - - `func (r *Replicator) FenceArmed() bool` (true only for an HA lease replicated at sync interval 0) |
| - - `lease.ErrReplicaStale` latched on the renewer: `r.Err()` returns it, `r.Lost()` closes. |
| -- Internal: |
| - - `type fenceGate struct{ inner litestream.ReplicaClient; ctx context.Context; cancel context.CancelFunc }` implementing `litestream.ReplicaClient`; `func newFenceGate(c litestream.ReplicaClient) *fenceGate`; `func (g *fenceGate) close()` |
| - - `func withFinalization(ctx context.Context) context.Context`; `func finalizing(ctx context.Context) bool` |
| - - `func (r *Replicator) runFence(walPath string, ticks <-chan time.Time, stop func(), sampled chan<- bool)` |
| - - `func (r *Replicator) fenceSample(walPath string) fenceSample`; `func (r *Replicator) fenceCovered(walPath string, w walState, l uint64) (uint64, bool)` |
| - - `func (rn *renewer) latchFence() bool` (under `rn.mu`: if `rn.err == nil && !rn.stopped`, `loseLocked(ErrReplicaStale)`; reports whether it latched) |
| -- Test seams in `export_test.go`: |
| - - `func SetFenceTicksForTest(ticks <-chan time.Time, sampled chan<- bool) (restore func())` (the goroutine uses the received tick value as `now`, and after each sample sends whether it tripped on `sampled` when non-nil). Production: a `time.Ticker` at `fenceTick`, `sampled` nil. |
| - - `func CaptureForTest(r *Replicator) error { return r.db.Sync(context.Background()) }` |
| - - `func CheckpointForTest(r *Replicator, mode string) error { return r.db.Checkpoint(context.Background(), mode) }` |
| - |
| -- [ ] **Step 1: Write the failing tests.** Helper `fencedReplicator(t, fx, client) (r *lease.Replicator, dbPath string, step func(k int) bool)`: `haHeld` (release_test.go), `lease.SetReplicaClientForTest(h, client)`, `h.SetMonitorInterval(time.Hour)` (captures happen only through `CaptureForTest`), unbuffered `ticks` and `sampled`, `t.Cleanup(lease.SetFenceTicksForTest(ticks, sampled))`, `h.Replicate(ctx, tempDB(t), 0)`. `step(k)` sends `t0+k s` and returns the receive from `sampled`; once a trip is seen, later steps must not be sent (the goroutine has exited). Clients: `lsfile.NewReplicaClient(t.TempDir())` (healthy); `failingReplica` (every `WriteLTXFile` returns an error while `down` is set); `hangingReplica` (an untagged `WriteLTXFile` signals `entered` and blocks until its context ends; any call returns an error while `down` is set; records `"replica write"` events like `recordingReplica`). |
| - - `TestWriteFenceArmedOnlyForHAStream`: HA + 0 → `FenceArmed()` true; HA + `5*time.Minute` and HA + `24*time.Hour` → false; a legacy `lease.AcquireTTL` handle replicated at 0 → false. |
| - - `TestWriteFenceTripsWithFailingUploads`: `failingReplica` down; baseline `step(0)` before any write (nothing captured yet: `L=R=0`); each `k>=1`: `addRows(t, dbPath, 1)`, `CaptureForTest`, `step(k)`. `step` is false through `k=31` and true at `k=32` (first obligation at step 1). Then `errors.Is(r.Err(), lease.ErrReplicaStale)`, `!errors.Is(r.Err(), lease.ErrLost)`, `r.Lost()` closed; 2 s later `r.Err()` is still `ErrReplicaStale` (the latch is permanent). |
| - - `TestWriteFenceIdleNeverTrips`: healthy client, no writes, 120 steps, all false, `r.Err() == nil`. |
| - - `TestWriteFenceNoDatabaseNeverTrips` (Review Focus 1): `Replicate` over a path with no database file; 60 steps false. Variant: the database exists in WAL mode with no writes after `Replicate`: 60 steps false. |
| - - `TestWriteFenceCheckpointRestartThenIdle` (Review Focus 2): healthy client; `addRows(50)`, `r.SyncAndWait`, `CheckpointForTest(r, litestream.CheckpointModeRestart)`, then in one step interval `addRows(1)` and `CaptureForTest` and `r.SyncAndWait`; read the WAL header salts before and after and assert they changed while the WAL file length did not shrink (the restart case; if they did not change, the case was not reached: report it, do not weaken the assertion); 60 further steps all false. |
| - - `TestWriteFenceShortOutageNoTrip` (Review Focus 3): `failingReplica` down for steps 1-20 with a write and capture each step; up from step 21 with `r.SyncAndWait` each step; steps through 80 all false. |
| - - `TestWriteFenceUnblocksAReleaseAlreadyWaiting` (G6-1.3, G6-2.3): `hangingReplica`; `addRows(5)`, `CaptureForTest`; wait for `entered` (the replica monitor's upload holds `syncMu`; its context is `db.ctx`, which nothing cancels before `DB.Close`); baseline `step(0)` (the empty-queue rule records the captured, unstored TXID); `lease.SetFinalSyncHookForTest` signals when `finalize` starts; `fx.FailNextMatching("PUT", 503, isMarkerBody)`; set `down`; `go r.ReleaseMarker(ctxWith5sBudget, hafresh.Marker{V: 1, Clean: true})`; after the hook fires, assert it has not returned within 200 ms; drive steps 1 to 31 (trip at 31). Assert `ReleaseMarker` returns within 8 s of the call (its 5 s budget: `DB.Close` retries the final sync until the budget ends, `db.go:826-866`) with an `*lease.ObligationError`; `len(lease.PendingObligations()) == 1`; `r.Done()` closed; no `"replica write"` event after the marker attempt (record it with `fx.AfterWrite`); the finalization's own sync reached the client once (a tagged call). Without the gate the release hangs past 8 s. Clear `down`; `lease.RetryPending(ctx)` returns nil; `lockView` shows `Release.Clean == false` and `Release.TXID` equal to the replica position the finalization recorded. |
| - - `TestWriteFenceEndsWithTheReplicator`: healthy client; `r.Close(ctx)`; `r.Done()` closed; a further tick is not received within 500 ms (`select` with timeout on the send). |
| - - `TestFenceGateRefusesAndCancels` (`package lease`): over a fake inner client: before `close`, untagged and tagged calls pass; an untagged call blocked in the inner client returns within 100 ms of `close` with a context error; after `close`, an untagged `WriteLTXFile`, `LTXFiles`, `OpenLTXFile`, `DeleteLTXFiles`, `DeleteAll` and `Init` return `ErrReplicaStale` without reaching the inner client; a call with `withFinalization(ctx)` still reaches it. A reader from `OpenLTXFile` and an iterator from `LTXFiles` release their cancel registration on `Close` (`context.AfterFunc`'s `stop` returns true). |
| - |
| -- [ ] **Step 2: Run to see them fail** |
| - |
| -Run (sandbox off): `TMPDIR=$(mktemp -d /tmp/g/fence2.XXXX) go test ./internal/lease/ -run 'TestWriteFence|TestFenceGate' -count=1` |
| -Expected: FAIL (undefined: Done, FenceArmed, SetFenceTicksForTest). |
| + - `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. |
| +- 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`). |
| + - `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. |
| + - `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. |
| + - `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. |
| + - `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. |
| + |
| +- [ ] **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 calls `admit(ctx)`: a `finalizing(ctx)` call passes unchanged; after `close`, `ErrReplicaStale`; otherwise a child context cancelled by `context.AfterFunc(g.ctx, cancel)`, released when the call returns (for `OpenLTXFile` and `LTXFiles`, when the returned reader or iterator is closed). `Type` and `SetLogger` pass through. |
| - - `lease.go`: `Replicator` gains `gate *fenceGate`, `done chan struct{}`, `doneOnce sync.Once`, `closeDone()`. `Replicate` builds `done` for every replicator; when armed, wraps `db.Replica.Client` in the gate before `store.Open` and, after the handover succeeds, starts `go r.runFence(db.WALPath(), ...)` with the seam's ticks. `Close` and the non-HA `Abandon` call `closeDone()` after `store.Close`. |
| + - `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`. |
| - `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 builds the sample (`r.db.Pos()`, `r.db.Replica.Pos()`, `os.Stat(walPath)` with not-exist as `exists:false`), calls `q.step(tickTime, s, func() (uint64, bool) { return r.fenceCovered(walPath, s.W, s.L) })`, sends on `sampled` if set, and on a trip calls `r.rn.latchFence()`; when it latched, `r.gate.close()` and logs the journal line once (`r.leaser.Path`, age `now - oldest` rounded to the second, `q.positions()`), then returns. `fenceCovered` reads the newest L0 header (`r.db.MaxLTX()`, `os.Open(r.db.LTXPath(0, min, max))`, `ltx.NewDecoder(f).DecodeHeader()`), the WAL's first 32 bytes and the 24 bytes at `h.WALOffset+h.WALSize`, and calls `walCovered`. Any read error answers `(0, false)`. |
| - - Comment the residuals (c) and (d) of Spec corrections 8 where the queue's first sample and the gate are built. |
| + - `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 this wiring can disturb: |
| +- [ ] **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. |
| -Run (sandbox off, same TMPDIR): `go test ./internal/lease/ -run 'TestWriteFence|TestFenceGate|TestFenceQueue|TestWalCovered|TestNoReplicaWriteAfterTheMarker|TestStreamCaptureOneSecond|TestHARelease|TestCleanReleaseMarker|TestEveryFailedHAReleaseIsPersisted|TestFailedMarkerIsAnObligation' -count=1` |
| -Expected: PASS. Remove the TMPDIR you made. |
| +- [ ] **Step 5: Cross-compile.** |
| -- [ ] **Step 5: Cross-compile.** `GOOS=darwin go build . && GOOS=windows go build .` succeeds. |
| +- [ ] **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 6: Mutation checks** (revert each): skip `gate.close()` at the trip → `TestWriteFenceUnblocksAReleaseAlreadyWaiting` times out; close `done` at the start of `finalize` → same test fails (no trip while blocked); drop the finalization tag → the same test's "reached the client once" fails; arm for batched → `TestWriteFenceArmedOnlyForHAStream` fails; treat not-exist as a stat error in the sampler → `TestWriteFenceNoDatabaseNeverTrips` fails. |
| - |
| -- [ ] **Step 7: Commit** |
| - |
| -```bash |
| -git add internal/lease/fencerun.go internal/lease/fencegate.go internal/lease/lease.go internal/lease/release.go internal/lease/export_test.go internal/lease/fence_test.go internal/lease/fencegate_test.go |
| -git commit -m "lease: arm the write fence on HA stream replicators" -m "A 1 s fence latches ErrReplicaStale at 30 s and gates the replica |
| -client so a release already waiting behind a hung upload finishes |
| -unclean within its budget (G6-1.3, G6-2.3, F6)." |
| -``` |
| +- [ ] **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 fences a host (internal/instancectl) |
| +### Task 3: Root freezes and kills a fenced host (internal/instancectl) |
| **Corrections for this task (read first):** |
| -- There is no single per-host `/start` lock (Spec corrections 3). Use a new `fenceMu` and the `startInSlice` wrapper. Never hold `fenceMu` across a `systemctl` call or a wait. |
| -- The kill targets `SliceName(host)` (`names.go:166`), never a unit list and never `cgroup.kill` (a cgroup that took `cgroup.kill` is not spawned into again, `internal/cgroup/recreate_linux.go`; the slice is reused at the next wake). |
| -- `/fence` and `/unfence` are not wrapped in `claimAwareLegacy`: the kill must answer with claims armed too. Claims are shelved and HA never runs under them; `claimunit.go`'s start is allowlisted in the guard with that reason. |
| -- Units are `Restart=no` (`carlos-instance-gen@.service:42`, and every `carlos-instance*@.service`), so systemd does not respawn what the kill ends. |
| +- **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, handlers, `startInSlice`, `refuseFenced`, client methods) |
| -- Modify: `internal/instancectl/server.go` (`Server` gains `fence hostFence`; `Handler()` registers `POST /fence`, `POST /unfence`; `handleStart` and `handleSeed` call `refuseFenced` right after `parseRequest`; `systemctl start` at `:998`, `:1091`, `:1106` via `startInSlice`) |
| -- Modify: `internal/instancectl/cmd.go` (`startOneShot`: `refuseFenced` after `parseRequest`, before the rootfs dispatch; `:119` via `startInSlice`) |
| -- Modify: `internal/instancectl/gen.go:458`, `internal/instancectl/rootfs.go:781`, `:1119` (via `startInSlice`) |
| -- Test: `internal/instancectl/fence_test.go`, `internal/instancectl/fence_guard_test.go` |
| +- 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): |
| - - `var ErrHostFenced = errors.New("instance control: the host is fenced by its write fence; nothing in its slice starts until its next lease acquire")` (journal and HTTP body, not copy) |
| - - `type FenceResponse struct { Slice string `json:"slice"`; Empty bool `json:"empty"` }` |
| + - `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) (FenceResponse, error)` (`POST /fence?host=`), `func (c *Client) Unfence(ctx context.Context, host string) error` (`POST /unfence?host=`, `DeadlineControl`) |
| + - `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 hostFence struct { mu sync.Mutex; marked map[string]bool; starting map[string]int; started map[string]uint64 }` |
| - - `func (s *Server) startInSlice(ctx context.Context, host string, args ...string) (string, error)`: under `mu`, a marked host returns `ErrHostFenced` with no `systemctl` call; otherwise `starting[host]++`; unlock; `s.Systemctl(ctx, append([]string{"start"}, args...)...)`; under `mu`, `starting--`, `started[host]++`. |
| - - `func (s *Server) refuseFenced(w http.ResponseWriter, host string) bool` (409 with `ErrHostFenced`'s text) |
| - - `func (s *Server) handleFence(w http.ResponseWriter, r *http.Request)`, `func (s *Server) handleUnfence(w http.ResponseWriter, r *http.Request)` |
| + - `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`, in order: host by `provision.ValidHostShape` (else 400, nothing called, nothing marked); mark and read `started[host]` under `mu`; log `instance-control: <host>: write fence: marked, killing <slice>`; `systemctl kill --signal=SIGKILL <slice>` (output naming the unit not loaded is success; any other error is 502, mark kept); poll every 20 ms, bounded by the request context, until `starting[host] == 0`; if `started[host]` moved since the mark, kill again; `WaitCgroupEmpty(ctx, s.CgroupRoot, SliceName(host), "", 50*time.Millisecond)`; empty: log `instance-control: <host>: write fence: <slice> empty after <d>` and 200 `{"slice":..., "empty":true}`; not empty by the deadline: 504, mark kept. `handleUnfence`: validate, delete the mark, log, 200. |
| +`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. |
| -- [ ] **Step 1: Write the failing tests** (fake `Systemctl` recording calls; `CgroupRoot` a temp dir with `carlos.slice/carlos-instances.slice/<slice>/cgroup.events`): |
| - - `TestFenceKillsTheHostSliceAndWaitsEmpty`: events `populated 1`; the fake flips it to `populated 0` 100 ms after the kill. `POST /fence?host=shop.example.com` → 200, `Empty` true, `Slice == SliceName("shop.example.com")`; calls are exactly `[kill --signal=SIGKILL carlos-instances-<id>.slice]`. |
| - - `TestFenceAbsentSliceIsEmpty`: no events file; the kill answers an error whose output says the unit is not loaded → 200, `Empty` true. |
| - - `TestFenceRefusesABadHost`: `host=../x` → 400, no calls; a following `/start` for a valid host is not refused by the fence. |
| - - `TestFenceTimesOutWhenTheSliceStaysPopulated`: events stay `populated 1`; request context 300 ms → 504; a following `/start` for that host is 409 with `ErrHostFenced`'s text (mark kept). |
| - - `TestFencedHostRefusesEveryRole` (F1): after `/fence`, each of the seven roles is refused 409 with `ErrHostFenced`'s text and the fake saw no call after the fence's own: `run` (`POST /start?role=run`), `gvisor-run` (`role=run` with `SandboxEffective` gVisor), `seed` (`POST /seed`), `sidecar` (`role=sidecar`), `cmd` (`POST /cmd`), `worker` (`role=worker` with the rootfs runtime fields), `tty` (`POST /tty`), plus the rootfs `cmd` and `tty` shapes. Build each query from the existing tests of that path (`server_test.go`, `rootfs_test.go`, `cmd_test.go`, `gvisorstart_test.go`). |
| - - `TestStartInFlightAtTheMarkIsKilledAgain` (F1): the fake blocks a `start` call until released. Send `/start?role=run`; once the fake has the `start`, send `/fence`; assert `/fence` has not answered after 200 ms; release the start. Call order is `kill <slice>`, `start <unit>` returns, `kill <slice>`; `/fence` answers 200. |
| - - `TestStartInSliceRefusesAfterTheMark`: mark the host, call `s.startInSlice(ctx, host, "x.service")` → `ErrHostFenced`, no call. |
| - - `TestUnfenceClearsTheMark` (Review Focus 4): `/fence`, then `/start` refused; `/unfence` 200; `/start` reaches `systemctl start`. `/unfence?host=../x` → 400. |
| - - `TestClientFenceAndUnfence`: through the package's client test harness (`client_test.go`'s server pattern): `Fence` decodes the response; `Unfence` sends the host; a 409 from a start surfaces as an error containing `ErrHostFenced`'s text. |
| - - `TestEveryHostSliceStartPassesTheFence` (`fence_guard_test.go`, `go/parser` over the package's non-test files): every call whose function is a selector named `Systemctl` and whose second argument is the string literal `"start"` must sit in `startInSlice` or in this allowlist keyed by file and enclosing function, each with its reason: `demo_snapshot_disk.go` (the snapshot mount unit), `demo_snapshot.go` (the snapshot unit, demo boxes only), `gvisorprobe.go` (the probe unit), `gvisorunit.go` (starts the slice unit itself, no process), `rootfs.go` rootfs probe (`RootfsProbeUnit`), `server.go` `RunProbe` (`probeUnit`), `claimunit.go` (claim units: claims shelved, HA never runs under them). Fill the enclosing function names from the tree; a new direct start fails the test with its file and line. |
| +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. |
| -- [ ] **Step 2: Run to see them fail** |
| +`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`. |
| -Run (sandbox off): `TMPDIR=$(mktemp -d /tmp/g/fence3.XXXX) go test ./internal/instancectl/ -run 'TestFence|TestStartInFlight|TestStartInSlice|TestUnfence|TestClientFenceAndUnfence|TestEveryHostSliceStartPassesTheFence' -count=1` |
| -Expected: FAIL. |
| +`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 3: Implement** `fence.go` and the edits above. The seven start sites keep their existing error handling; only the call changes. |
| +- [ ] **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 4: Run to see them pass**, plus the start paths' own suites: |
| +- [ ] **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. |
| -Run (same TMPDIR): the Step 2 command, then `go test ./internal/instancectl/ -run 'TestStart|TestSeed|TestCmd|TestTTY|TestGen|TestRootfs|TestGVisor' -count=1` |
| -Expected: PASS. Remove the TMPDIR. |
| +- [ ] **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 5: Cross-compile.** `GOOS=darwin go build . && GOOS=windows go build .` |
| +- [ ] **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. |
| -- [ ] **Step 6: Mutation checks** (revert each): drop `refuseFenced` from `startOneShot` → `TestFencedHostRefusesEveryRole` cmd/tty rows fail; drop the mark check in `startInSlice` → `TestStartInSliceRefusesAfterTheMark` fails; drop the wait for `starting == 0` or the second kill → `TestStartInFlightAtTheMarkIsKilledAgain` fails; call `Systemctl(ctx, "start", unit)` directly at `gen.go:458` → the guard fails; delete the mark on timeout → `TestFenceTimesOutWhenTheSliceStaysPopulated` fails. |
| +- [ ] **Step 5: Cross-compile.** |
| -- [ ] **Step 7: Commit** |
| +- [ ] **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. |
| -```bash |
| -git add internal/instancectl/fence.go internal/instancectl/fence_test.go internal/instancectl/fence_guard_test.go internal/instancectl/server.go internal/instancectl/cmd.go internal/instancectl/gen.go internal/instancectl/rootfs.go |
| -git commit -m "instancectl: POST /fence marks a host and SIGKILLs its slice" -m "Every host-slice systemctl start goes through startInSlice, which |
| -refuses a marked host; /unfence clears the mark (G6 F1, G6-2.2)." |
| -``` |
| +- [ ] **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. |
| --- |
| -### Task 4: The activator watches, stops and kills (internal/activator) |
| +### Task 4: The activator watches, stops and fences (internal/activator) |
| **Corrections for this task (read first):** |
| -- Stop with `StopLeaseLost`, never `StopFenced` (Spec corrections 2). Name the flag `writeFenced`. |
| -- Start a stop only from `actAwake` (G6-1.4); an entry already stopping gets the kill and no new stop. |
| -- The watcher ends on the replicator's `Done()`, not on the entry's lifecycle; it never holds `a.mu` while calling root. |
| -- Do not route the kill through `KillHost` (`genbackend.go:684-717` opens `carlos-exec@<host>`, absent for nested hosts, G6-2.2). |
| -- The mark clears in `acquireClassified`'s HA branch (`hawake.go:425-436`), best effort: a failure is logged, and the next start's refusal (Task 3) keeps it safe. Do not touch `haadopt.go` (adoption acquires and releases without starting anything). |
| +- 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` |
| -- Modify: `internal/activator/activator.go` (`actEntry` gains `writeFenced bool`, `fenceRep Rep`; `Service` gains `fenceWatchers sync.WaitGroup`; `installProcLocked` calls `a.watchWriteFenceLocked(e)` after setting `e.rep`) |
| -- Modify: `internal/activator/swapadmit.go:88-102` (`ownedLocked`: `case e.writeFenced: return errSwapLeaseLost` right after the identity case, so waking callers refuse too) |
| -- Modify: `internal/activator/hawake.go:425-436` (`b.unfenceHost` after the HA acquire succeeds) |
| -- Modify (test double): `internal/activator/unitproc_test.go` (`fakeControl` gains `Fence`, `Unfence`, a `fenceHook func(host string)`, recording `fence <host>` / `unfence <host>` in `calls`) |
| -- Test: `internal/activator/writefence_test.go` |
| +- 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>`) |
| **Interfaces:** |
| -- Consumes: Task 2's `(*lease.Replicator).Done`, `FenceArmed`, `lease.ErrReplicaStale`; Task 3's `instancectl.FenceResponse`, `(*instancectl.Client).Fence`, `Unfence`, `instancectl.DeadlineFence`. |
| +- Consumes: Task 2 `Done`, `Fenced`, `FenceArmed`, `Generation`, `Held.Generation`; Task 3 `FenceResponse`, `Client.Fence`, `Client.Unfence`, `DeadlineFence`. |
| - Produces: |
| - - `type FenceControl interface { Fence(ctx context.Context, host string) (instancectl.FenceResponse, error); Unfence(ctx context.Context, host string) error }`; `var _ FenceControl = (*instancectl.Client)(nil)` |
| - - `type writeFenceRep interface { Lost() <-chan struct{}; Done() <-chan struct{}; Err() error; FenceArmed() bool }`; `var _ writeFenceRep = (*lease.Replicator)(nil)` |
| - - `type hostFencer interface { fenceHost(ctx context.Context, rt registry.Route) (instancectl.FenceResponse, error); unfenceHost(ctx context.Context, rt registry.Route) error }`, implemented by `*ExecBackend` (through `b.Control.(FenceControl)`; no such control is an error) and `*SplitBackend` (dispatch through `pick(rt)`, as `hostSliceEmpty` does, `backend_unit.go:458-463`) |
| - - `func (a *Service) watchWriteFenceLocked(e *actEntry)`: requires `haEntryRep(e)` and `e.rep.(writeFenceRep)` with `FenceArmed()`; idempotent (`e.fenceRep == e.rep` returns); sets `e.fenceRep`, `a.fenceWatchers.Add(1)`, `go a.watchWriteFence(e, e.rep, w)`. |
| - - `func (a *Service) watchWriteFence(e *actEntry, rep Rep, w writeFenceRep)`: waits on `w.Done()` (return) or `w.Lost()`; if `!errors.Is(w.Err(), lease.ErrReplicaStale)`, return; under `a.mu`: if `a.entries[e.host] != e || e.rep != rep`, return; `e.writeFenced = true`; if `e.state == actAwake`, `a.beginStopLocked(e, StopLeaseLost)`; copy `e.route`; release `a.mu`; log `activator: <host>: write fence: standing down and killing its slice`; `fenceHost` with `context.WithTimeout(context.Background(), instancectl.DeadlineFence)`; log `activator: <host>: write fence: <slice> empty after <d>` or the error (the release's own `hostSliceEmpty` proof still holds the lease until the slice is empty). |
| - |
| -- [ ] **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 `lost`, `done` channels, an `err` value and `FenceArmed() == true`; swap it in under `a.mu` and call `a.watchWriteFenceLocked(e)`. "Trip" = set `err` to `lease.ErrReplicaStale`, close `lost`. |
| - - `TestWriteFenceAnswersLikeALostLease`: after the trip, `assertLostResponse(t, s)` (503, `Retry-After: 10`, `X-Carlos-Holder: none`, no proxy, within 1 s). |
| - - `TestWriteFenceRequestAndWatcherStopOnce` (G6-1.4): trip and issue a request concurrently; exactly one stop (`e.stopped` created once: count `beginStopLocked` through a test hook or the fake rep's `ReleaseMarker`/`Finish` calls == 1), one marker write to the lock, one `fence <host>` call. |
| - - `TestWriteFenceKillsDuringABlockedStop` (G6-2.3), subtests `start-done`, `op-join`, `process-drain`: block the ordinary stop (`StopIdle`) in each wait (`a.joinWaiting` reports `"sidecar start"`; an operation member left running for `joinOps`; a process whose stop blocks until killed); trip; the fake's `fenceHook` releases the blocked wait. Assert `fence <host>` was called, the stop completes within 10 s, `e.stopWhy` is still `StopIdle`, and no second stop began. |
| - - `TestWriteFenceKillTargetsTheSliceNotTheExecCgroup` (G6-2.2): `b.openHostCleanup` set to fail the test if called; trip; `fence shop.example.com` is in `ctl.calls`. |
| - - `TestWriteFenceWatcherEndsOnCleanHibernation`: `stopForTest(e)` (`StopIdle`); the fake rep closes `done` in its `Finish`; `a.fenceWatchers.Wait()` returns within 5 s; no `fence` call; one stop. |
| - - `TestWriteFenceRefusesSpawnsWhileWaking` (F1 fast path): with `e.writeFenced` set, `a.ownedLocked(e, true)` returns `errSwapLeaseLost`. |
| - - `TestHAAcquireClearsTheFenceMark` (Review Focus 4; "the mark clears at the next acquire"): a fresh HA wake records `unfence <host>` before any `start` in `ctl.calls`; with `Unfence` failing, the wake still proceeds and logs. |
| - - `TestWriteFenceLatchToKillWiring` (G6-2.4, wiring only): a proxied request blocked in its handler and a fake worker goroutine incrementing a counter every 100 ms; trip; the `fenceHook` ends both. After `Fence` returns, the counter does not move for 500 ms and the blocked request gets no 2xx; a new request gets the lost-lease answer. |
| - |
| -- [ ] **Step 2: Run to see them fail** |
| + - `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)`) |
| + - `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. |
| -Run (sandbox off): `TMPDIR=$(mktemp -d /tmp/g/fence4.XXXX) go test ./internal/activator/ -run 'TestWriteFence|TestHAAcquireClearsTheFenceMark' -count=1` |
| -Expected: FAIL. |
| +- [ ] **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 3: Implement** `writefence.go` and the edits listed. `installProcLocked` keeps its existing body; the watch call goes after the `e.rep` assignment and before the rootfs lease watch. |
| +- [ ] **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. |
| -- [ ] **Step 4: Run to see them pass**, plus the HA suites this touches: |
| +- [ ] **Step 3: Implement** `writefence.go` and the edits listed. |
| -Run (same TMPDIR): the Step 2 command, then `go test ./internal/activator/ -run 'TestHALost|TestHARelease|TestRestoreHA|TestHAWake|TestDrain|TestStreamCapture' -count=1` |
| -Expected: 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.** `GOOS=darwin go build . && GOOS=windows go build .` |
| +- [ ] **Step 5: Cross-compile.** |
| -- [ ] **Step 6: Mutation checks** (revert each): drop the `actAwake` guard → `TestWriteFenceRequestAndWatcherStopOnce` fails; skip the kill when the entry is stopping → `TestWriteFenceKillsDuringABlockedStop` fails; ignore `Done()` → `TestWriteFenceWatcherEndsOnCleanHibernation` fails; remove the unfence → `TestHAAcquireClearsTheFenceMark` fails; drop the `writeFenced` case → `TestWriteFenceRefusesSpawnsWhileWaking` fails. |
| +- [ ] **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** |
| - |
| -```bash |
| -git add internal/activator/writefence.go internal/activator/writefence_test.go internal/activator/activator.go internal/activator/swapadmit.go internal/activator/hawake.go internal/activator/unitproc_test.go |
| -git commit -m "activator: stand down and kill the host slice on a write fence" -m "One watcher per HA stream entry; the stop is the lease-loss stop, |
| -started only from awake; the HA acquire clears root's mark (G6)." |
| -``` |
| +- [ ] **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. |
| --- |
| ### Task 5: The replication rail on HA routes (cli.go) |
| **Corrections for this task (read first):** |
| -- Keep `replicationRail`'s signature (five call sites in tests). Add a separate rail. |
| -- The message is copy-pending. Use the constant only; Task 7 swaps the text. The printed line is `route: <host>: <text>` (`log.Fatalf` at `cli.go:2061-2063`), which the copy reviewer should see. |
| -- Existing HA routes with another class keep it (§3.3): the rail refuses only setting `batched` or `daily`; setting `stream` or `""` on such a route is allowed. |
| +- 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). |
| +- Existing HA routes with another class keep it; only setting `batched`/`daily` is refused. |
| **Files:** |
| -- Modify: `cli.go:2060-2115` (`runRouteReplication` calls the new rail right after `replicationRail`; the rail beside it) |
| +- 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` (returns `fmt.Errorf(routeReplicationHARefusalFmt, rt.Host)` when `rt.HA` and `class` is `registry.ReplicationBatched` or `registry.ReplicationDaily`; nil otherwise). |
| +- 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 test** `TestReplicationHARail`: for `rt.HA = true`, classes `batched` and `daily` give an error whose text equals `fmt.Sprintf(routeReplicationHARefusalFmt, rt.Host)`; `""` and `stream` give nil. For `rt.HA = false`, all four give nil. |
| +- [ ] **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 it fail** |
| - |
| -Run: `go test . -run 'TestReplicationHARail' -count=1` |
| -Expected: FAIL (undefined: replicationHARail). |
| +- [ ] **Step 2: Run to see them fail.** `go test . -run 'TestReplicationHARail|TestRouteReplicationRefusedOnAnHARoute' -count=1` → FAIL. |
| - [ ] **Step 3: Implement** the rail and the call. |
| -- [ ] **Step 4: Run to see it pass**, with the existing rail tests: |
| - |
| -Run: `go test . -run 'TestReplicationHARail|TestRouteReplication|TestRootfsReplication|TestReplicationRail' -count=1` |
| -Expected: PASS. |
| +- [ ] **Step 4: Run to see them pass**, with `TestRouteReplication|TestReplicationRail|TestRootfsReplication`. |
| -- [ ] **Step 5: Cross-compile.** `GOOS=darwin go build . && GOOS=windows go build .` |
| +- [ ] **Step 5: Cross-compile.** |
| -- [ ] **Step 6: Mutation check**: drop the `rt.HA` condition → the non-HA rows fail. |
| +- [ ] **Step 6: Mutation checks**: drop the `rt.HA` condition → non-HA rows fail; remove the call from `runRouteReplication` → `TestRouteReplicationRefusedOnAnHARoute` fails. |
| -- [ ] **Step 7: Commit** |
| - |
| -```bash |
| -git add cli.go route_replication_test.go |
| -git commit -m "route: refuse batched and daily replication on HA routes (G6)" |
| -``` |
| +- [ ] **Step 7: Commit.** `git commit -m "route: refuse batched and daily replication on HA routes (G6)"` |
| --- |
| ### Task 6: Spec text and the census card |
| **Corrections for this task (read first):** |
| -- Branch `ha-unclean-marker-waits` also edits the region HA spec (unplanned takeover time) and the runbook. Change only the §5.5 paragraph there. |
| -- The census overlay depends on every code change above; re-run `census-propose` with the same NAME if any later commit touches a census file (Task 7 will). |
| +- 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). |
| **Files:** |
| -- Modify: `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` (§5.5, after its second paragraph, line ~227) |
| -- Modify: `docs/superpowers/specs/2026-11-11-g6-write-fence-design.md` (append `## 9. Build notes (plan 2026-11-12)`) |
| +- 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` |
| - [ ] **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 2: Fence spec §9.** One short paragraph per item of this plan's Spec corrections 2 to 8 and 11, stating what the build does instead and each residual of item 8 in the spec's own voice. Do not edit §1 to §8 (approved text). |
| - |
| -- [ ] **Step 3: Census card.** `make census-card`. Write `$TMPDIR/g6-fence-claims.tsv`, one line per changed unit the card lists (`<file>:<unit><TAB><claim>`). Claims to make, matched to the card's unit names: instancectl `handleFence` (new: runs `systemctl kill --signal=SIGKILL` on `SliceName(host)` of a host that passed `ValidHostShape`, reads that slice's `cgroup.events` under `CgroupRoot`; the host comes from the agent's request); `handleUnfence` (new: deletes an in-memory mark; no read); `startInSlice` and `refuseFenced` (new: add refusals only; the start's arguments are the caller's, unchanged); `handleStart`, `handleSeed`, `startOneShot`, `startGen`, `startRootfs`, `startRootfsCmd` (body: a refusal at entry and the start through `startInSlice`; no read added); lease, activator and root-package units (agent-side code compiled into the root binary; no root read added; `runRouteReplication` adds a refusal only). |
| - |
| -- [ ] **Step 4: Propose and check.** `make census-propose NAME=g6-fence CLAIMS=$TMPDIR/g6-fence-claims.tsv`, then |
| +- [ ] **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. |
| -Run: `go test ./internal/provision/ -run 'TestPlan14RootReadCensus|TestCensusScopeIsTheRootBinary' -count=1` |
| -Expected: PASS. Delete the claims file. |
| +- [ ] **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 5: Commit** |
| +- [ ] **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. |
| -```bash |
| -git add docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md docs/superpowers/specs/2026-11-11-g6-write-fence-design.md internal/provision/testdata/ docs/superpowers/notes/census-proposal-g6-fence.md |
| -git commit -m "G6 fence: RHA 5.5 sentence, build notes, census card" |
| -``` |
| +- [ ] **Step 5: Commit.** `git commit -m "G6 fence: RHA 5.5 sentence, build notes, census card"` |
| --- |
| ### Task 7: Wire the approved copy (waits on Paul's review) |
| **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` and has an approved entry for `cli.route.replication_ha_refusal`. Read it; never copy text from the spec or `strings.json`. |
| -- The approved text must keep exactly one `%s` (the hostname). If it does not, stop and report. |
| -- Other G6 copy ids belong to the pool-path plan; touch none of them and no shared copy record. |
| - |
| -**Files:** |
| -- Modify: `cli.go` (`routeReplicationHARefusalFmt` value) |
| -- Create: `approved_g6_fence_copy_test.go` |
| -- Modify (regenerated): the census overlay and card (`make census-propose NAME=g6-fence ...` again) |
| - |
| -- [ ] **Step 1: Write the failing test** `TestG6FenceRefusalCopyIsApproved`: `routeReplicationHARefusalFmt` equals the approved text, pinned as a literal in the test; it contains exactly one `%s`; it has no `COPY-PENDING`, no em dash. `TestG6FenceNoPendingCopy`: no non-test `.go` file of the root package contains `COPY-PENDING:cli.route.replication_ha_refusal`. |
| +- 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`. |
| +- The approved text keeps exactly one `%s`. If not, stop and report. |
| +- Touch no other G6 copy id and no shared copy record. |
| -- [ ] **Step 2: Run to see it fail** |
| +**Files:** Modify `cli.go`; create `approved_g6_fence_copy_test.go`; regenerate the census overlay and card. |
| -Run: `go test . -run 'TestG6Fence' -count=1` |
| -Expected: FAIL. |
| - |
| -- [ ] **Step 3: Set the constant** to the approved text. |
| - |
| -- [ ] **Step 4: Run to see it pass**, with Task 5's test: |
| - |
| -Run: `go test . -run 'TestG6Fence|TestReplicationHARail' -count=1` |
| -Expected: PASS. |
| - |
| -- [ ] **Step 5: Re-propose the census** with the same NAME and claims (`runRouteReplication` body unchanged in behaviour; the constant's text changed) and run the two census tests as in Task 6 Step 4. |
| - |
| -- [ ] **Step 6: Commit** |
| - |
| -```bash |
| -git add cli.go approved_g6_fence_copy_test.go internal/provision/testdata/ docs/superpowers/notes/census-proposal-g6-fence.md |
| -git commit -m "route: approved copy for the HA replication 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 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"` |
| --- |
| @@ -482,12 +410,10 @@ git commit -m "route: approved copy for the HA replication refusal" |
| 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. |
| 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). |
| -Lines to read in the journal: lease `a write has waited ... (write fence)` (fence line); systemd `Main process exited, code=killed, status=9/KILL` per unit (writers dead); activator `write fence: <slice> empty after <d>` (slice-empty). |
| - |
| -**Flagship check (§3.3).** Before the pool's first app: on a member, `carlos routes` shows the class of every pool `ha` route; expect none `batched` or `daily`. |
| +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. |
| -**With branch `ha-unclean-marker-waits`.** A fence trip always ends in an unclean marker (`finishErr` carries `ErrReplicaStale`, `release.go:254`), and at the latch the renewer stops renewing (`health.go:193-214`), so the lock keeps the expiry of its last renewal: at most 15 minutes after the latch, and at least about 9.4 minutes after it (renewals run every 5 minutes, the latch comes 30 to 35 s after the cut). Today any marker is taken at once (`hafresh/acquire.go:87-89`). Once that branch lands, an unclean marker waits for the old holder's lease term: recovery after a fence is the later of the store's return (when the owed marker lands) and that expiry, which is about 10 to 15 minutes after the fence line if the rule reads the lease's expiry, or 15 minutes after the marker lands if it counts from the marker's write. During the wait every request gets 503 with `Retry-After: 10` from the loss latch. §4's "the service comes back without a terminate" still holds, later. The drill's "serves again within RHA §9.8's bound" then needs that bound read with the new wait; record the measured time. The release itself is unchanged: the marker's `markerExpiry` body (`hafresh/lock.go:73`) is that branch's to extend. |
| +**Flagship check (§3.3).** On a member, `carlos routes` shows the class of every pool `ha` route; expect none `batched` or `daily`. |
| -**Files both branches touch:** `internal/lease/release.go` (this plan: two lines in `finalize`; that branch: the comment above it) and `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` (this plan: §5.5; that branch: takeover time). Neither touches the other's code paths; whichever merges second rebases those two hunks. No test of this plan 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), 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. |
| -**Rollout.** The fence rides the next release (dev first, then flagship per the roll recipe). Root's `/fence` and the agent's caller ship in one binary, so there is no version skew inside a box. |
| +**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. |