fix: demo snapshot lock order, soft init and WAL tails
Address Task 3 review round 1: hold the adopt guard outside snapshot exclusion, retry unavailable snapshot initialization without stopping instance-control, and recover the committed SQLite WAL prefix. Keep snapshot cleanup poison separate from build cleanup, refuse unknown transfer closes, and suppress claim capability after failed hold recovery. Add failing-before regressions for all six findings. Validation: targeted TestDemo regressions in instancectl, demobuild, democlaim and host; touched-package go vet and touched-file gofmt checks. Real-box witnesses remain gated and unrun.
internal/demobuild/purge.go+4 −1internal/demobuild/snapshot_slot.go+17 −1internal/demobuild/snapshot_slot_test.go+39 −0internal/demobuild/worker.go+3 −1internal/democlaim/snapshot.go+19 −11internal/democlaim/snapshot_test.go+96 −2internal/host/demo_claim_executor_test.go+50 −0internal/host/demo_jobs.go+3 −0internal/instancectl/demo_build.go+3 −0internal/instancectl/demo_snapshot.go+72 −19internal/instancectl/demo_snapshot_fix_linux_test.go+256 −0internal/instancectl/demo_snapshot_test.go+3 −0internal/instancectl/server.go+1 −3
CI failed — run details
Intent
<task-notification> <task-id>b2dg2o101</task-id> <tool-use-id>toolu_01KtD4FzmaEhAm7FBHrpY6V8</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/b2dg2o101.output</output-file> <status>completed</status> <summary>Background command "S=/home/paulca/.cache/tmp/claude-1001/agent-start-demo-3; until [ -f $S/t3d.done ]; do sleep 30; done; tail -1 $S/t3d.log" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>ae3358749d8f7d5c5</task-id> <tool-use-id>toolu_01Kk96kXsQcaqErQpRm5u32f</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/ae3358749d8f7d5c5.output</output-file> <status>completed</status> <summary>Agent "Review Task 3 (Opus)" 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>**Task 3 review, round 1 of 3: NOT READY.** Two P1 defects block merge: a deadlock between root's snapshot and purge doors, and a snapshot startup failure that kills root control on the whole demo box. ## 1) Spec compliance: ❌ (because of the P1s; the interface surface is complete) - **Interfaces all present.** `Work`/`SignWork`/`VerifyWork`, `claimDemo`, `FreezeDemo` on `POST /demo-freeze`, `ExportSQLite`/`Snapshot`, `SnapshotDemo` on `POST /demo-snapshot`, `RunSnapshotWorker` with private `__demo-snapshot` dispatch (`main.go:38`), `Record.DemoClaim`, `StreamMessage.Claim` and `WorkerReady.ClaimCapability`. `EmptyBuild` ignores the claim capability. - **Files the brief listed but the diff does not touch, all justified:** - `internal/console/apidemobox.go`: moved to Task 5 by R3. - `internal/host/bootstrap.go`: the existing `units/*.service` embed glob already installs the new unit. - `internal/instancectl/demo_policy.go`: its existing `/start` gate already refuses held demo rows. - **Not verifiable from the diff (⚠️):** - How `FenceAndStopAs` returning `ErrStopUnproven` interacts with the real activator's `Quiesced` after an agent restart (`demo_claim_executor.go:157,166`). Only fakes cover it. - Whether systemd's mount of the snapshot disk propagates into instance-control's own mount namespace (that service runs with `ProtectSystem=strict` and `StateDirectory`). - What writing up to 256 MiB through instance-control does to its page cache under `MemoryMax=64M`. - **Requirements resting ONLY on the gated tests** (`CARLOS_DEMO_CLAIM_DEV_WITNESS=1`: `TestDemoClaimFreezeDevWitness`, `TestDemoClaimSnapshotUnitDevWitness`, `TestDemoClaimSnapshotRuntimeDevWitness`): - real cgroup stop proof for freeze, and zero data reads after an unproven stop on a real box; - helper memory ≤256 MiB and OOM kill, `RuntimeMaxSec` ≤120 s, and descendants killed; - the 768 MiB scratch reservation actually enforced (fallocate, mkfs.ext4, loop mount, ENOSPC); - credentials and sibling data unreachable; network and control sockets denied; - "cancel leaves no helper or scratch" against real systemd; - the effective-unit property readback matching systemd 257's exact `show` formatting. ## 2) Findings ### P1-1. ABBA deadlock between the snapshot door and demo purge (lock ordering, root availability) **Evidence:** - The snapshot handler takes `buildPurge` exclusively through `AcquireSnapshot` (`internal/instancectl/demo_snapshot.go:148`, `internal/demobuild/snapshot_slot.go:8`). - While holding it, the handler calls `snapshotHeld` again at `demo_snapshot.go:217` and `:236`. `snapshotHeld` enters `s.DemoPurgeGuard` (`:70`). - In production that guard is `instanceDemoPurgeGuard` (`internal/host/claimstop_run.go:276`). It takes `lockAdoptPass`, which is a blocking `syscall.Flock(LOCK_EX)` (`internal/host/flock_unix.go:13`) and ignores the context. - Purge locks in the opposite order: `handleDemoPurge` → `DemoPurgeGuard` (adopt flock) → `lockDemo` (`demo_cleanup.go:85`) → `PurgeDemo` (`:102`) → `buildPurge.Lock()` (`internal/demobuild/purge.go:21`). **Failure scenario:** 1. An export is running. That is up to 120 s, and includes the case where the source demo expires mid-export, which the plan explicitly expects ("source expiry still wins"). 2. A retirement purge with jobs arrives for any demo on the box. 3. Purge takes the adopt flock and blocks on `buildPurge`. 4. The snapshot handler reaches its recheck and blocks on the flock. 5. Both goroutines hang forever. The 120 s socket deadlines cannot interrupt either a flock or a `sync.RWMutex`. **Impact:** the adopt-pass lock stays held until instance-control restarts. Every adopt, stage, restart and config-sync pass on the box hangs, along with builds, purges and readiness (`recoverPurge` also takes `buildPurge.Lock`). **Fix:** never take `DemoPurgeGuard` while holding `buildPurge`. Either: - recheck under `lockDemo` plus `HostDemo` only, after the slot is held; or - acquire the snapshot slot inside one `DemoPurgeGuard` scope held for the whole export. Add a test that runs a purge with jobs concurrently with an export, using the production guard's lock order. ### P1-2. Any snapshot-recovery or template-check failure kills root control on the box (blast radius, "capability only when fully wired") **Evidence:** - `Serve` returns the error from `s.snapshots.initialize(ctx)` (`internal/instancectl/server.go:378`). `runWithClaim` then calls `log.Fatalf` (`:366`). - `initialize` (`demo_snapshot.go:449-510`) fails on many things: a missing or non-0700 `/var/lib/carlos-demo-snapshots`, any unexpected entry or unit name, any cleanup failure such as a busy unmount, or any `checkUnit` property mismatch. **Failure scenario:** a demo box gets the new binary before its `carlos-instance-control.service` gains `StateDirectory`. Note `ensureSystemUnits` only installs missing units. Or the snapshot template is absent, or real systemd formats one of the ~45 asserted properties differently, or a leftover mount won't unmount. Then instance-control crash-loops: no `/start`, `/stop`, purge or builds for every Plan 1/2 demo on the box. This happens even though `CARLOS_DEMO_CLAIM` is off, because the root side runs whenever `DemoBox` is set. **Fix:** log the failure, leave `ready` false (so no claim capability is advertised), and keep serving. Retry recovery from the readiness path if desired. ### P2-1. WAL check refuses legitimate WALs that contain stale frames (snapshot correctness) **Evidence:** `checkWALBounds` (`internal/democlaim/snapshot.go:186-208`) requires every frame in the file to match the header salt and continue the checksum chain, and requires the file size to be a whole number of frames (`:173`). **Why that is wrong:** SQLite reuses a WAL from the start after a checkpoint, with new salts, and does not truncate it unless `journal_size_limit` is set. Frames past the last valid commit therefore normally carry the old salt. A process killed between SQLite's frame-header write and page write also leaves a torn tail. **Failure scenario:** a demo app that has passed one auto-checkpoint and is stopped without a clean close always fails export with `DEMO-CLAIM-SNAPSHOT`. It fails closed, but claims will not work for a common class of apps. **Fix:** follow SQLite's recovery rule. Validate the prefix up to the first frame with a salt or checksum mismatch, or a partial frame, and apply the page-number bound only within that prefix. Frames past that point are not committed data by SQLite's own definition. Add a test with a reused WAL and a torn tail. ### P3 (follow-up list) - **P3-1. A failed snapshot cleanup does not block builds for long** (one-export-per-box budget). `release(false)` poisons the builder, but `recoverPurge` clears the poison by running the build cleanup, not the snapshot reap (`snapshot_slot.go:99-107`, `purge.go:66-89`). Builds can resume while the helper's stop is unproven. Exports stay off because `p.ready` is false. Keep builds poisoned until the snapshot unit is proven stopped. - **P3-2. The close door can fill the session table** (control-socket DoS). It registers placeholder sessions for unknown transfer IDs (`demo_snapshot.go:295-300`). Any vetted peer can fill all 64 slots and refuse exports for about 150 s. - **P3-3. A failed hold restore still advertises claim capability** (capability gating). `Connect` closes serving when `restoreDemoClaimHolds` fails (`demo_jobs.go:425-434`), but `demoClaimCapability` stays advertised. Clear it on recovery failure. - **P3-4. The agent's digest check runs after the console has accepted the upload** (verification order). `uploadDemoClaimHTTP` wraps the body in `LimitReader(size)` (`internal/host/demo_claim.go:85`), so the body's hash check only runs at `Close`, after the console's 204. It is safe only because the contract says the console verifies the digest itself; Task 5 must actually do that. ### Root census: new root reads and actions (for the R9 overlay) - **`/demo-freeze`:** reads the route via `HostDemo` (written by the agent, as for purge), stats the cgroup parent, and runs `systemctl list-units`/`show`. It reads the `ExeRoot` and `DropInDir` directories (shared `stopDemoUnits`) and checks `cgroup.events`. It reads no data files. - **`/demo-snapshot`:** - reads `HostDemo` three times and runs `Statfs` on the snapshot root; - writes `/run/systemd/system/<escaped>.mount`, whose content uses only paths built from a validated job ID; - runs `/usr/sbin/mkfs.ext4` on an image root itself created; - reads `/proc/self/mountinfo` and `system.slice/carlos-demo-snapshot@<id>.service/cgroup.events`; - **after reaping the helper, reads files the helper wrote:** `work/result.json` (≤1 KiB, strict JSON, `openat2` without following symlinks, regular file only, `O_NONBLOCK`, so a FIFO is safe) and `work/snapshot.db` (`OpenSource`: link count 1, unchanged check, re-hashed). - **Restart recovery:** `ReadDir` of the snapshot root, `list-units` with a pattern, and `os.Root.RemoveAll` of validated IDs. **Assessment:** root never runs SQLite, never opens a path an agent or tenant supplies, and never follows a symlink. The helper-written reads are what the brief requires ("result.json validated independently and re-hashed") and are adequately constrained. I am not raising them as P1. No existing root check is weakened: the `stopDemoUnits` extraction keeps purge's checks and their order. ## 3) Strengths - Work is tightly bound to box, fleet, lifetime, generation and action, with strict JSON and domain-separated Ed25519 signatures. Freeze and export deadlines are capped at demo expiry, and abort gets a fresh 30-second window. - Pickup is authenticated and re-checked before the hold, before export and before ack. Abort requires `RollbackProven`, an absent record hold, an unexpired demo and its own hold. - The persistent hold covers every path: `RouteFor`/`mintHeld`, `holdExisting`, `demoFixed`, `TombstoneBody`, `AssertDemoRoute`, `demoJobAllowed`, `convergeAdopted`, the root `/start` gate and retirement's `HandHold`. - Source files are opened without following symlinks, with link-count and unchanged-file checks. Missing DB, empty DB and over-256 MiB are refused, and there is no empty fallback. - Fixed multipart fields with no filenames, declared-length streaming, the loop-image disk reservation and an exact unit-property readback. ## 4) Verdict: NOT READY The P1s are P1-1 (snapshot/purge deadlock) and P1-2 (fatal snapshot initialization takes down instance-control). P2-1 (WAL stale-frame refusal) should be fixed in the same round. Files: - /home/paulca/amadan.net/carlos/platform/.claude/worktrees/agent-start-demo-3/internal/instancectl/demo_snapshot.go - /home/paulca/amadan.net/carlos/platform/.claude/worktrees/agent-start-demo-3/internal/instancectl/server.go - /home/paulca/amadan.net/carlos/platform/.claude/worktrees/agent-start-demo-3/internal/democlaim/snapshot.go - /home/paulca/amadan.net/carlos/platform/.claude/worktrees/agent-start-demo-3/internal/demobuild/snapshot_slot.go - /home/paulca/amadan.net/carlos/platform/.claude/worktrees/agent-start-demo-3/internal/host/claimstop_run.go</result> <usage><subagent_tokens>190930</subagent_tokens><tool_uses>38</tool_uses><duration_ms>486170</duration_ms></usage> </task-notification>
Attributed to this commit: 12.0 g CO₂e (1,390,824 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/purge.go b/internal/demobuild/purge.go| index 7b9e38e1d..6c90515b5 100644 |
| --- a/internal/demobuild/purge.go |
| +++ b/internal/demobuild/purge.go |
| @@ -66,8 +66,11 @@ func (w *Worker) PurgeDemo(ctx context.Context, demoID, host string, ids []strin |
| // cannot make a poisoned worker available while any build is still active. |
| func (w *Worker) recoverPurge(ctx context.Context) error { |
| w.mu.Lock() |
| - poisoned := w.poisoned |
| + poisoned, snapshotPoisoned := w.poisoned, w.snapshotPoisoned |
| w.mu.Unlock() |
| + if snapshotPoisoned { |
| + return ErrBuild |
| + } |
| if !poisoned { |
| return nil |
| } |
diff --git a/internal/demobuild/snapshot_slot.go b/internal/demobuild/snapshot_slot.go| index f8f738709..b242f85f4 100644 |
| --- a/internal/demobuild/snapshot_slot.go |
| +++ b/internal/demobuild/snapshot_slot.go |
| @@ -21,10 +21,26 @@ func (w *Worker) AcquireSnapshot(ctx context.Context) (func(bool), error) { |
| return func(clean bool) { |
| if !clean { |
| w.mu.Lock() |
| - w.poisoned = true |
| + w.snapshotPoisoned = true |
| w.mu.Unlock() |
| } |
| <-w.slots |
| w.buildPurge.Unlock() |
| }, nil |
| } |
| + |
| +// RecoverSnapshots keeps build admission closed until snapshot-specific recovery |
| +// proves the helper stopped and removes its scratch. Build cleanup cannot do so. |
| +func (w *Worker) RecoverSnapshots(ctx context.Context, reap func(context.Context) error) error { |
| + if !w.buildPurge.TryLock() { |
| + return ErrBuild |
| + } |
| + defer w.buildPurge.Unlock() |
| + if err := reap(ctx); err != nil { |
| + return err |
| + } |
| + w.mu.Lock() |
| + w.snapshotPoisoned = false |
| + w.mu.Unlock() |
| + return nil |
| +} |
diff --git a/internal/demobuild/snapshot_slot_test.go b/internal/demobuild/snapshot_slot_test.go| index 5ba3c39b8..d531c6666 100644 |
| --- a/internal/demobuild/snapshot_slot_test.go |
| +++ b/internal/demobuild/snapshot_slot_test.go |
| @@ -35,3 +35,42 @@ func TestDemoClaimExportBuilderSlot(t *testing.T) { |
| t.Fatal("failed snapshot cleanup did not poison builder") |
| } |
| } |
| + |
| +func TestDemoClaimSnapshotPoisonSurvivesBuildRecovery(t *testing.T) { |
| + buildCleanups := 0 |
| + w := &Worker{ready: true, slots: make(chan struct{}, 1), proof: func(context.Context) error { return nil }, retryCleanup: func(context.Context) error { buildCleanups++; return nil }} |
| + release, err := w.AcquireSnapshot(t.Context()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + release(false) |
| + if err := w.recoverPurge(t.Context()); err == nil || w.available() { |
| + t.Fatal("build cleanup cleared poison without proving the snapshot stopped") |
| + } |
| + if buildCleanups != 0 { |
| + t.Fatal("snapshot recovery used build cleanup") |
| + } |
| + if err := w.RecoverSnapshots(t.Context(), func(context.Context) error { return ErrBuild }); err == nil || w.available() { |
| + t.Fatal("failed snapshot reap reopened builds") |
| + } |
| + // Independent build poison must survive successful snapshot recovery too. |
| + w.poisoned = true |
| + if err := w.RecoverSnapshots(t.Context(), func(ctx context.Context) error { |
| + if release, err := w.AcquireSnapshot(ctx); err == nil { |
| + release(true) |
| + t.Fatal("export overlapped recovery") |
| + } |
| + if w.available() { |
| + t.Fatal("builds admitted before snapshot reap completed") |
| + } |
| + return nil |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + if w.available() { |
| + t.Fatal("snapshot recovery cleared independent build poison") |
| + } |
| + if err := w.recoverPurge(t.Context()); err != nil || !w.available() || buildCleanups != 1 { |
| + t.Fatal("recovery did not reopen after both cleanups", err, buildCleanups) |
| + } |
| +} |
diff --git a/internal/demobuild/worker.go b/internal/demobuild/worker.go| index 1c13da7f3..07552b905 100644 |
| --- a/internal/demobuild/worker.go |
| +++ b/internal/demobuild/worker.go |
| @@ -47,6 +47,8 @@ type Worker struct { |
| ready bool |
| initMu sync.Mutex |
| initDone bool |
| + |
| + snapshotPoisoned bool |
| } |
| func NewWorker(getenv func(string) string, proof func(context.Context) error) (*Worker, error) { |
| @@ -144,7 +146,7 @@ func (w *Worker) available() bool { |
| } |
| w.mu.Lock() |
| defer w.mu.Unlock() |
| - return w.ready && !w.poisoned |
| + return w.ready && !w.poisoned && !w.snapshotPoisoned |
| } |
| func (w *Worker) Close() error { |
diff --git a/internal/democlaim/snapshot.go b/internal/democlaim/snapshot.go| index 0c673e0e1..eb5bf6bb3 100644 |
| --- a/internal/democlaim/snapshot.go |
| +++ b/internal/democlaim/snapshot.go |
| @@ -146,10 +146,11 @@ func copySnapshotFile(ctx context.Context, path string, r io.Reader, size int64) |
| } |
| // A small WAL can name a huge page number. Refuse that before SQLite can |
| -// grow the private DB while checkpointing. Validate every checksum too: |
| -// SQLite can silently discard an invalid WAL, losing committed source data. |
| +// grow the private DB while checkpointing. Match SQLite recovery: validate |
| +// the header, then stop at the first invalid or partial frame. Trim this private |
| +// copy to the last valid commit so SQLite sees exactly that committed prefix. |
| func checkWALBounds(ctx context.Context, path string) error { |
| - f, err := os.Open(path) |
| + f, err := os.OpenFile(path, os.O_RDWR, 0) |
| if errors.Is(err, os.ErrNotExist) { |
| return nil |
| } |
| @@ -170,7 +171,7 @@ func checkWALBounds(ctx context.Context, path string) error { |
| } |
| magic := binary.BigEndian.Uint32(header[0:4]) |
| page := int64(binary.BigEndian.Uint32(header[8:12])) |
| - if (magic != 0x377f0682 && magic != 0x377f0683) || binary.BigEndian.Uint32(header[4:8]) != 3007000 || page < 512 || page > 65536 || page&(page-1) != 0 || (st.Size()-32)%(page+24) != 0 { |
| + if (magic != 0x377f0682 && magic != 0x377f0683) || binary.BigEndian.Uint32(header[4:8]) != 3007000 || page < 512 || page > 65536 || page&(page-1) != 0 { |
| return ErrSnapshot |
| } |
| var order binary.ByteOrder = binary.LittleEndian |
| @@ -183,19 +184,16 @@ func checkWALBounds(ctx context.Context, path string) error { |
| } |
| data := make([]byte, page) |
| var frame [24]byte |
| - for offset := int64(32); offset < st.Size(); offset += page + 24 { |
| + committedEnd := int64(32) |
| + for offset := int64(32); offset+page+24 <= st.Size(); offset += page + 24 { |
| if err = ctx.Err(); err != nil { |
| return err |
| } |
| if _, err = f.ReadAt(frame[:], offset); err != nil { |
| return err |
| } |
| - pg, commit := int64(binary.BigEndian.Uint32(frame[0:4])), int64(binary.BigEndian.Uint32(frame[4:8])) |
| - if pg == 0 || pg > MaxSnapshotBytes/page || commit > MaxSnapshotBytes/page { |
| - return ErrSnapshot |
| - } |
| if !bytes.Equal(frame[8:16], header[16:24]) { |
| - return ErrSnapshot |
| + break |
| } |
| if _, err = f.ReadAt(data, offset+24); err != nil { |
| return err |
| @@ -203,8 +201,18 @@ func checkWALBounds(ctx context.Context, path string) error { |
| s0, s1 = litestream.WALChecksum(order, s0, s1, frame[:8]) |
| s0, s1 = litestream.WALChecksum(order, s0, s1, data) |
| if s0 != binary.BigEndian.Uint32(frame[16:20]) || s1 != binary.BigEndian.Uint32(frame[20:24]) { |
| + break |
| + } |
| + pg, commit := int64(binary.BigEndian.Uint32(frame[0:4])), int64(binary.BigEndian.Uint32(frame[4:8])) |
| + if pg == 0 || pg > MaxSnapshotBytes/page || commit > MaxSnapshotBytes/page { |
| return ErrSnapshot |
| } |
| + if commit != 0 { |
| + committedEnd = offset + page + 24 |
| + } |
| + } |
| + if err := ctx.Err(); err != nil { |
| + return err |
| } |
| - return nil |
| + return f.Truncate(committedEnd) |
| } |
diff --git a/internal/democlaim/snapshot_test.go b/internal/democlaim/snapshot_test.go| index 88664fe99..3abcb66dc 100644 |
| --- a/internal/democlaim/snapshot_test.go |
| +++ b/internal/democlaim/snapshot_test.go |
| @@ -3,6 +3,7 @@ |
| package democlaim |
| import ( |
| + "bytes" |
| "context" |
| "crypto/sha256" |
| "database/sql" |
| @@ -12,6 +13,7 @@ import ( |
| "path/filepath" |
| "testing" |
| + "github.com/benbjohnson/litestream" |
| "golang.org/x/sys/unix" |
| _ "modernc.org/sqlite" |
| ) |
| @@ -122,14 +124,14 @@ func TestDemoClaimSnapshotWAL(t *testing.T) { |
| } |
| func TestDemoClaimExportBounded(t *testing.T) { |
| - t.Run("corruptWALCannotDisappear", func(t *testing.T) { |
| + t.Run("corruptWALHeaderCannotDisappear", func(t *testing.T) { |
| dir := walFixture(t) |
| p := filepath.Join(dir, "source.db-wal") |
| b, err := os.ReadFile(p) |
| if err != nil { |
| t.Fatal(err) |
| } |
| - b[len(b)-1] ^= 1 |
| + b[24] ^= 1 |
| if err = os.WriteFile(p, b, 0600); err != nil { |
| t.Fatal(err) |
| } |
| @@ -145,6 +147,16 @@ func TestDemoClaimExportBounded(t *testing.T) { |
| t.Fatal(err) |
| } |
| binary.BigEndian.PutUint32(b[32:36], 0x7fffffff) |
| + // Keep this frame valid so the page bound, not recovery, rejects it. |
| + var order binary.ByteOrder = binary.LittleEndian |
| + if binary.BigEndian.Uint32(b[:4]) == 0x377f0683 { |
| + order = binary.BigEndian |
| + } |
| + s0, s1 := binary.BigEndian.Uint32(b[24:28]), binary.BigEndian.Uint32(b[28:32]) |
| + s0, s1 = litestream.WALChecksum(order, s0, s1, b[32:40]) |
| + s0, s1 = litestream.WALChecksum(order, s0, s1, b[56:]) |
| + binary.BigEndian.PutUint32(b[48:52], s0) |
| + binary.BigEndian.PutUint32(b[52:56], s1) |
| if err = os.WriteFile(p, b, 0600); err != nil { |
| t.Fatal(err) |
| } |
| @@ -180,3 +192,85 @@ func TestDemoClaimExportBounded(t *testing.T) { |
| } |
| }) |
| } |
| + |
| +func TestDemoClaimSnapshotWALRecoveryPrefix(t *testing.T) { |
| + for _, tail := range []string{"reused", "torn", "checksum", "uncommitted", "corruptHeader"} { |
| + t.Run(tail, func(t *testing.T) { |
| + dir := t.TempDir() |
| + path := filepath.Join(dir, "source.db") |
| + db, err := sql.Open("sqlite", path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer db.Close() |
| + db.SetMaxOpenConns(1) |
| + exec := func(q string) { |
| + t.Helper() |
| + if _, err := db.Exec(q); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for _, q := range []string{"PRAGMA journal_mode=WAL", "PRAGMA wal_autocheckpoint=0", "CREATE TABLE items(value TEXT)", "PRAGMA wal_checkpoint(TRUNCATE)", "INSERT INTO items VALUES ('first')", "INSERT INTO items VALUES ('second')", "INSERT INTO items VALUES ('third')", "PRAGMA wal_checkpoint(FULL)", "INSERT INTO items VALUES ('latest')"} { |
| + exec(q) |
| + } |
| + wal, err := os.ReadFile(path + "-wal") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + frameBytes := int(binary.BigEndian.Uint32(wal[8:12])) + 24 |
| + prefix := 32 + frameBytes |
| + if len(wal) < prefix+frameBytes || bytes.Equal(wal[16:24], wal[prefix+8:prefix+16]) { |
| + t.Fatal("fixture lacks reused stale-salt tail") |
| + } |
| + switch tail { |
| + case "torn": |
| + wal = append(wal[:prefix], wal[32:32+frameBytes/2]...) |
| + case "checksum": |
| + wal = append(wal[:prefix], wal[32:prefix]...) |
| + // Invalid frames must not trigger the valid-prefix page bound. |
| + binary.BigEndian.PutUint32(wal[prefix:prefix+4], 0x7fffffff) |
| + case "uncommitted": |
| + wal = append(wal[:prefix], wal[32:prefix]...) |
| + binary.BigEndian.PutUint32(wal[prefix+4:prefix+8], 0) |
| + wal[len(wal)-1] ^= 1 |
| + var order binary.ByteOrder = binary.LittleEndian |
| + if binary.BigEndian.Uint32(wal[:4]) == 0x377f0683 { |
| + order = binary.BigEndian |
| + } |
| + s0, s1 := binary.BigEndian.Uint32(wal[48:52]), binary.BigEndian.Uint32(wal[52:56]) |
| + s0, s1 = litestream.WALChecksum(order, s0, s1, wal[prefix:prefix+8]) |
| + s0, s1 = litestream.WALChecksum(order, s0, s1, wal[prefix+24:]) |
| + binary.BigEndian.PutUint32(wal[prefix+16:prefix+20], s0) |
| + binary.BigEndian.PutUint32(wal[prefix+20:prefix+24], s1) |
| + case "corruptHeader": |
| + wal[24] ^= 1 |
| + } |
| + if err := os.WriteFile(path+"-wal", wal, 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + beforeDB, beforeWAL := fileHash(t, path), fileHash(t, path+"-wal") |
| + s, err := ExportSQLite(t.Context(), dir, "source.db", t.TempDir()) |
| + if tail == "corruptHeader" { |
| + if err == nil { |
| + t.Fatal("corrupt WAL header accepted") |
| + } |
| + return |
| + } |
| + if err != nil { |
| + t.Fatal("recoverable WAL refused:", err) |
| + } |
| + out, err := sql.Open("sqlite", "file:"+s.Path+"?mode=ro") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer out.Close() |
| + var rows string |
| + if err := out.QueryRow("SELECT group_concat(value, ',') FROM items").Scan(&rows); err != nil || rows != "first,second,third,latest" { |
| + t.Fatalf("committed rows=%q err=%v", rows, err) |
| + } |
| + if beforeDB != fileHash(t, path) || beforeWAL != fileHash(t, path+"-wal") { |
| + t.Fatal("source modified") |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/host/demo_claim_executor_test.go b/internal/host/demo_claim_executor_test.go| index e41c86655..86e43b6f0 100644 |
| --- a/internal/host/demo_claim_executor_test.go |
| +++ b/internal/host/demo_claim_executor_test.go |
| @@ -526,3 +526,53 @@ func TestDemoClaimFreezeAbortCancelledKeepsHold(t *testing.T) { |
| t.Fatal("cancelled abort lifted hold") |
| } |
| } |
| + |
| +func TestDemoClaimRecoveryFailureClearsCapability(t *testing.T) { |
| + for _, fail := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "recovered", true: "failed"}[fail], func(t *testing.T) { |
| + f := newClaimFixture(t) |
| + f.w.cfg.BuildConcurrency = 1 |
| + if fail { |
| + if err := f.w.reg.SetHold(f.rec.Host, "moving", "demo-claim/invalid"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.w.restoreDemoClaimHolds(t.Context()); err == nil { |
| + t.Fatal("fixture did not fail hold recovery") |
| + } |
| + } |
| + f.w.readiness = func(context.Context) (demobuild.WorkerReady, error) { |
| + return demobuild.WorkerReady{Capability: "anonymous-demo-v1", ClaimCapability: democlaim.Capability, GOARCH: "arm64", Slots: 1, BundleSHA256: strings.Repeat("b", 64)}, nil |
| + } |
| + observed := make(chan demobuild.WorkerReady, 1) |
| + stream := interactive.NewServer(func(ws *websocket.Conn) { |
| + defer ws.Close() |
| + deadline := time.NewTimer(time.Second) |
| + defer deadline.Stop() |
| + tick := time.NewTicker(time.Millisecond) |
| + defer tick.Stop() |
| + for !f.w.buildReady().Valid() { |
| + select { |
| + case <-deadline.C: |
| + return |
| + case <-tick.C: |
| + } |
| + } |
| + observed <- f.w.demoHeartbeat(time.Now()) |
| + }) |
| + srv := httptest.NewServer(stream) |
| + defer srv.Close() |
| + f.w.base = srv.URL |
| + ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second) |
| + defer cancel() |
| + _ = f.w.Connect(ctx) |
| + select { |
| + case got := <-observed: |
| + if (got.ClaimCapability == democlaim.Capability) == fail { |
| + t.Fatalf("recovery failed=%v, advertised claim capability %q", fail, got.ClaimCapability) |
| + } |
| + default: |
| + t.Fatal("root readiness was not observed") |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/host/demo_jobs.go b/internal/host/demo_jobs.go| index 934e1e8be..c791c262c 100644 |
| --- a/internal/host/demo_jobs.go |
| +++ b/internal/host/demo_jobs.go |
| @@ -477,6 +477,9 @@ func (w *demoWorker) Connect(ctx context.Context) error { |
| if err != nil || !ready.Valid() || ready.Slots != w.cfg.BuildConcurrency { |
| ready = demobuild.WorkerReady{} |
| } |
| + if !recoveryOK { |
| + ready.ClaimCapability = "" |
| + } |
| w.readyMu.Lock() |
| w.ready = ready |
| w.readyMu.Unlock() |
diff --git a/internal/instancectl/demo_build.go b/internal/instancectl/demo_build.go| index 739ec3a4c..f62a35127 100644 |
| --- a/internal/instancectl/demo_build.go |
| +++ b/internal/instancectl/demo_build.go |
| @@ -93,6 +93,9 @@ func (s *Server) handleDemoBuildReady(w http.ResponseWriter, r *http.Request) { |
| http.Error(w, demobuild.ErrBuild.Error(), http.StatusServiceUnavailable) |
| return |
| } |
| + if s.snapshots != nil { |
| + s.snapshots.ensureReady(r.Context()) |
| + } |
| ready, err := s.DemoBuilder.Readiness(r.Context()) |
| if err != nil { |
| http.Error(w, demobuild.ErrBuild.Error(), http.StatusServiceUnavailable) |
diff --git a/internal/instancectl/demo_snapshot.go b/internal/instancectl/demo_snapshot.go| index 5b243e830..eaff27c8a 100644 |
| --- a/internal/instancectl/demo_snapshot.go |
| +++ b/internal/instancectl/demo_snapshot.go |
| @@ -45,6 +45,8 @@ type demoSnapshotSupervisor struct { |
| assertUnit func(context.Context, string) error |
| empty func(string) error |
| ready, busy atomic.Bool |
| + initMu sync.Mutex |
| + nextInit time.Time |
| mu sync.Mutex |
| sessions map[string]*snapshotSession |
| } |
| @@ -59,6 +61,7 @@ func newDemoSnapshotSupervisor(s *Server) *demoSnapshotSupervisor { |
| } |
| func snapshotUnit(id string) string { return "carlos-demo-snapshot@" + id + ".service" } |
| +// snapshotHeld rechecks the registry under lockDemo; its caller holds DemoPurgeGuard. |
| func (s *Server) snapshotHeld(ctx context.Context, in demoSnapshotRequest) error { |
| if !s.DemoBox || s.HostDemo == nil || s.DemoPurgeGuard == nil || !s.DemoConfig.BoxMode() || !demobuild.ValidJobID(in.OperationID) || !provision.ValidHostShape(in.Demo.Host) || ctx.Err() != nil { |
| return demo.ErrPolicy |
| @@ -67,17 +70,15 @@ func (s *Server) snapshotHeld(ctx context.Context, in demoSnapshotRequest) error |
| if !ok || s.DemoConfig.ValidateBinding(in.Demo, s.DemoConfig.Account, demo.AppPrefix+name, in.Demo.Host, in.Demo.Lifetime, s.DemoConfig.Fleet) != nil || time.Now().Unix() >= in.Demo.ExpiresAt { |
| return demo.ErrPolicy |
| } |
| - return s.DemoPurgeGuard(ctx, func() error { |
| - defer s.lockDemo(in.Demo.Host)() |
| - rt, err := s.HostDemo(in.Demo.Host) |
| - if err != nil { |
| - return err |
| - } |
| - if rt == nil || !rt.IsDemo() || rt.Host != in.Demo.Host || rt.DemoID != in.Demo.ID || rt.DemoHost != in.Demo.Host || rt.DemoLifetime != in.Demo.Lifetime || rt.DemoExpiresAt != in.Demo.ExpiresAt || rt.Account != s.DemoConfig.Account || rt.App != demo.AppPrefix+name || rt.Status != "moving" || rt.HoldOp != "demo-claim/"+in.OperationID { |
| - return demo.ErrPolicy |
| - } |
| - return nil |
| - }) |
| + defer s.lockDemo(in.Demo.Host)() |
| + rt, err := s.HostDemo(in.Demo.Host) |
| + if err != nil { |
| + return err |
| + } |
| + if rt == nil || !rt.IsDemo() || rt.Host != in.Demo.Host || rt.DemoID != in.Demo.ID || rt.DemoHost != in.Demo.Host || rt.DemoLifetime != in.Demo.Lifetime || rt.DemoExpiresAt != in.Demo.ExpiresAt || rt.Account != s.DemoConfig.Account || rt.App != demo.AppPrefix+name || rt.Status != "moving" || rt.HoldOp != "demo-claim/"+in.OperationID { |
| + return demo.ErrPolicy |
| + } |
| + return nil |
| } |
| func snapshotPart(m *multipart.Reader, name string) (*multipart.Part, error) { |
| p, err := m.NextRawPart() |
| @@ -93,7 +94,7 @@ func snapshotPart(m *multipart.Reader, name string) (*multipart.Part, error) { |
| func (s *Server) handleDemoSnapshot(w http.ResponseWriter, r *http.Request) { |
| defer r.Body.Close() |
| p := s.snapshots |
| - if p == nil || !p.ready.Load() { |
| + if p == nil || !p.ensureReady(r.Context()) { |
| http.Error(w, democlaim.ErrSnapshot.Error(), 503) |
| return |
| } |
| @@ -131,7 +132,26 @@ func (s *Server) handleDemoSnapshot(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| defer close(session.done) |
| - if err = s.snapshotHeld(ctx, in); err != nil { |
| + if s.DemoPurgeGuard == nil { |
| + http.Error(w, democlaim.ErrSnapshot.Error(), 409) |
| + return |
| + } |
| + // Take the adopt guard before the snapshot/buildPurge slot and retain it |
| + // through response cleanup. Purge takes adopt -> lockDemo -> buildPurge; |
| + // this outer guard serializes both paths, including the lockDemo rechecks. |
| + // Never reacquire the adopt guard while holding the snapshot slot. |
| + if err = s.DemoPurgeGuard(ctx, func() error { |
| + s.exportDemoSnapshot(ctx, w, m, in, session) |
| + return nil |
| + }); err != nil { |
| + http.Error(w, democlaim.ErrSnapshot.Error(), 409) |
| + } |
| +} |
| + |
| +// The caller holds DemoPurgeGuard until all export defers have finished. |
| +func (s *Server) exportDemoSnapshot(ctx context.Context, w http.ResponseWriter, m *multipart.Reader, in demoSnapshotRequest, session *snapshotSession) { |
| + p := s.snapshots |
| + if err := s.snapshotHeld(ctx, in); err != nil { |
| http.Error(w, democlaim.ErrSnapshot.Error(), 409) |
| return |
| } |
| @@ -292,12 +312,6 @@ func (s *Server) handleDemoSnapshotClose(w http.ResponseWriter, r *http.Request) |
| p.mu.Lock() |
| p.prune() |
| session := p.sessions[in.TransferID] |
| - if session == nil && len(p.sessions) < 64 { |
| - // Remember an early cancellation before a delayed POST can register. |
| - session = &snapshotSession{op: in.OperationID, done: make(chan struct{}), created: time.Now(), cancel: func() {}} |
| - close(session.done) |
| - p.sessions[in.TransferID] = session |
| - } |
| p.mu.Unlock() |
| if session == nil || session.op != in.OperationID { |
| http.Error(w, democlaim.ErrSnapshot.Error(), 409) |
| @@ -446,6 +460,42 @@ func (p *demoSnapshotSupervisor) result(ctx context.Context, id string) (*democl |
| } |
| return source, democlaim.Snapshot{SHA256: meta.SHA256, Bytes: meta.Bytes}, nil |
| } |
| + |
| +// Retry only on demand. Serialize recovery with exports and the builder slot: |
| +// a readiness probe must never reap the helper of an active export. |
| +func (p *demoSnapshotSupervisor) ensureReady(ctx context.Context) bool { |
| + if p.ready.Load() { |
| + return true |
| + } |
| + if !p.initMu.TryLock() { |
| + return false |
| + } |
| + defer p.initMu.Unlock() |
| + if p.ready.Load() { |
| + return true |
| + } |
| + if time.Now().Before(p.nextInit) || !p.busy.CompareAndSwap(false, true) { |
| + return false |
| + } |
| + defer p.busy.Store(false) |
| + defer func() { p.nextInit = time.Now().Add(5 * time.Second) }() |
| + ctx, cancel := context.WithTimeout(ctx, p.stopWindow) |
| + defer cancel() |
| + var err error |
| + if recovery, ok := p.s.DemoBuilder.(interface { |
| + RecoverSnapshots(context.Context, func(context.Context) error) error |
| + }); ok { |
| + err = recovery.RecoverSnapshots(ctx, p.initialize) |
| + } else { |
| + err = p.initialize(ctx) |
| + } |
| + if err != nil { |
| + p.s.logf("instance-control: demo snapshot: %v", err) |
| + return false |
| + } |
| + return p.ready.Load() |
| +} |
| + |
| func (p *demoSnapshotSupervisor) initialize(ctx context.Context) error { |
| p.ready.Store(false) |
| root, err := instancefs.OpenRootBeneath(p.root, ".") |
| @@ -505,6 +555,9 @@ func (p *demoSnapshotSupervisor) initialize(ctx context.Context) error { |
| if err = p.assertUnit(ctx, strings.Repeat("A", 43)); err != nil { |
| return err |
| } |
| + if err := ctx.Err(); err != nil { |
| + return err |
| + } |
| p.ready.Store(true) |
| return nil |
| } |
diff --git a/internal/instancectl/demo_snapshot_fix_linux_test.go b/internal/instancectl/demo_snapshot_fix_linux_test.go| new file mode 100644 |
| index 000000000..40388fb32 |
| --- /dev/null |
| +++ b/internal/instancectl/demo_snapshot_fix_linux_test.go |
| @@ -0,0 +1,256 @@ |
| +//go:build linux |
| + |
| +package instancectl |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demobuild" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// This fixture uses the production adopt flock -> lockDemo -> buildPurge order. |
| +// The slot watchdog breaks the cycle on failure so the test can clean up. |
| +type snapshotPurgeBuilder struct { |
| + *snapshotBuilderFake |
| + slot chan struct{} |
| + waiting func() |
| +} |
| + |
| +func (b *snapshotPurgeBuilder) AcquireSnapshot(context.Context) (func(bool), error) { |
| + select { |
| + case b.slot <- struct{}{}: |
| + return func(bool) { <-b.slot }, nil |
| + default: |
| + return nil, demobuild.ErrBuild |
| + } |
| +} |
| +func (b *snapshotPurgeBuilder) PurgeDemo(_ context.Context, _, _ string, jobs []string) error { |
| + if len(jobs) != 1 { |
| + return errors.New("missing purge jobs") |
| + } |
| + b.waiting() |
| + select { |
| + case b.slot <- struct{}{}: |
| + <-b.slot |
| + return nil |
| + case <-time.After(time.Second): |
| + return errors.New("deadlock: purge waited for snapshot slot while holding adopt flock") |
| + } |
| +} |
| + |
| +func TestDemoClaimSnapshotPurgeLockOrder(t *testing.T) { |
| + f := newSnapshotFixture(t) |
| + f.s.DataRoot, f.s.DemoRunRoot, f.s.CgroupRoot = t.TempDir(), t.TempDir(), t.TempDir() |
| + other := f.d |
| + other.Host = "calm-otter-43.example.com" |
| + f.s.HostDemo = func(host string) (*registry.Route, error) { |
| + if host == other.Host { |
| + return nil, nil |
| + } |
| + return f.rt, nil |
| + } |
| + attempt := make(chan struct{}) |
| + var once sync.Once |
| + signal := func() { once.Do(func() { close(attempt) }) } |
| + b := &snapshotPurgeBuilder{snapshotBuilderFake: f.builder, slot: make(chan struct{}, 1), waiting: signal} |
| + f.s.DemoBuilder = b |
| + lockPath := filepath.Join(t.TempDir(), "adopt.lock") |
| + type purgeKey struct{} |
| + f.s.DemoPurgeGuard = func(ctx context.Context, effect func() error) error { |
| + lock, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0600) |
| + if err != nil { |
| + return err |
| + } |
| + defer lock.Close() |
| + err = unix.Flock(int(lock.Fd()), unix.LOCK_EX|unix.LOCK_NB) |
| + if errors.Is(err, unix.EWOULDBLOCK) { |
| + if ctx.Value(purgeKey{}) != nil { |
| + signal() |
| + } |
| + err = unix.Flock(int(lock.Fd()), unix.LOCK_EX) |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + defer unix.Flock(int(lock.Fd()), unix.LOCK_UN) |
| + return effect() |
| + } |
| + purged := make(chan int, 1) |
| + prepare := f.p.prepare |
| + f.p.prepare = func(ctx context.Context, id string) error { |
| + go func() { |
| + raw, _ := json.Marshal(DemoPurgeRequest{Demo: other, Jobs: []string{f.op}}) |
| + req := httptest.NewRequest("POST", "/demo-purge", bytes.NewReader(raw)).WithContext(context.WithValue(t.Context(), purgeKey{}, true)) |
| + out := httptest.NewRecorder() |
| + f.s.Handler().ServeHTTP(out, req) |
| + purged <- out.Code |
| + }() |
| + select { |
| + case <-attempt: |
| + case <-time.After(2 * time.Second): |
| + return errors.New("purge did not reach lock") |
| + } |
| + return prepare(ctx, id) |
| + } |
| + body, err := f.client.SnapshotDemo(t.Context(), f.d, f.op, strings.NewReader("data"), 4, nil, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + _, err = io.Copy(io.Discard, body) |
| + closeErr := body.Close() |
| + if err != nil || closeErr != nil { |
| + t.Fatal(err, closeErr) |
| + } |
| + select { |
| + case code := <-purged: |
| + if code != 204 { |
| + t.Fatalf("purge-with-jobs failed or deadlocked: HTTP %d", code) |
| + } |
| + case <-time.After(2 * time.Second): |
| + t.Fatal("purge/export deadlock") |
| + } |
| + f.noScratch(t) |
| +} |
| + |
| +func (b *snapshotBuilderFake) Initialize(context.Context) error { return nil } |
| + |
| +func TestDemoClaimSnapshotSoftInitialization(t *testing.T) { |
| + for _, fault := range []string{"missingRoot", "rootMode", "unexpectedEntry", "cleanup", "unitProperties"} { |
| + t.Run(fault, func(t *testing.T) { |
| + f := newSnapshotFixture(t) |
| + f.s.PeerOK = func(net.Conn) error { return nil } |
| + f.p.stopWindow = 500 * time.Millisecond |
| + f.s.Logf = t.Logf |
| + systemctl := f.s.Systemctl |
| + f.s.Systemctl = func(ctx context.Context, args ...string) (string, error) { |
| + if args[0] == "stop" && !strings.HasPrefix(args[len(args)-1], "carlos-demo-snapshot@") { |
| + return "", nil |
| + } |
| + return systemctl(ctx, args...) |
| + } |
| + f.s.DataRoot, f.s.DemoRunRoot, f.s.CgroupRoot = t.TempDir(), t.TempDir(), t.TempDir() |
| + var repair func() |
| + switch fault { |
| + case "missingRoot": |
| + root := f.p.root |
| + f.p.root = filepath.Join(root, "missing") |
| + repair = func() { |
| + if err := os.Mkdir(f.p.root, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + case "rootMode": |
| + os.Chmod(f.p.root, 0755) |
| + repair = func() { os.Chmod(f.p.root, 0700) } |
| + case "unexpectedEntry": |
| + path := filepath.Join(f.p.root, "unexpected") |
| + os.WriteFile(path, nil, 0600) |
| + repair = func() { os.Remove(path) } |
| + case "cleanup": |
| + os.Mkdir(filepath.Join(f.p.root, f.op), 0700) |
| + f.failStop = true |
| + repair = func() { f.mu.Lock(); f.failStop = false; f.mu.Unlock() } |
| + case "unitProperties": |
| + f.p.assertUnit = func(context.Context, string) error { return errors.New("unit format mismatch") } |
| + repair = func() { f.p.assertUnit = func(context.Context, string) error { return nil } } |
| + } |
| + f.p.ready.Store(false) |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer ln.Close() |
| + ctx, cancel := context.WithCancel(t.Context()) |
| + done := make(chan error, 1) |
| + go func() { done <- f.s.Serve(ctx, ln) }() |
| + defer func() { |
| + cancel() |
| + select { |
| + case <-done: |
| + case <-time.After(time.Second): |
| + t.Error("Serve did not stop") |
| + } |
| + }() |
| + client := &http.Client{Timeout: time.Second} |
| + defer client.CloseIdleConnections() |
| + base := "http://" + ln.Addr().String() |
| + request := func(method, path string, body io.Reader, want int) []byte { |
| + t.Helper() |
| + req, _ := http.NewRequest(method, base+path, body) |
| + res, err := client.Do(req) |
| + if err != nil { |
| + t.Fatalf("Serve unavailable after snapshot init failure: %v", err) |
| + } |
| + defer res.Body.Close() |
| + raw, _ := io.ReadAll(res.Body) |
| + if res.StatusCode != want { |
| + t.Fatalf("%s: HTTP %d, want %d: %s", path, res.StatusCode, want, raw) |
| + } |
| + return raw |
| + } |
| + // Existing start hold refusal and a successful stop still dispatch. |
| + request("POST", "/start?host="+f.d.Host+"&role=run&memory_max=536870912", nil, 409) |
| + request("POST", "/stop?host="+f.d.Host+"&role=run", nil, 204) |
| + absent := f.d |
| + absent.Host = "calm-otter-43.example.com" |
| + oldHost := f.s.HostDemo |
| + f.s.HostDemo = func(host string) (*registry.Route, error) { |
| + if host == absent.Host { |
| + return nil, nil |
| + } |
| + return oldHost(host) |
| + } |
| + raw, _ := json.Marshal(DemoPurgeRequest{Demo: absent}) |
| + request("POST", "/demo-purge", bytes.NewReader(raw), 204) |
| + request("POST", "/demo-snapshot", nil, 503) |
| + var ready demobuild.WorkerReady |
| + json.Unmarshal(request("GET", "/demo-build/ready", nil, 200), &ready) |
| + if ready.ClaimCapability != "" { |
| + t.Fatal("failed init advertised claims") |
| + } |
| + repair() |
| + // Retry is lazy and bounded; give its rate limit a chance to expire. |
| + deadline := time.Now().Add(7 * time.Second) |
| + for time.Now().Before(deadline) { |
| + json.Unmarshal(request("GET", "/demo-build/ready", nil, 200), &ready) |
| + if ready.ClaimCapability != "" { |
| + return |
| + } |
| + time.Sleep(100 * time.Millisecond) |
| + } |
| + t.Fatal("snapshot initialization was never retried") |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoClaimSnapshotCloseUnknownTransfer(t *testing.T) { |
| + f := newSnapshotFixture(t) |
| + for i := 0; i < 65; i++ { |
| + id, _ := demobuild.NewJobID() |
| + raw, _ := json.Marshal(demoSnapshotClose{OperationID: f.op, TransferID: id}) |
| + out := httptest.NewRecorder() |
| + f.s.Handler().ServeHTTP(out, httptest.NewRequest("POST", "/demo-snapshot/close", bytes.NewReader(raw))) |
| + if out.Code != 409 { |
| + t.Errorf("unknown close HTTP %d, want 409", out.Code) |
| + break |
| + } |
| + } |
| + if len(f.p.sessions) != 0 { |
| + t.Fatalf("unknown closes reserved %d sessions", len(f.p.sessions)) |
| + } |
| +} |
diff --git a/internal/instancectl/demo_snapshot_test.go b/internal/instancectl/demo_snapshot_test.go| index 205ef0eee..6872e57f3 100644 |
| --- a/internal/instancectl/demo_snapshot_test.go |
| +++ b/internal/instancectl/demo_snapshot_test.go |
| @@ -501,6 +501,9 @@ func TestDemoClaimSnapshotRootCapability(t *testing.T) { |
| f := newSnapshotFixture(t) |
| for _, ready := range []bool{true, false} { |
| f.p.ready.Store(ready) |
| + if !ready { |
| + f.p.assertUnit = func(context.Context, string) error { return democlaim.ErrSnapshot } |
| + } |
| out := httptest.NewRecorder() |
| f.s.Handler().ServeHTTP(out, httptest.NewRequest("GET", "/demo-build/ready", nil)) |
| var got demobuild.WorkerReady |
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go| index d2140745a..489bf476d 100644 |
| --- a/internal/instancectl/server.go |
| +++ b/internal/instancectl/server.go |
| @@ -375,9 +375,7 @@ func (s *Server) Serve(ctx context.Context, ln net.Listener) error { |
| ctx, cancel := context.WithCancel(ctx) |
| defer cancel() |
| if s.snapshots != nil { |
| - if err := s.snapshots.initialize(ctx); err != nil { |
| - return err |
| - } |
| + s.snapshots.ensureReady(ctx) |
| } |
| if s.DemoBuilder != nil { |
| done := make(chan struct{}) |