Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(missions): arm PR_SET_PDEATHSIG on Linux worker spawn (P-10)
Ruben Lütke84e571e19440
diff --git a/jarvis/missions/isolation/job_object.py b/jarvis/missions/isolation/job_object.pyindex 27eae826e2..8c6040a710 100644--- a/jarvis/missions/isolation/job_object.py+++ b/jarvis/missions/isolation/job_object.py@@ -338,10 +338,15 @@ class _PosixProcessGroupJobObject:any handled orchestrator exception, all of which used to leak the tree.Honest limitation: a *hard* ``SIGKILL`` of the orchestrator process itself- bypasses ``close()``, so it cannot reap there — the groups are reparented to- init and survive (the one case the kernel-level Job Object covers and this does- not). A future Linux-only ``PR_SET_PDEATHSIG`` preexec hook would close that- gap; macOS has no direct equivalent.+ bypasses ``close()``, so it cannot reap there — the groups would be reparented+ to init and survive (the one case the kernel-level Job Object covers and this+ class alone does not). On Linux this is now covered separately: every worker+ is spawned via ``create_worker_subprocess``+ (``jarvis/missions/workers/process_utils.py``), which arms+ ``PR_SET_PDEATHSIG`` in a ``preexec_fn`` so the kernel itself SIGKILLs the+ worker leader the instant its parent dies, independent of this class's+ ``close()`` path. macOS still has no equivalent (a future launchd/kqueue+ ``EVFILT_PROC`` watcher would be the path there)."""def __init__(diff --git a/jarvis/missions/workers/process_utils.py b/jarvis/missions/workers/process_utils.pyindex 6bc01bf13b..3ba1b8c329 100644--- a/jarvis/missions/workers/process_utils.py+++ b/jarvis/missions/workers/process_utils.py@@ -2,11 +2,14 @@from __future__ import annotationsimport asyncio+import ctypesimport loggingimport osimport shutil+import signalimport subprocessimport sys+from collections.abc import Callablefrom contextlib import suppress as contextlib_suppressfrom pathlib import Pathfrom typing import Any@@ -15,6 +18,73 @@ logger = logging.getLogger(__name__)_CREATE_BREAKAWAY_FROM_JOB = 0x01000000+# Linux prctl() option to ask the kernel to signal this process when its+# parent dies. See `_linux_pdeathsig_preexec_fn` below (P-10 / os-parity.md).+_PR_SET_PDEATHSIG = 1+# SIGKILL is POSIX-only; ``signal`` has no attribute on Windows, and this+# module is imported (and platform-spoofed via monkeypatch in tests) on a+# Windows host too, so resolve with the same fallback pattern already used in+# ``jarvis/missions/isolation/job_object.py``.+_SIGKILL = getattr(signal, "SIGKILL", 9)+++def _resolve_linux_prctl() -> Callable[..., int] | None:+ """Return ``libc.prctl`` on Linux, or ``None`` if unavailable.++ Resolved once in the parent process, BEFORE spawn, so the ``preexec_fn``+ closure only ever calls an already-bound C function — never imports or+ does discovery work between ``fork()`` and ``exec()``.++ Guarded with a broad ``except Exception``: ``ctypes.CDLL(None)`` is a+ POSIX/glibc idiom (load the running process's own symbols) that raises+ different exception types depending on the host — e.g. ``TypeError`` on a+ Windows host with ``sys.platform`` patched to ``"linux"`` in tests, or+ ``OSError``/``AttributeError`` on a real Linux host missing ``prctl`` in+ libc. Any failure here must degrade to "no PDEATHSIG", never crash the spawn.+ """+ if sys.platform != "linux":+ return None+ try:+ libc = ctypes.CDLL(None, use_errno=True) # noqa: SIM115 - not a file handle+ return libc.prctl # type: ignore[no-any-return]+ except Exception: # noqa: BLE001 - discovery must never break a worker spawn+ return None+++def _linux_pdeathsig_preexec_fn(prctl: Callable[..., int]) -> Callable[[], None]:+ """Build a ``preexec_fn`` that arms ``PR_SET_PDEATHSIG`` in the child.++ Closes gap P-10 (``docs/os-parity.md``): a hard SIGKILL of the orchestrator+ bypasses ``_PosixProcessGroupJobObject.close()`` (it only reaps via+ ``killpg`` on an orderly close), so the worker's session/process group is+ reparented to init and survives. Arming ``PR_SET_PDEATHSIG`` makes the+ kernel itself deliver SIGKILL to the worker leader the instant its parent+ (the orchestrator) dies — including on a hard SIGKILL, which no userspace+ signal handler could ever observe.++ Runs between ``fork()`` and ``exec()`` in the child: kept minimal (no+ logging, no imports — ``prctl`` is bound in the parent and passed in via+ closure) and never raises, because ``subprocess`` re-raises any+ ``preexec_fn`` exception as ``SubprocessError`` and would abort the whole+ spawn over what is purely a containment hardening step.++ Known caveats (acceptable — this only strengthens containment, it is+ never the only reaper):+ - PDEATHSIG fires when the spawning *thread* exits, not only when the+ whole process dies; in the asyncio subprocess-spawn path that thread is+ the process itself, so this does not fire spuriously here.+ - macOS has no equivalent syscall; the future path there is a launchd/+ kqueue ``EVFILT_PROC`` watcher, not prctl.+ """++ def _preexec() -> None:+ try:+ prctl(_PR_SET_PDEATHSIG, _SIGKILL)+ except Exception: # noqa: BLE001, S110 - must never abort the spawn+ pass++ return _preexec+def _windows_node_dir_candidates() -> list[str]:"""Well-known Windows directories that may contain ``node.exe``.@@ -100,6 +170,16 @@ async def create_worker_subprocess(# per-mission job object can reap the whole tree via os.killpg on close# (the Windows equivalent is the Job Object + CREATE_BREAKAWAY_FROM_JOB).kwargs.setdefault("start_new_session", True)+ if sys.platform == "linux":+ # Close gap P-10 (docs/os-parity.md): a hard SIGKILL of the orchestrator+ # bypasses the job object's close()-based reaping, reparenting the worker+ # tree to init. PR_SET_PDEATHSIG makes the kernel SIGKILL the worker+ # leader the instant its parent dies, no matter how the parent died.+ # ``preexec_fn`` is compatible with ``start_new_session=True`` — Python+ # applies setsid() then runs preexec_fn, both in the child post-fork.+ prctl = _resolve_linux_prctl()+ if prctl is not None:+ kwargs.setdefault("preexec_fn", _linux_pdeathsig_preexec_fn(prctl))try:return await asyncio.create_subprocess_exec(*cmd, creationflags=flags, **kwargsdiff --git a/tests/missions/test_posix_containment.py b/tests/missions/test_posix_containment.pyindex 04547c60d6..c508e3fdab 100644--- a/tests/missions/test_posix_containment.py+++ b/tests/missions/test_posix_containment.py@@ -12,11 +12,17 @@ POSIX syscalls (``os.killpg``/``os.getpgid``, ``SIGKILL``) do not exist on theWindows test host, so the POSIX job object takes injectable ``getpgid``/``killpg``callables, and the spawn-contract test monkeypatches ``sys.platform`` + a fake``create_subprocess_exec`` — the same pattern as ``test_spawn_breakaway_fallback``.++The P-10 gap (a hard SIGKILL of the orchestrator reparents the worker tree to+init because the job object above can only reap via an orderly ``close()``) is+closed on Linux by arming ``PR_SET_PDEATHSIG`` at spawn time in+``create_worker_subprocess`` — see the ``preexec_fn`` tests below."""from __future__ import annotationsimport asyncioimport signal+import sysimport pytest@@ -179,6 +185,108 @@ async def test_worker_spawn_no_new_session_on_windows()+# --- P-10: PR_SET_PDEATHSIG hardening on Linux only --------------------------+++async def test_worker_spawn_passes_no_preexec_fn_on_macos(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Only Linux gets the prctl hardening — macOS has no PR_SET_PDEATHSIG."""+ seen: dict[str, object] = {}++ async def _fake_exec(*_a, **kw): # noqa: ANN002, ANN003+ seen.update(kw)+ return object()++ monkeypatch.setattr(asyncio, "create_subprocess_exec", _fake_exec)+ monkeypatch.setattr(pu.sys, "platform", "darwin")++ await pu.create_worker_subprocess(["x"], cwd=".", env={})+ assert "preexec_fn" not in seen, "macOS has no PR_SET_PDEATHSIG equivalent"+++async def test_worker_spawn_passes_no_preexec_fn_on_windows(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ seen: dict[str, object] = {}++ async def _fake_exec(*_a, creationflags: int = 0, **kw): # noqa: ANN002, ANN003+ seen.update(kw)+ return object()++ monkeypatch.setattr(asyncio, "create_subprocess_exec", _fake_exec)+ monkeypatch.setattr(pu.sys, "platform", "win32")+ monkeypatch.setattr(pu, "worker_creationflags", lambda: 0x08000000)++ await pu.create_worker_subprocess(["x"], cwd=".", env={})+ assert "preexec_fn" not in seen+++async def test_worker_spawn_passes_no_preexec_fn_when_prctl_unavailable(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Even on Linux, a missing/unresolvable prctl must degrade silently."""+ seen: dict[str, object] = {}++ async def _fake_exec(*_a, **kw): # noqa: ANN002, ANN003+ seen.update(kw)+ return object()++ monkeypatch.setattr(asyncio, "create_subprocess_exec", _fake_exec)+ monkeypatch.setattr(pu.sys, "platform", "linux")+ monkeypatch.setattr(pu, "_resolve_linux_prctl", lambda: None)++ proc = await pu.create_worker_subprocess(["x"], cwd=".", env={})+ assert proc is not None+ assert "preexec_fn" not in seen+++async def test_worker_spawn_passes_preexec_fn_on_linux_when_prctl_available(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """On Linux with a resolvable prctl, the spawn gets a PDEATHSIG preexec_fn."""+ seen: dict[str, object] = {}+ prctl_calls: list[tuple[int, int]] = []++ def _fake_prctl(option: int, sig: int) -> int:+ prctl_calls.append((option, sig))+ return 0++ async def _fake_exec(*_a, **kw): # noqa: ANN002, ANN003+ seen.update(kw)+ return object()++ monkeypatch.setattr(asyncio, "create_subprocess_exec", _fake_exec)+ monkeypatch.setattr(pu.sys, "platform", "linux")+ monkeypatch.setattr(pu, "_resolve_linux_prctl", lambda: _fake_prctl)++ await pu.create_worker_subprocess(["x"], cwd=".", env={})++ preexec = seen.get("preexec_fn")+ assert callable(preexec), "Linux spawn with a working prctl must set preexec_fn"+ # Simulate the fork-time call the real subprocess machinery would make.+ preexec()+ assert prctl_calls == [(pu._PR_SET_PDEATHSIG, pu._SIGKILL)]+++def test_linux_pdeathsig_preexec_fn_never_raises() -> None:+ """The preexec_fn must swallow prctl failures — it must never abort a spawn."""++ def _boom(*_a, **_k): # noqa: ANN002, ANN003+ raise OSError("simulated prctl failure")++ preexec = pu._linux_pdeathsig_preexec_fn(_boom)+ preexec() # must not raise++[email protected](sys.platform != "linux", reason="prctl is Linux-only")+def test_resolve_linux_prctl_returns_callable_on_real_linux() -> None:+ """On a real Linux host, libc.prctl must resolve to a callable."""+ prctl = pu._resolve_linux_prctl()+ assert prctl is not None+ assert callable(prctl)++# --- Bootstrap wiring: the mission job factory must reap on POSIX -----------