carlos / platform Public

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.dev pushed by claude agent, operated by paul@keymail.dev ef8b609ad6ba367f5af6b72deddfb866e9f3497d parent 2e3ae79
4 files changed, +119 −6
  • internal/demobuild/snapshot_slot.go +3 −5
  • internal/demobuild/worker.go +3 −1
  • internal/demobuild/worker_test.go +49 −0
  • internal/instancectl/demo_snapshot_fix_linux_test.go +64 −0

Intent

Human

<task-notification> <task-id>brp3ptfmk</task-id> <tool-use-id>toolu_01JzV5vEbPiBKwuYz23LaoaF</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/brp3ptfmk.output</output-file> <status>completed</status> <summary>Background command "S=/home/paulca/.cache/tmp/claude-1001/agent-start-demo-3; until [ -f $S/t3fix.done ]; do sleep 30; done; tail -1 $S/t3fix.log" completed (exit code 0)</summary> </task-notification>

Human

<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.

diff --git a/internal/demobuild/snapshot_slot.go b/internal/demobuild/snapshot_slot.go
index b242f85f4..39b0225c7 100644
--- a/internal/demobuild/snapshot_slot.go
+++ b/internal/demobuild/snapshot_slot.go
@@ -36,11 +36,9 @@ func (w *Worker) RecoverSnapshots(ctx context.Context, reap func(context.Context
return ErrBuild
}
defer w.buildPurge.Unlock()
- if err := reap(ctx); err != nil {
- return err
- }
+ err := reap(ctx)
w.mu.Lock()
- w.snapshotPoisoned = false
+ w.snapshotPoisoned = err != nil
w.mu.Unlock()
- return nil
+ return err
}
diff --git a/internal/demobuild/worker.go b/internal/demobuild/worker.go
index 07552b905..8b06b70ad 100644
--- a/internal/demobuild/worker.go
+++ b/internal/demobuild/worker.go
@@ -95,7 +95,9 @@ func NewWorker(getenv func(string) string, proof func(context.Context) error) (*
if err != nil {
return nil, err
}
- w := &Worker{cfg: cfg, box: box, pub: pub, lock: lock, root: BuildRoot, slots: make(chan struct{}, cfg.BuildConcurrency), proof: proof, processLock: guard}
+ // A snapshot helper can outlive instance-control. Only snapshot recovery
+ // proves that a previous process left no helper running.
+ w := &Worker{cfg: cfg, box: box, pub: pub, lock: lock, root: BuildRoot, slots: make(chan struct{}, cfg.BuildConcurrency), proof: proof, processLock: guard, snapshotPoisoned: true}
w.retryCleanup = w.recover
w.prepare = w.prepareUnit
w.run = w.runUnit
diff --git a/internal/demobuild/worker_test.go b/internal/demobuild/worker_test.go
index 88929e7c9..7de6f6413 100644
--- a/internal/demobuild/worker_test.go
+++ b/internal/demobuild/worker_test.go
@@ -11,6 +11,7 @@ import (
"encoding/base64"
"encoding/hex"
"errors"
+ "fmt"
"io"
"os"
"path/filepath"
@@ -44,6 +45,54 @@ func (r neverRead) Read([]byte) (int, error) {
return 0, io.EOF
}
+func TestDemoBuildSnapshotRecoveryAdmission(t *testing.T) {
+ for _, initialPoison := range []bool{false, true} {
+ t.Run(fmt.Sprintf("initialPoison=%t", initialPoison), func(t *testing.T) {
+ fakeUnitController(t)
+ systemctl = func(context.Context, ...string) (string, error) {
+ return "MemoryMax=1073741824\nMemorySwapMax=0\nTasksMax=128\nCPUQuotaPerSecUSec=500ms\n", nil
+ }
+ w, j, key, src := workerFixture(t)
+ w.snapshotPoisoned = initialPoison
+ wire, err := SignJob(key, j)
+ if err != nil {
+ t.Fatal(err)
+ }
+ refuse := func() {
+ t.Helper()
+ if w.available() {
+ t.Fatal("builds available before successful snapshot recovery")
+ }
+ if _, err := w.Readiness(t.Context()); err == nil {
+ t.Fatal("advertised before successful snapshot recovery")
+ }
+ if _, err := w.Build(t.Context(), wire, neverRead{t}); err == nil {
+ t.Fatal("build admitted before successful snapshot recovery")
+ }
+ }
+ if initialPoison {
+ refuse()
+ }
+ if err := w.RecoverSnapshots(t.Context(), func(context.Context) error { return ErrBuild }); !errors.Is(err, ErrBuild) {
+ t.Fatalf("recovery error = %v", err)
+ }
+ refuse()
+ if err := w.RecoverSnapshots(t.Context(), func(context.Context) error {
+ refuse()
+ return nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := w.Readiness(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := w.Build(t.Context(), wire, bytes.NewReader(src)); err != nil {
+ t.Fatal(err)
+ }
+ })
+ }
+}
+
func TestDemoBuildWrongGrant(t *testing.T) {
for _, mutate := range []func(*Job){func(j *Job) { j.Account = "other" }, func(j *Job) { j.Box = "box-2" }, func(j *Job) { j.Fleet = "other" }, func(j *Job) { j.Host = "bright-otter-42.other.example.com" }, func(j *Job) { j.BundleSHA256 = strings.Repeat("c", 64) }, func(j *Job) { j.Deadline = time.Now().Add(BuildWindow + ClockSkew + time.Second) }} {
w, j, priv, _ := workerFixture(t)
diff --git a/internal/instancectl/demo_snapshot_fix_linux_test.go b/internal/instancectl/demo_snapshot_fix_linux_test.go
index 40388fb32..3fe692d3f 100644
--- a/internal/instancectl/demo_snapshot_fix_linux_test.go
+++ b/internal/instancectl/demo_snapshot_fix_linux_test.go
@@ -129,6 +129,70 @@ func TestDemoClaimSnapshotPurgeLockOrder(t *testing.T) {
func (b *snapshotBuilderFake) Initialize(context.Context) error { return nil }
+type snapshotStartupBuilder struct {
+ *startupBuilder
+ recovered chan error
+}
+
+func (b *snapshotStartupBuilder) RecoverSnapshots(ctx context.Context, reap func(context.Context) error) error {
+ err := reap(ctx)
+ b.recovered <- err
+ return err
+}
+
+func TestDemoClaimSnapshotCleanStartup(t *testing.T) {
+ f := newSnapshotFixture(t)
+ f.p.ready.Store(false)
+ f.p.stopWindow = time.Second
+ f.s.PeerOK = func(net.Conn) error { return nil }
+ b := &snapshotStartupBuilder{
+ startupBuilder: &startupBuilder{entered: make(chan struct{}), release: make(chan struct{}), done: make(chan struct{})},
+ recovered: make(chan error, 1),
+ }
+ f.s.DemoBuilder = b
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithCancel(t.Context())
+ stopped := make(chan error, 1)
+ go func() { stopped <- f.s.Serve(ctx, ln) }()
+ t.Cleanup(func() {
+ cancel()
+ ln.Close()
+ select {
+ case err := <-stopped:
+ if err != nil {
+ t.Error(err)
+ }
+ case <-time.After(time.Second):
+ t.Error("Serve did not stop")
+ }
+ })
+ // Startup must recover even when no claim or readiness request arrives.
+ select {
+ case err := <-b.recovered:
+ if err != nil || !f.p.ready.Load() {
+ t.Fatalf("clean startup recovery failed: %v", err)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("startup did not run snapshot recovery")
+ }
+ close(b.release)
+ select {
+ case <-b.done:
+ case <-time.After(time.Second):
+ t.Fatal("startup did not initialize builder")
+ }
+ c := &Client{Dial: func(ctx context.Context, _ string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, "tcp", ln.Addr().String())
+ }}
+ if _, err := c.DemoBuildReadiness(t.Context()); err != nil {
+ t.Fatalf("clean box unavailable after startup: %v", err)
+ }
+ f.noScratch(t)
+}
+
func TestDemoClaimSnapshotSoftInitialization(t *testing.T) {
for _, fault := range []string{"missingRoot", "rootMode", "unexpectedEntry", "cleanup", "unitProperties"} {
t.Run(fault, func(t *testing.T) {