fix: keep demo builds closed until snapshot recovery succeeds
Start demo workers snapshot-poisoned because helpers can survive an instance-control restart. Set poison after a failed recovery reap and clear it only after successful snapshot recovery.
Cover failed cleanup, recovery after repair, build admission, and prompt recovery of a clean box during server startup. Targeted build, claim and purge tests and scoped go vet pass.
codex agent, operated by paul@keymail.devpushed by claude agent, operated by paul@keymail.devef8b609ad6ba367f5af6b72deddfb866e9f3497dparent 2e3ae79
<task-notification>
<task-id>ad121279a077d2ff2</task-id>
<tool-use-id>toolu_01PNEQ48RtaHp3vU2gzYG84x</tool-use-id>
<output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/ad121279a077d2ff2.output</output-file>
<status>completed</status>
<summary>Agent "Re-review Task 3 fix round 1" finished</summary>
<note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note>
<result>**Verdict: READY AFTER FIXES.** All six round-1 findings are fixed. One new P2 needs fixing first: a failed snapshot recovery after an instance-control restart no longer keeps builds closed. I found no P1s. I ran no tests; everything below comes from reading the code.
## Round-1 findings
**P1-1, lock order: ADDRESSED.**
- `internal/instancectl/demo_snapshot.go:135-148`: `handleDemoSnapshot` takes `DemoPurgeGuard` (the adopt flock) once, before the snapshot slot. It keeps it through streaming, cleanup and slot release.
- `demo_snapshot.go:64-80`: `snapshotHeld` no longer takes the guard. It does the same field-for-field hold recheck under `lockDemo`, and runs at the start, after the upload and before streaming.
- Every lock order I traced is now acyclic:
- Purge: guard → `lockDemo` → `buildPurge.Lock` (`demo_cleanup.go:62-65`, `:85`, `purge.go:21`).
- Freeze: guard → `lockDemo` (`demo_claim.go:62`, `:81`).
- Snapshot: guard → `lockDemo` (released) → busy → `buildPurge.TryLock` (`snapshot_slot.go:8`) → `lockDemo` again. The only inversion against purge is inside the guard, and the guard is a flock on a fresh descriptor each time, so it shuts out other goroutines in the same process too.
- Build: `buildPurge.RLock` only (`worker.go:197`).
- Start gate: `lockDemo` only (`demo_policy.go:28`).
- `ensureReady`: `initMu.TryLock` → busy CAS → `buildPurge.TryLock`. It never takes `lockDemo` or the flock.
- Nothing inside the export calls the guard again, so it cannot deadlock on its own flock.
- `demo_snapshot_fix_linux_test.go:58` exercises the production order with a real flock.
**P1-2, crash on snapshot init failure: ADDRESSED.**
- `server.go:377-379`: `Serve` calls `ensureReady` and ignores the result, so `runWithClaim`'s `log.Fatalf` can no longer fire for this.
- `demo_snapshot.go:466-497`: retry happens only on demand, at most once every 5 s. It is serialised by `initMu`, `busy` and the builder slot.
- Exports are refused with 503 until recovery succeeds (`:97`). Claim capability is advertised only when `ready` is set (`demo_build.go:96-107`).
- `ready` is set only at the end of `initialize` (`:500`, `:558-561`). Each export still does its own `assertUnit`, disk-space check and hold recheck, so a half-initialised provider cannot serve.
**P2-1, WAL recovery prefix: ADDRESSED.**
- `internal/democlaim/snapshot.go:152-218`: the WAL header is still checked strictly and a bad one is refused.
- Scanning stops at the first salt mismatch, bad checksum or partial frame. Checksums chain from the header checksum, and byte order follows the magic's low bit, as SQLite does.
- Page limits apply only to frames that pass validation. The copy is truncated after the last valid commit frame, or at 32 bytes if there is none.
- This runs only on the helper's private copy and only without root (`finishSnapshot` at `:81-86` refuses euid 0). No shared-memory file exists in that copy, so SQLite rebuilds its index from the truncated WAL.
- Stopping at the first invalid frame matches SQLite, so committed frames after it are correctly dropped, and SQLite sees exactly what the scan validated.
- One harmless difference: an uncommitted frame with a valid checksum but an out-of-range page number is refused rather than ignored. That fails closed.
**P3-1, poison until the unit is proven stopped: ADDRESSED** for a live process.
- `purge.go:69-75`: `recoverPurge` refuses while snapshot poison is set and never runs build cleanup for it.
- `snapshot_slot.go:24-29`, `:33-46`: only `RecoverSnapshots` clears snapshot poison, and only after `initialize` has stopped the helper.
- Every failure path in `p.cleanup` (`demo_snapshot.go:407-428`) clears `ready`, so the next readiness probe retries recovery.
- The restart case is not covered; see the new P2 below.
**P3-2, unknown close IDs: ADDRESSED.**
- `demo_snapshot.go:314-320`: no placeholder session is created, and an unknown ID gets 409.
**P3-3, capability after failed hold recovery: ADDRESSED.**
- `internal/host/demo_jobs.go:357-360`, `:480-482`: `ClaimCapability` is cleared before readiness is published, and `demoClaimCapability` reads it (`demo_claim_executor.go:37`).
## New findings
**P2-A: a restart with a failed snapshot reap admits builds while the helper may still be running.**
- `snapshotPoisoned` lives only in memory and starts false (`worker.go:49`). Only `AcquireSnapshot`'s release sets it.
- Scenario: instance-control restarts mid-export. The `carlos-demo-snapshot@` unit is its own systemd unit, so it outlives the restart.
- `Serve` → `ensureReady` → `RecoverSnapshots` → `initialize` → `cleanup` fails (stop or unmount error). `RecoverSnapshots` returns the error without poisoning anything (`snapshot_slot.go:38-40`).
- `Worker.available()` (`worker.go:149`) is then true. `handleDemoBuildReady` ignores what `ensureReady` returns (`demo_build.go:96-99`). Builds are advertised and admitted while the old helper and its scratch may still exist.
- This breaks the brief's rule: "serialize it with the builder slot; kill/reap before returning or cleaning scratch, including restart recovery." Before the fix, this case crash-looped, so no build could run; the soft-init change opened it.
- `RuntimeMaxSec=120` limits the overlap, but a failed stop is exactly the case where nothing proves that limit held.
- Suggested fix: set `snapshotPoisoned = true` in `RecoverSnapshots` when the reap fails, or start a demo-box worker poisoned until the first successful `RecoverSnapshots`. Add a regression test where initial `cleanup` fails and builds stay unavailable until it is repaired.
- Fault family: snapshot cleanup work must keep builds closed until the helper is proven stopped. This is the same family as round-1 P3-1, now reached through the P1-2 restart path.
**P3-a: the export now holds the adopt flock for up to about 2.5 minutes** (120 s window plus 10 s stop and cleanup).
- Adopt passes, stage relays, purge and freeze wait for it. `instanceDemoPurgeGuard` takes the flock without honouring its context (`claimstop_run.go:279`, `adoptlock.go:47`).
- So freeze's 30 s budget and the close door's 12 s wait can expire while a request sits on the flock. The handler then gives up cleanly once it gets the lock (`claimstop_run.go:284`).
- This is what the chosen outer-guard design costs, not a deadlock. It is worth a comment or a bounded wait.
**P3-b: recovery can run past its timeout.** `p.cleanup` creates its own `context.Background()` timeout of `stopWindow` (`demo_snapshot.go:407-409`), so the timeout `ensureReady` sets does not bound a cleanup already in progress.
- One recovery can take about 2× `stopWindow` (roughly 20 s). That holds up `Serve` startup and a `/demo-build/ready` request, while the agent's readiness probe gives up at 10 s (`demo_jobs.go:474`).
- Effect: one lost readiness tick during recovery.
## Other checks
- Root never reads from a path the agent or tenant can write: `checkWALBounds` and its truncation run in the unprivileged helper, and `initialize` reads only the root-owned 0700 snapshot root.
- Lock ordering of the new `ensureReady` and `RecoverSnapshots` path against purge, adopt, build and freeze is covered under P1-1 above.
## Out of scope
- Because unknown close IDs now get 409, a close that arrives before its POST registers no longer cancels that POST. The agent must cancel its own request context too. That was the requested change; I did not check the client side.
- The real-systemd and cgroup witnesses are still gated and were not run.
## Verdict
**READY AFTER FIXES**
- P2-A: restart recovery failure must keep builds closed. Same family as round-1 P3-1.
Files: `internal/demobuild/snapshot_slot.go`, `internal/demobuild/worker.go`, `internal/instancectl/demo_snapshot.go`, `internal/instancectl/demo_build.go`, `internal/instancectl/server.go`, all under `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/agent-start-demo-3/`.</result>
<usage><subagent_tokens>104275</subagent_tokens><tool_uses>16</tool_uses><duration_ms>219212</duration_ms></usage>
</task-notification>
Attributed to this commit: 10.5 g CO₂e (1,251,033 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on agent-start-demo-3, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.