Skip to content

Clean up orphaned VM data dirs from crashed VMs - #198

Merged
JAORMX merged 2 commits into
mainfrom
fix/87-cleanup-orphaned-vm-data
Jun 29, 2026
Merged

JAORMX merged 2 commits into
mainfrom
fix/87-cleanup-orphaned-vm-data

Conversation

@JAORMX

@JAORMX JAORMX commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

Summary

Fixes #87 — orphaned COW rootfs clones from crashed VMs leak disk indefinitely.

When a VM crashes or bbox is killed (SIGKILL, OOM) before WithCleanDataDir() 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.

CleanupStaleLogs already 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 reads go-microvm-state.json without locking) rather than the bbox sentinel:

  • Scan ~/.config/broodbox/vms/*/data/.
  • A data dir whose state is active: true but whose recorded runner PID is dead was orphaned → remove it.
  • A live runner PID is left untouched, so it's safe to run at startup alongside concurrent VMs (each VM has its own uniquely named dir). A recycled PID now hosting an unrelated live process is conservatively treated as alive and skipped; the orphan is reclaimed on a later run.
  • After removing the data dir, best-effort removes the now-empty parent (reclaiming sentinel-less --log-file runs) via a non-recursive Remove, which only succeeds on an empty dir — so it never deletes lingering logs or a sentinel that CleanupStaleLogs still owns.

Wired into the composition root next to CleanupStaleLogs / CleanupStaleSnapshots.

Note: the issue referenced state.json; the actual go-microvm state file is go-microvm-state.json. Reusing state.Manager.Load() means we don't hardcode the filename or schema.

Tests

New table of cases in cleanup_test.go (state fixtures written via the canonical state package):

  • orphaned (active + dead PID) → data dir and empty parent removed
  • live runner (active + our own PID) → preserved
  • inactive state (clean shutdown) → preserved
  • orphan with parent logs → only data dir removed, parent left for log cleanup
  • no state file → preserved
  • nonexistent vms dir → no panic

Verified: task lint (0 issues), full task test passes (incl. -race).

🤖 Generated with Claude Code

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 JAORMX left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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] CleanupStaleVMData runs unconditionally at startup and silently defeats the documented BBOX_KEEP_VM_DATA=1 debug workflow — a crashed run's data/ 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() and os.RemoveAll — flagged independently by secure-code-reviewer, devops-expert, and software-architect. A concurrent bbox starting in the same dir can have its rootfs clone deleted out from under it. Use LoadAndLock(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) (bare kill -0) ignores the PIDStartTime / exe-path fingerprint that CleanupStaleLogs and go-microvm's terminateStaleRunner both use. Recycled-PID orphans leak indefinitely. Use process.IsExpectedProcess(st.PID, "go-microvm-runner"). cleanup.go:179.
  • [Medium] Ordering with CleanupStaleLogs is load-bearing in the harmful direction — CleanupStaleLogs runs first and os.RemoveAlls the whole vmDir (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 RemoveAll on a latency-sensitive interactive path — hundreds of MB of small files removed on every bbox invocation before the VM boots. Move to bbox cleanup subcommand, background it, or cap it. cleanup.go:187.

Polish (2)

  • [Low] No size cap on the state.Load() read (CWE-400) — the sibling CleanupStaleLogs caps its sentinel read at 4 KiB; this function reads an unbounded os.ReadFile. cleanup.go:167.
  • [Low] vmDataSubdir = "data" const is duplicated by a string literal in vmDataDir() (runner.go:441) — latent desync with no compile-time signal. cleanup.go:126.

Gaps

  • library-reuse-reviewer returned clean — no reinventions; the scan-loop shape is incidental duplication (Rule of Three not met), IsAlive is 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

Comment thread cmd/bbox/main.go Resolved
Comment thread internal/infra/vm/cleanup.go Resolved
Comment thread cmd/bbox/main.go Resolved
Comment thread internal/infra/vm/cleanup.go Resolved
Comment thread internal/infra/vm/cleanup.go Resolved
Comment thread internal/infra/vm/cleanup.go Resolved
Comment thread internal/infra/vm/cleanup.go Resolved
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
@JAORMX
JAORMX merged commit f1f96a5 into main Jun 29, 2026
8 checks passed
@JAORMX
JAORMX deleted the fix/87-cleanup-orphaned-vm-data branch June 29, 2026 18:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Clean up orphaned rootfs-work dirs from crashed VMs

1 participant