Skip to content

Quickly sandbox your AI agent.

Python

fix: kill QEMU when parent dies via reaper launcher

Tyler Payneb324755dc121
diff --git a/packages/quicksand-core/quicksand_core/_reaper.py b/packages/quicksand-core/quicksand_core/_reaper.py
new file mode 100644
index 0000000..7fddc72
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/_reaper.py
@@ -0,0 +1,92 @@
+#!/usr/bin/env python3
+"""Tiny launcher that wraps a child process and kills it when the Python
+parent dies.
+
+VMProcessManager spawns this between itself and QEMU. The parent opens a
+pipe to our stdin (Popen(stdin=PIPE)); we read bytes from that pipe and
+forward them to the child's stdin. When the parent dies for any reason
+(Ctrl+C, crash, kill -9, OOM kill), the kernel closes the write end of
+the pipe and our read returns EOF — at which point we tear down the child.
+
+Stdout and stderr are NOT redirected: the child inherits them from us, so
+the parent's view of the child's streams is unchanged.
+
+Usage (invoked by VMProcessManager, not directly):
+ python3 _reaper.py -- <child cmd> [args...]
+"""
+
+from __future__ import annotations
+
+import contextlib
+import os
+import signal
+import subprocess
+import sys
+import threading
+
+GRACEFUL_TIMEOUT = 15.0
+
+
+def _kill(child: subprocess.Popen) -> None:
+ if child.poll() is not None:
+ return
+ with contextlib.suppress(Exception):
+ child.terminate()
+ try:
+ child.wait(timeout=GRACEFUL_TIMEOUT)
+ return
+ except subprocess.TimeoutExpired:
+ pass
+ child.kill()
+ with contextlib.suppress(subprocess.TimeoutExpired):
+ child.wait(timeout=GRACEFUL_TIMEOUT)
+
+
+def _watch_stdin(child: subprocess.Popen) -> None:
+ """Forward our stdin to the child; kill the child on EOF."""
+ try:
+ while True:
+ data = os.read(0, 4096)
+ if not data:
+ break
+ if child.stdin is None:
+ continue
+ try:
+ child.stdin.write(data)
+ child.stdin.flush()
+ except (BrokenPipeError, ValueError, OSError):
+ break
+ except OSError:
+ pass
+ finally:
+ _kill(child)
+
+
+def main() -> int:
+ if len(sys.argv) < 3 or sys.argv[1] != "--":
+ print("usage: _reaper.py -- <cmd> [args...]", file=sys.stderr)
+ return 2
+
+ cmd = sys.argv[2:]
+ child = subprocess.Popen(cmd, stdin=subprocess.PIPE)
+
+ def _forward(signum, _frame):
+ if child.poll() is None:
+ with contextlib.suppress(Exception):
+ child.send_signal(signum)
+
+ for sig in (signal.SIGINT, signal.SIGTERM):
+ with contextlib.suppress(ValueError, OSError):
+ signal.signal(sig, _forward)
+
+ threading.Thread(target=_watch_stdin, args=(child,), daemon=True).start()
+
+ try:
+ child.wait()
+ except KeyboardInterrupt:
+ _kill(child)
+ return child.returncode if child.returncode is not None else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/packages/quicksand-core/quicksand_core/qemu/process.py b/packages/quicksand-core/quicksand_core/qemu/process.py
index e2e578d..88699e3 100644
--- a/packages/quicksand-core/quicksand_core/qemu/process.py
+++ b/packages/quicksand-core/quicksand_core/qemu/process.py
@@ -9,13 +9,17 @@ from __future__ import annotations
import contextlib
import logging
import subprocess
+import sys
from pathlib import Path
from typing import IO
+from .. import _reaper
from .._types import Timeouts
logger = logging.getLogger("quicksand.process")
+_REAPER_SCRIPT = Path(_reaper.__file__)
+
class VMProcessManager:
"""Manages QEMU process lifecycle.
@@ -76,15 +80,21 @@ class VMProcessManager:
self._console_log = console_log_path
self._console_file = self._console_log.open("w")
+ # Spawn QEMU through the reaper so it dies when we die. The parent's
+ # write end of the stdin pipe is what keeps the reaper alive: when
+ # this process dies (Ctrl+C, crash, kill -9), the kernel closes that
+ # pipe and the reaper tears QEMU down. write_serial() still reaches
+ # QEMU because the reaper forwards stdin bytes to QEMU's stdin.
+ wrapped = [sys.executable, str(_REAPER_SCRIPT), "--", *command]
self._process = subprocess.Popen(
- command,
+ wrapped,
stdout=self._console_file,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
env=env,
)
- logger.debug(f"Started QEMU process with PID {self._process.pid}")
+ logger.debug(f"Started QEMU via reaper, reaper PID {self._process.pid}")
def write_serial(self, data: bytes) -> None:
"""Write raw bytes to the VM's serial port (stdin of QEMU process).
@@ -160,15 +170,25 @@ class VMProcessManager:
if self._process:
pid = self._process.pid
try:
- self._process.terminate()
+ # Close stdin first: this signals the reaper to tear QEMU
+ # down (its stdin watcher sees EOF and kills the child).
+ # Works the same on every platform, including Windows where
+ # Popen.terminate is a hard kill that wouldn't let the
+ # reaper run its cleanup.
+ if self._process.stdin is not None:
+ with contextlib.suppress(Exception):
+ self._process.stdin.close()
try:
self._process.wait(timeout=graceful_timeout)
except subprocess.TimeoutExpired:
- logger.warning(
- "QEMU process %d did not terminate gracefully, sending SIGKILL", pid
- )
- self._process.kill()
- self._process.wait(timeout=graceful_timeout)
+ logger.warning("Reaper %d did not exit gracefully, sending terminate", pid)
+ self._process.terminate()
+ try:
+ self._process.wait(timeout=graceful_timeout)
+ except subprocess.TimeoutExpired:
+ logger.warning("Reaper %d did not terminate, sending SIGKILL", pid)
+ self._process.kill()
+ self._process.wait(timeout=graceful_timeout)
except Exception as e:
errors.append(("QEMU process", e))
logger.error("Failed to terminate QEMU process (pid=%d): %s", pid, e)