Repository navigation
Clean up orphaned VM data dirs from crashed VMs - #198
Conversation
When a VM crashes or the bbox process is killed (SIGKILL, OOM) before WithCleanDataDir() runs, the COW-cloned rootfs under ~/.config/broodbox/vms/<name>/data/rootfs-work/ survives — potentially hundreds of MB per orphan, accumulating unbounded. CleanupStaleLogs already removes a whole VM directory when its bbox sentinel's PID is dead, but no sentinel is written for runs that use --log-file, so those data clones leak. Add CleanupStaleVMData, keyed off go-microvm's per-VM state file (state.Manager.Load) rather than the sentinel: a data dir whose state is still active but whose runner PID is dead was orphaned and is reclaimed. A live runner PID is left untouched, so it is safe to run at startup alongside concurrent VMs. After removing the data dir it best-effort removes the now-empty parent (reclaiming sentinel-less --log-file runs) while leaving parents that still hold logs to CleanupStaleLogs. Wire it into the composition root next to CleanupStaleLogs and CleanupStaleSnapshots. Fixes #87 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VP887qH8BMW4PMUXBuEqGc
JAORMX
left a comment
There was a problem hiding this comment.
Panel review — 3 axes, 5 reviewers
Ran a three-axis panel review (Spec / Standards / Domain) with the Domain axis fanned out to secure-code-reviewer, software-architect, devops-expert, and library-reuse-reviewer. Findings are inline as line-anchored comments; summary below. (Submitting as COMMENT rather than REQUEST_CHANGES since GitHub doesn't allow requesting changes on your own PR — but please treat the High finding as a merge blocker.)
Spec — ✅ clean (with one scope-creep note)
All core requirements in issue #87 are satisfied (scan ~/.config/broodbox/vms/*/data/, check active: true + dead PID, remove orphaned data dirs, wire into internal/infra/vm/ called from cmd/bbox/main.go). The spec said state.json; the PR correctly uses state.Manager.Load() which reads go-microvm-state.json (the actual go-microvm filename) — an acceptable correction, not a mismatch. One scope-creep note: the os.Remove(vmDir) parent-prune is defensible (reclaims --log-file runs) but wasn't asked for; left as-is since it's the right call.
Standards — ✅ clean
SPDX headers present, log/slog exclusively, correct DDD layer (internal/infra/vm/, no domain/sandbox/client leakage, go-microvm/state import is consistent — internal/infra/vm/ is the go-microvm adapter), table-driven tests alongside code, imperative commit message.
Domain — 1 High ship-blocker, 4 Medium, 2 Low
Ship-blockers (1)
- [High]
CleanupStaleVMDataruns unconditionally at startup and silently defeats the documentedBBOX_KEEP_VM_DATA=1debug workflow — a crashed run'sdata/dir is exactly what the env var is meant to preserve, and this cleanup deletes it before the user can inspect.cmd/bbox/main.go:527.
Cross-confirmed (1)
- [Medium] TOCTOU between unlocked
state.Load()andos.RemoveAll— flagged independently by secure-code-reviewer, devops-expert, and software-architect. A concurrentbboxstarting in the same dir can have its rootfs clone deleted out from under it. UseLoadAndLock(ctx). CWE-367/CWE-663.internal/infra/vm/cleanup.go:167.
Mechanical fixes (3)
- [Medium] Weaker liveness check than the sibling and than go-microvm's own analogue —
process.IsAlive(st.PID)(barekill -0) ignores thePIDStartTime/ exe-path fingerprint thatCleanupStaleLogsand go-microvm'sterminateStaleRunnerboth use. Recycled-PID orphans leak indefinitely. Useprocess.IsExpectedProcess(st.PID, "go-microvm-runner").cleanup.go:179. - [Medium] Ordering with
CleanupStaleLogsis load-bearing in the harmful direction —CleanupStaleLogsruns first andos.RemoveAlls the wholevmDir(incl.data/rootfs-work/) on a dead bbox sentinel, before this function's runner-aware check can protect a still-live detached runner. Guest-side I/O corruption of a live VM.main.go:526. - [Medium] Unbounded synchronous
RemoveAllon a latency-sensitive interactive path — hundreds of MB of small files removed on everybboxinvocation before the VM boots. Move tobbox cleanupsubcommand, background it, or cap it.cleanup.go:187.
Polish (2)
- [Low] No size cap on the
state.Load()read (CWE-400) — the siblingCleanupStaleLogscaps its sentinel read at 4 KiB; this function reads an unboundedos.ReadFile.cleanup.go:167. - [Low]
vmDataSubdir = "data"const is duplicated by a string literal invmDataDir()(runner.go:441) — latent desync with no compile-time signal.cleanup.go:126.
Gaps
library-reuse-reviewerreturned clean — no reinventions; the scan-loop shape is incidental duplication (Rule of Three not met),IsAliveis the right primitive here (no exe path in state to fingerprint against — though see the Medium on using the runner binary name).
Most important single issue: the High BBOX_KEEP_VM_DATA defeat — it directly breaks a documented debugging procedure. The TOCTOU (cross-confirmed Medium) is the highest-confidence finding since three reviewers independently reached it.
🤖 Generated with Claude Code
Collapse CleanupStaleLogs + CleanupStaleVMData into a single CleanupStaleVMDirs that reclaims a vmDir only when neither the bbox sentinel nor the go-microvm-runner state shows a live owner. - Gate startup sweep on BBOX_KEEP_VM_DATA != 1 (was nuking the dir the debug env var is meant to preserve); document the dual gating - Use state.LoadAndLockWithRetry so cleanup serializes with a concurrently-starting VM on the same flock (TOCTOU, CWE-367) - Fingerprint the runner PID via IsExpectedProcess(pid, "go-microvm-runner"), matching go-microvm's terminateStaleRunner - One pass per vmDir closes the ordering hole where CleanupStaleLogs recursed a live data/rootfs-work/ away before the runner check - Background the sweep off the boot path with elapsed debug logging - Cap state-file reads at 4 KiB (CWE-400), mirroring the sentinel - Move vmDataSubdir const next to vmDataDir, the path authority
Summary
Fixes #87 — orphaned COW rootfs clones from crashed VMs leak disk indefinitely.
When a VM crashes or
bboxis killed (SIGKILL, OOM) beforeWithCleanDataDir()runs, the COW-cloned rootfs at~/.config/broodbox/vms/<name>/data/rootfs-work/survives — potentially hundreds of MB per orphan, accumulating unbounded across crashed runs.CleanupStaleLogsalready removes a whole VM directory when its bbox sentinel PID is dead, but no sentinel is written for runs that pass--log-file, so those data clones leak.Approach
Add
CleanupStaleVMData, keyed off go-microvm's per-VM state file (state.Manager.Load(), which readsgo-microvm-state.jsonwithout locking) rather than the bbox sentinel:~/.config/broodbox/vms/*/data/.active: truebut whose recorded runner PID is dead was orphaned → remove it.--log-fileruns) via a non-recursiveRemove, which only succeeds on an empty dir — so it never deletes lingering logs or a sentinel thatCleanupStaleLogsstill owns.Wired into the composition root next to
CleanupStaleLogs/CleanupStaleSnapshots.Tests
New table of cases in
cleanup_test.go(state fixtures written via the canonicalstatepackage):Verified:
task lint(0 issues), fulltask testpasses (incl.-race).🤖 Generated with Claude Code