Skip to content

An open-source, faster Devin alternative

TypeScript

fix reaper race for cross wake

Brian Reardon6c97a6096355
diff --git a/internal/qemu/orphan_reaper.go b/internal/qemu/orphan_reaper.go
index aa7bbf94..da119193 100644
--- a/internal/qemu/orphan_reaper.go
+++ b/internal/qemu/orphan_reaper.go
@@ -22,6 +22,21 @@ const orphanReapInterval = 60 * time.Second
// generous and bounds the reap pass at ~5s per orphan in the worst case.
const orphanGraceTermDelay = 5 * time.Second
+// orphanYoungProcessGrace is the minimum age a qemu-system process must have
+// before we consider it a reap candidate. Wake / create / fork code starts
+// QEMU via cmd.Start() and only registers the sandbox in m.vms *after* QMP
+// connect + loadvm + virtio-mem plug + cont + agent connect — 5-30 seconds
+// for hibernated wake under chunked download. Reaping a just-started qemu in
+// that window kills the in-progress operation: the caller observes
+// "QMP cont: write: broken pipe" or "agent not ready after 10s".
+//
+// Treat too-young processes as off-limits. If they're genuinely orphaned
+// (e.g. wake crashed silently between cmd.Start and m.vms registration), a
+// later sweep will catch them once they age past the grace window. The cost
+// of waiting one extra sweep on a real orphan is bounded — they linger 60s
+// longer than they would have otherwise.
+const orphanYoungProcessGrace = 2 * time.Minute
+
// sandboxIDRe extracts an sb-xxxxxxxx sandbox ID from a qemu command line.
// QEMU's cmdline embeds the sandboxDir as a -drive file=… and -chardev path=…
// argument, so the ID always appears in the form /data/sandboxes/sandboxes/sb-XXX/.
@@ -78,14 +93,27 @@ func (m *Manager) reapOrphans() {
}
m.mu.RUnlock()
- for sandboxID, pid := range pidByID {
+ now := time.Now()
+ for sandboxID, p := range pidByID {
if known[sandboxID] {
continue
}
- log.Printf("qemu: orphan-reaper: found leaked qemu pid=%d sandbox=%s (not in vm registry), terminating",
- pid, sandboxID)
- if err := terminateAndWait(pid); err != nil {
- log.Printf("qemu: orphan-reaper: failed to terminate pid=%d: %v", pid, err)
+ // Skip too-young processes: wake / create / fork start QEMU before
+ // registering the sandbox in m.vms (QMP setup + loadvm + cont + agent
+ // connect happen between cmd.Start and m.vms[id] = vm, up to ~30s for
+ // hibernated wake under chunked download). Killing one of those mid-
+ // flight surfaces as "QMP cont: broken pipe" or "agent not ready" to
+ // the caller. If the process is genuinely orphaned, a later sweep
+ // catches it once it ages past the grace window.
+ if age := now.Sub(p.start); age < orphanYoungProcessGrace {
+ log.Printf("qemu: orphan-reaper: skip pid=%d sandbox=%s — process too young (%s < %s)",
+ p.pid, sandboxID, age.Round(time.Second), orphanYoungProcessGrace)
+ continue
+ }
+ log.Printf("qemu: orphan-reaper: found leaked qemu pid=%d sandbox=%s (not in vm registry, age=%s), terminating",
+ p.pid, sandboxID, now.Sub(p.start).Round(time.Second))
+ if err := terminateAndWait(p.pid); err != nil {
+ log.Printf("qemu: orphan-reaper: failed to terminate pid=%d: %v", p.pid, err)
continue
}
// Best-effort sandbox dir cleanup. If destroyVM was supposed to remove
@@ -94,7 +122,7 @@ func (m *Manager) reapOrphans() {
if _, err := os.Stat(sandboxDir); err == nil {
if err := os.RemoveAll(sandboxDir); err != nil {
log.Printf("qemu: orphan-reaper: removed pid=%d but failed to clean %s: %v",
- pid, sandboxDir, err)
+ p.pid, sandboxDir, err)
} else {
log.Printf("qemu: orphan-reaper: cleaned up sandbox dir %s", sandboxDir)
}
@@ -102,14 +130,25 @@ func (m *Manager) reapOrphans() {
}
}
-// scanQEMUProcesses walks /proc and returns a map of sandboxID -> pid for
-// every qemu-system-x86_64 process whose cmdline references a sandbox dir.
-func scanQEMUProcesses() (map[string]int, error) {
+// procInfo carries a qemu-system process's pid + start time. Start time is
+// resolved from /proc/PID stat info (the directory's mtime is good enough —
+// it's set at process creation and doesn't get touched after).
+type procInfo struct {
+ pid int
+ start time.Time
+}
+
+// scanQEMUProcesses walks /proc and returns a map of sandboxID -> procInfo
+// for every qemu-system-x86_64 process whose cmdline references a sandbox dir.
+// The start time on each procInfo is the mtime of /proc/PID, which Linux
+// stamps at process creation and leaves untouched afterward — close enough
+// to a real start time for the orphan-reaper's grace check.
+func scanQEMUProcesses() (map[string]procInfo, error) {
procEntries, err := os.ReadDir("/proc")
if err != nil {
return nil, err
}
- out := make(map[string]int)
+ out := make(map[string]procInfo)
for _, entry := range procEntries {
if !entry.IsDir() {
continue
@@ -118,8 +157,9 @@ func scanQEMUProcesses() (map[string]int, error) {
if err != nil {
continue
}
+ procDir := filepath.Join("/proc", entry.Name())
// Read /proc/PID/comm — cheap, only ~16 bytes; skip non-qemu fast.
- commBytes, err := os.ReadFile(filepath.Join("/proc", entry.Name(), "comm"))
+ commBytes, err := os.ReadFile(filepath.Join(procDir, "comm"))
if err != nil {
continue
}
@@ -128,7 +168,7 @@ func scanQEMUProcesses() (map[string]int, error) {
continue
}
// /proc/PID/cmdline is NUL-separated; we scan it as a single blob.
- cmdlineBytes, err := os.ReadFile(filepath.Join("/proc", entry.Name(), "cmdline"))
+ cmdlineBytes, err := os.ReadFile(filepath.Join(procDir, "cmdline"))
if err != nil {
continue
}
@@ -138,11 +178,15 @@ func scanQEMUProcesses() (map[string]int, error) {
continue
}
sandboxID := match[1]
+ st, err := os.Stat(procDir)
+ if err != nil {
+ continue
+ }
// Multiple qemu processes for the same sandbox shouldn't exist —
// if they do, the first one wins; the duplicate will be reaped on
// the next pass after the registered one is removed.
if _, dup := out[sandboxID]; !dup {
- out[sandboxID] = pid
+ out[sandboxID] = procInfo{pid: pid, start: st.ModTime()}
}
}
return out, nil