plan: G6 write fence (F-C), seven tasks
Implements spec rev 3.1. Lists spec corrections found against 3d332f24 (client gate in place of Stop(true), salt-aware WAL coverage, StopLeaseLost, root start wrapper) and the drill 4 exit test.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+493
−0
docs/superpowers/plans/2026-11-12-g6-write-fence.md+493 −0
Intent
diff --git a/docs/superpowers/plans/2026-11-12-g6-write-fence.md b/docs/superpowers/plans/2026-11-12-g6-write-fence.md| new file mode 100644 |
| index 000000000..19564d73b |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-12-g6-write-fence.md |
| @@ -0,0 +1,493 @@ |
| +# G6 Write Fence (F-C) Implementation Plan |
| + |
| +> **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. |
| + |
| +**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. |
| + |
| +**Tech Stack:** Go; litestream v0.5.14 (embedded); `github.com/superfly/ltx` v0.5.1; systemd 257 (Debian 13 boxes). |
| + |
| +**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`. |
| + |
| +**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. |
| + |
| +## Spec corrections (verified against this tree, 3d332f24) |
| + |
| +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`. |
| + |
| +## 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 .`. |
| +- Mutation checks only on refusal, termination and lifecycle paths, at most ~10 per task, each a targeted `-run`; revert each one. |
| +- Commit subjects under 80 characters, body after a blank line. Implementers never create or remove worktrees, never `git worktree prune`, never `git stash`, never push, never touch amadan. |
| +- Census: every package here is in the root binary's `go list -deps .`; Task 6 runs `make census-card` / `make census-propose NAME=g6-fence CLAIMS=<file>` and commits the overlay. Astra decides. |
| +- Wire shapes are additive. No new sqlite columns. Provider-neutral core: no AWS calls; the fence makes no request and adds no S3 cost. |
| +- Do not touch `internal/hafresh/acquire.go` (`DecideAcquire`): branch `ha-unclean-marker-waits` owns it. |
| + |
| +## Review Focus |
| + |
| +1. **An HA stream instance with no database, or 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`.) |
| + |
| +--- |
| + |
| +### 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`. |
| + |
| +**Files:** |
| +- Create: `internal/lease/fence.go` |
| +- Test: `internal/lease/fence_queue_test.go` (`package lease`) |
| + |
| +**Interfaces:** |
| +- Produces (used by Task 2): |
| + - `var ErrReplicaStale = errors.New("lease: a write has waited too long to reach storage (write fence)")` (distinct from `ErrLost`; does not wrap it) |
| + - `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 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 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: |
| + |
| +```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 |
| + if s.statErr == nil { |
| + q.w, q.haveW = s.W, true |
| + } |
| + advanced := s.lOK && s.L > q.l |
| + if advanced { // rule A: obligations from EARLIER runs are in transactions up to L |
| + for i := range q.ob { |
| + if !q.ob[i].known { |
| + q.ob[i].txid, q.ob[i].known = s.L, true |
| + } |
| + } |
| + q.l = s.L |
| + } |
| + if changed { |
| + 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 |
| + if txid, ok := covered(); ok { |
| + for i := range q.ob { |
| + if !q.ob[i].known { |
| + q.ob[i].txid, q.ob[i].known = txid, true |
| + } |
| + } |
| + } |
| + } |
| + 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 |
| + 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). |
| + |
| +- [ ] **Step 4: Run to see them pass** |
| + |
| +Run: `go test ./internal/lease/ -run 'TestFenceQueue|TestWalCovered' -count=1` |
| +Expected: PASS. |
| + |
| +- [ ] **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)" |
| +``` |
| + |
| +--- |
| + |
| +### Task 2: The fence 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). |
| + |
| +**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`) |
| + |
| +**Interfaces:** |
| +- Consumes: Task 1's `fenceQueue`, `fenceSample`, `walState`, `walCovered`, `ErrReplicaStale`, `fenceTick`, `fenceLimit`. |
| +- 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). |
| + |
| +- [ ] **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`. |
| + - `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. |
| + |
| +- [ ] **Step 4: Run to see them pass**, then the neighbours this wiring can disturb: |
| + |
| +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.** `GOOS=darwin go build . && GOOS=windows go build .` succeeds. |
| + |
| +- [ ] **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)." |
| +``` |
| + |
| +--- |
| + |
| +### Task 3: Root fences a 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. |
| + |
| +**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` |
| + |
| +**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"` }` |
| + - `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`) |
| +- 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)` |
| + |
| +`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. |
| + |
| +- [ ] **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. |
| + |
| +- [ ] **Step 2: Run to see them fail** |
| + |
| +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. |
| + |
| +- [ ] **Step 3: Implement** `fence.go` and the edits above. The seven start sites keep their existing error handling; only the call changes. |
| + |
| +- [ ] **Step 4: Run to see them pass**, plus the start paths' own suites: |
| + |
| +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 5: Cross-compile.** `GOOS=darwin go build . && GOOS=windows go build .` |
| + |
| +- [ ] **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 7: Commit** |
| + |
| +```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)." |
| +``` |
| + |
| +--- |
| + |
| +### Task 4: The activator watches, stops and kills (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). |
| + |
| +**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` |
| + |
| +**Interfaces:** |
| +- Consumes: Task 2's `(*lease.Replicator).Done`, `FenceArmed`, `lease.ErrReplicaStale`; Task 3's `instancectl.FenceResponse`, `(*instancectl.Client).Fence`, `Unfence`, `instancectl.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** |
| + |
| +Run (sandbox off): `TMPDIR=$(mktemp -d /tmp/g/fence4.XXXX) go test ./internal/activator/ -run 'TestWriteFence|TestHAAcquireClearsTheFenceMark' -count=1` |
| +Expected: FAIL. |
| + |
| +- [ ] **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 4: Run to see them pass**, plus the HA suites this touches: |
| + |
| +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 5: Cross-compile.** `GOOS=darwin go build . && GOOS=windows go build .` |
| + |
| +- [ ] **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 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)." |
| +``` |
| + |
| +--- |
| + |
| +### 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. |
| + |
| +**Files:** |
| +- Modify: `cli.go:2060-2115` (`runRouteReplication` calls the new rail right after `replicationRail`; the rail beside it) |
| +- 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). |
| + |
| +- [ ] **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 2: Run to see it fail** |
| + |
| +Run: `go test . -run 'TestReplicationHARail' -count=1` |
| +Expected: FAIL (undefined: replicationHARail). |
| + |
| +- [ ] **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 5: Cross-compile.** `GOOS=darwin go build . && GOOS=windows go build .` |
| + |
| +- [ ] **Step 6: Mutation check**: drop the `rt.HA` condition → the non-HA rows fail. |
| + |
| +- [ ] **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)" |
| +``` |
| + |
| +--- |
| + |
| +### 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). |
| + |
| +**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)`) |
| +- 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 |
| + |
| +Run: `go test ./internal/provision/ -run 'TestPlan14RootReadCensus|TestCensusScopeIsTheRootBinary' -count=1` |
| +Expected: PASS. Delete the claims file. |
| + |
| +- [ ] **Step 5: Commit** |
| + |
| +```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" |
| +``` |
| + |
| +--- |
| + |
| +### 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`. |
| + |
| +- [ ] **Step 2: Run to see it fail** |
| + |
| +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" |
| +``` |
| + |
| +--- |
| + |
| +## After merge (not plan tasks) |
| + |
| +**Dev drill 4 rerun (the exit test; needs a #421 window and 8a3d302's GO).** `~/.cache/region-ha-next/G2-CARD.md` drill 4, the fault harness with its 35-minute expiry timer, on the dev IE group, pool `hapair`, fixture `g2-stream` written about once a second through both entries: |
| +1. Cut outbound 443 on the holder for 10 minutes. |
| +2. **Pass:** the fence line appears between t0+30 s and t0+35 s; from it every request started after it gets 503 with `Retry-After: 10`, with no hangs; acknowledged and lost writes (probe acks against `/ranges`) were all committed between 32 s before the fence line and the writers-dead line, and number at most 36 (was 131); `K` (fence line to writers dead) is under 2 s; slice-empty is recorded; after the fault ends the unclean marker lands and the fixture serves again within the bound of RHA §9.8; no other box takes the lease before the marker or a terminate; the F-A, F-B and F-D rows of the rerun still pass. |
| +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`. |
| + |
| +**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. |
| + |
| +**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. |
| + |
| +**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. |