Skip to content

An open-source, faster Devin alternative

TypeScript

prevent ghost vms from billing

Brian Reardona2739ac867f8
diff --git a/internal/firecracker/manager.go b/internal/firecracker/manager.go
index 536d4800..76625b20 100644
--- a/internal/firecracker/manager.go
+++ b/internal/firecracker/manager.go
@@ -14,6 +14,7 @@ import (
"path/filepath"
"strings"
"sync"
+ "syscall"
"time"
"github.com/google/uuid"
@@ -675,18 +676,46 @@ func (m *Manager) cleanupVM(netCfg *NetworkConfig, sandboxDir string) {
}
}
-// List returns all running VMs.
+// List returns all running VMs. Skips ghost entries — see fcVMAlive.
func (m *Manager) List(ctx context.Context) ([]types.Sandbox, error) {
m.mu.RLock()
defer m.mu.RUnlock()
result := make([]types.Sandbox, 0, len(m.vms))
for _, vm := range m.vms {
+ if !fcVMAlive(vm) {
+ continue
+ }
result = append(result, *vmToSandbox(vm))
}
return result, nil
}
+// fcVMAlive — same signal-0 process probe as qemu's vmAlive (see
+// qemu/ghost_reaper.go). Firecracker VMInstance has the same cmd/pid shape
+// but is a distinct type, so the check is inlined here rather than abstracted.
+func fcVMAlive(vm *VMInstance) bool {
+ if vm == nil || vm.cmd == nil || vm.cmd.Process == nil {
+ return false
+ }
+ if vm.cmd.ProcessState != nil && vm.cmd.ProcessState.Exited() {
+ return false
+ }
+ return vm.cmd.Process.Signal(syscall.Signal(0)) == nil
+}
+
+// IsSandboxAlive — interface contract for Manager. (false, nil) on unknown id
+// OR known-but-dead. Usage_ticker treats both the same: skip the tick.
+func (m *Manager) IsSandboxAlive(ctx context.Context, id string) (bool, error) {
+ m.mu.RLock()
+ vm, ok := m.vms[id]
+ m.mu.RUnlock()
+ if !ok {
+ return false, nil
+ }
+ return fcVMAlive(vm), nil
+}
+
// Count returns the number of running VMs.
func (m *Manager) Count(ctx context.Context) (int, error) {
m.mu.RLock()
diff --git a/internal/qemu/ghost_reaper.go b/internal/qemu/ghost_reaper.go
new file mode 100644
index 00000000..0138cf88
--- /dev/null
+++ b/internal/qemu/ghost_reaper.go
@@ -0,0 +1,126 @@
+package qemu
+
+import (
+ "context"
+ "log"
+ "syscall"
+ "time"
+)
+
+// Ghost VM reaper — defense for the case where a code path adds to m.vms,
+// later kills the qemu process (or qemu dies on its own), and never cleans the
+// map entry. Symptom in the wild: usage_ticker.tick() reads m.vms, finds the
+// ghost, emits usage_tick events every 20s — runs forever until the worker
+// process restarts and clears the map.
+//
+// Three layers, top-down (matches Fix A / B / C in the triage):
+//
+// A. usage_ticker calls IsSandboxAlive(id) before LogEvent("usage_tick"). Even
+// if List() returns a ghost, the ticker won't bill for it.
+// B. List() filters m.vms entries whose qemu process is dead. + a reaper
+// goroutine (started by NewManager, stopped by Close) walks m.vms every
+// 30s and prunes dead entries so they free memory + stop appearing in any
+// consumer of m.vms — not just usage_ticker.
+// C. Each m.vms add-site's failure paths are audited so the leak doesn't
+// occur in the first place; the reaper is only the safety net.
+
+const reaperInterval = 30 * time.Second
+
+// vmAlive reports whether the qemu process backing this VM is still running.
+// Uses signal-0 ("does this process exist?") which is non-blocking and safe to
+// call on every tick. Survives transient QMP unresponsiveness (e.g. during a
+// savevm) because it checks the OS process, not the QMP socket.
+//
+// Returns false for: nil cmd, nil cmd.Process, or a reaped/exited process.
+func vmAlive(vm *VMInstance) bool {
+ if vm == nil || vm.cmd == nil || vm.cmd.Process == nil {
+ return false
+ }
+ // If cmd.Wait() already returned, ProcessState is non-nil and Exited() is true.
+ if vm.cmd.ProcessState != nil && vm.cmd.ProcessState.Exited() {
+ return false
+ }
+ // Signal(0) is the standard Unix "test process existence" probe. Returns
+ // nil if the process is still around, ESRCH/"already finished" otherwise.
+ return vm.cmd.Process.Signal(syscall.Signal(0)) == nil
+}
+
+// IsSandboxAlive returns true iff the manager has a tracked VM for this id AND
+// its qemu process is still running. Used by usage_ticker before emitting
+// billing events so a ghost m.vms entry can't drive billing on a dead sandbox.
+//
+// (false, nil) on unknown id (not in m.vms) OR known id whose process is dead.
+// Caller treats both the same: skip the tick.
+func (m *Manager) IsSandboxAlive(ctx context.Context, id string) (bool, error) {
+ m.mu.RLock()
+ vm, ok := m.vms[id]
+ m.mu.RUnlock()
+ if !ok {
+ return false, nil
+ }
+ return vmAlive(vm), nil
+}
+
+// startGhostReaper launches the reaper goroutine. Called once from NewManager.
+// Stop via m.stopGhostReaper() — Close() does that.
+func (m *Manager) startGhostReaper() {
+ m.reaperStop = make(chan struct{})
+ m.reaperDone = make(chan struct{})
+ go m.runGhostReaper()
+}
+
+// stopGhostReaper signals the reaper to exit and waits up to 2s for it to
+// drain. Idempotent — multiple Close() calls are safe.
+func (m *Manager) stopGhostReaper() {
+ m.reaperOnce.Do(func() {
+ if m.reaperStop != nil {
+ close(m.reaperStop)
+ }
+ })
+ if m.reaperDone == nil {
+ return
+ }
+ select {
+ case <-m.reaperDone:
+ case <-time.After(2 * time.Second):
+ log.Printf("qemu: ghost reaper did not exit within 2s; continuing close")
+ }
+}
+
+func (m *Manager) runGhostReaper() {
+ defer close(m.reaperDone)
+ t := time.NewTicker(reaperInterval)
+ defer t.Stop()
+ for {
+ select {
+ case <-m.reaperStop:
+ return
+ case <-t.C:
+ m.reapDeadVMs(context.Background())
+ }
+ }
+}
+
+// reapDeadVMs walks m.vms under the write lock and removes entries whose qemu
+// process has exited. Logs each removal — these are bugs upstream (a code path
+// that should have delete()'d on failure) and the log is the trail back to the
+// leaking path.
+//
+// Holds the write lock for the duration; the loop is short (one Signal(0)
+// syscall per VM) so this doesn't measurably contend with create/list/exec.
+func (m *Manager) reapDeadVMs(_ context.Context) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ var reaped int
+ for id, vm := range m.vms {
+ if vmAlive(vm) {
+ continue
+ }
+ log.Printf("qemu: ghost-reaper: removing dead VM %s (pid=%d) from m.vms — qemu process is gone but entry was not cleaned up", id, vm.pid)
+ delete(m.vms, id)
+ reaped++
+ }
+ if reaped > 0 {
+ log.Printf("qemu: ghost-reaper: removed %d dead VM(s) from m.vms; %d alive remain", reaped, len(m.vms))
+ }
+}
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index 59ce9249..7c63aa4a 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -348,6 +348,12 @@ type Manager struct {
// Per-sandbox stats cache populated by a background collector and read by
// the heartbeat path. See stats_collector.go.
statsCache *SandboxStatsCache
+
+ // Ghost-VM reaper: periodically prunes m.vms entries whose qemu process is
+ // dead but the map entry wasn't cleaned up. See ghost_reaper.go.
+ reaperStop chan struct{}
+ reaperDone chan struct{}
+ reaperOnce sync.Once
}
// NewManager creates a new QEMU-backed sandbox manager.
@@ -400,12 +406,17 @@ func NewManager(cfg Config) (*Manager, error) {
log.Printf("qemu: cleaned up stale archive-staging: %s", d)
}
- return &Manager{
+ m := &Manager{
cfg: cfg,
subnets: NewSubnetAllocator(),
vms: make(map[string]*VMInstance),
nextCID: 3,
- }, nil
+ }
+ // Start the ghost-VM reaper. Without it a code path that leaks an m.vms
+ // entry on failure (qemu dies but map entry stays) leads to usage_ticker
+ // emitting billing events forever — see ghost_reaper.go.
+ m.startGhostReaper()
+ return m, nil
}
// SetMetadataCallbacks registers callbacks that are invoked when sandboxes
@@ -2029,6 +2040,13 @@ func (m *Manager) List(ctx context.Context) ([]types.Sandbox, error) {
result := make([]types.Sandbox, 0, len(m.vms))
for _, vm := range m.vms {
+ // Filter ghost VMs: qemu died but the m.vms entry never got cleaned
+ // up. The reaper (ghost_reaper.go) eventually prunes these, but List
+ // callers — most importantly usage_ticker, which uses the list to
+ // drive billing — should never see them, even between reaper ticks.
+ if !vmAlive(vm) {
+ continue
+ }
result = append(result, *vmToSandbox(vm))
}
return result, nil
@@ -2043,6 +2061,8 @@ func (m *Manager) Count(ctx context.Context) (int, error) {
// Close stops all VMs and cleans up.
func (m *Manager) Close() {
+ m.stopGhostReaper()
+
m.mu.Lock()
vms := make([]*VMInstance, 0, len(m.vms))
for _, vm := range m.vms {
@@ -2666,6 +2686,17 @@ func (m *Manager) Hibernate(ctx context.Context, sandboxID string, checkpointSto
result, err := m.doHibernate(ctx, vm, checkpointStore)
if err != nil {
+ // Fix C: doHibernate may have killed qemu mid-flight (savevm path
+ // quits the VM) before bailing out. If qemu is dead, clean the
+ // m.vms entry now — otherwise it becomes a ghost that drives the
+ // usage_ticker until the next ghost-reaper tick (~30s). If qemu is
+ // still alive, leave it: the sandbox may still be recoverable.
+ if !vmAlive(vm) {
+ m.mu.Lock()
+ delete(m.vms, sandboxID)
+ m.mu.Unlock()
+ log.Printf("qemu: Hibernate %s failed (%v) AND qemu process is dead — cleaned m.vms entry inline", sandboxID, err)
+ }
return nil, err
}
diff --git a/internal/qemu/reset.go b/internal/qemu/reset.go
index 299a2a62..d4a0f8ec 100644
--- a/internal/qemu/reset.go
+++ b/internal/qemu/reset.go
@@ -110,6 +110,26 @@ func (m *Manager) PowerCycleSandbox(ctx context.Context, sandboxID string) (host
t0 := time.Now()
+ // Fix C: once we kill the old qemu below, vm.cmd points to a reaped
+ // process until step 6 swaps in a new live cmd. Eight failure-returns
+ // live between the kill and the swap (drives missing, subnet alloc,
+ // TAP create, free port, DNAT, fresh qemu start, fresh QMP connect,
+ // fresh agent connect). Without this defer, any of them leaves m.vms
+ // holding a VMInstance whose vm.cmd refers to a reaped process — the
+ // ghost-VM shape that drove the billing leak. usage_ticker.IsSandboxAlive
+ // already skips these and the ghost-reaper drains them in ≤ 30s, but
+ // explicit local cleanup makes the failure semantics obvious here and
+ // matches the Hibernate failure-path fix.
+ var vmRestored bool
+ defer func() {
+ if err != nil && !vmRestored {
+ m.mu.Lock()
+ delete(m.vms, sandboxID)
+ m.mu.Unlock()
+ log.Printf("qemu: PowerCycleSandbox %s: failed before new qemu swap-in (%v) — cleaned m.vms entry", sandboxID, err)
+ }
+ }()
+
// Best-effort sync before we yank the rug. The QEMU drive is opened
// with cache=writethrough so the host always has a consistent view
// once the guest issues a write — but the guest kernel's own page
@@ -306,6 +326,9 @@ func (m *Manager) PowerCycleSandbox(ctx context.Context, sandboxID string) (host
vm.MemoryMB = finalMemMB
vm.baseMemoryMB = bootMemMB
vm.virtioMemRequestedMB = finalPlugMB
+ // Swap-in complete — the deferred cleanup at the top of this function
+ // will now no-op even if a future addition adds error returns below.
+ vmRestored = true
log.Printf("qemu: PowerCycleSandbox %s: complete (%dms, port=%d, tap=%s)",
sandboxID, time.Since(t0).Milliseconds(), freshPort, netCfg.TAPName)
diff --git a/internal/sandbox/interface.go b/internal/sandbox/interface.go
index a91523ff..2e0aaa6c 100644
--- a/internal/sandbox/interface.go
+++ b/internal/sandbox/interface.go
@@ -57,6 +57,12 @@ type Manager interface {
Kill(ctx context.Context, id string) error
List(ctx context.Context) ([]types.Sandbox, error)
Count(ctx context.Context) (int, error)
+ // IsSandboxAlive reports whether the manager has a tracked VM for id AND
+ // its backing process (qemu/firecracker) is still running. Used by the
+ // usage_ticker before emitting billing events so a stale in-memory entry
+ // (the "ghost VM" bug) can't drive billing on a dead sandbox.
+ // Returns (false, nil) for both "unknown id" and "known but dead".
+ IsSandboxAlive(ctx context.Context, id string) (bool, error)
Close()
// Execution
diff --git a/internal/worker/usage_ticker.go b/internal/worker/usage_ticker.go
index d15b2dfd..4d741f6b 100644
--- a/internal/worker/usage_ticker.go
+++ b/internal/worker/usage_ticker.go
@@ -108,7 +108,25 @@ func (t *UsageTicker) tick(ctx context.Context) {
return
}
emitted := 0
+ skippedDead := 0
for _, sb := range list {
+ // Defense in depth: even if manager.List() returns a ghost entry
+ // (m.vms entry whose qemu/firecracker process died but wasn't
+ // cleaned up), don't bill for it. The leak this guards against
+ // was a 70+ hour-per-sandbox billing bleed in prod where ghosts
+ // kept ticking until the worker process restarted and wiped m.vms.
+ // See internal/qemu/ghost_reaper.go for the boundary fix +
+ // reaper that drains the map.
+ alive, err := t.manager.IsSandboxAlive(ctx, sb.ID)
+ if err != nil {
+ log.Printf("usage_ticker: %s: IsSandboxAlive check failed: %v — skipping this tick", sb.ID, err)
+ continue
+ }
+ if !alive {
+ skippedDead++
+ log.Printf("usage_ticker: %s: not alive (ghost m.vms entry?) — skipping; reaper should drain it", sb.ID)
+ continue
+ }
sdb, err := t.sandboxDBs.Get(sb.ID)
if err != nil {
log.Printf("usage_ticker: %s: Get failed: %v", sb.ID, err)
@@ -124,5 +142,5 @@ func (t *UsageTicker) tick(ctx context.Context) {
}
emitted++
}
- log.Printf("usage_ticker: tick: emitted %d usage_tick event(s) for %d running sandbox(es)", emitted, len(list))
+ log.Printf("usage_ticker: tick: emitted %d usage_tick event(s) for %d listed sandbox(es) (skipped %d as not-alive)", emitted, len(list), skippedDead)
}