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(clis): a stopped CLI probe takes its own child processes with it (#955)
Ruben Lütke7989f8be2a5e
diff --git a/dodaios/clis/prober.py b/dodaios/clis/prober.pyindex e719d8c3d2..251482b462 100644--- a/dodaios/clis/prober.py+++ b/dodaios/clis/prober.py@@ -56,6 +56,27 @@ PROBE_ALL_TIMEOUT_S = CHECK_TIMEOUT_S + AUTH_TIMEOUT_S + 2 * KILL_WAIT_TIMEOUT_S# BUG-189). Six lanes keep a calm sweep under ten seconds and turn the# cold-boot burst into a queue.PROBE_CONCURRENCY = 6+# POSIX: every probe leads its own process group, so a stop reaches what the+# CLI spawned too. ``wrangler --version`` re-launches itself as a child node;+# killing only the parent left that child running past ``jarvis serve``'s exit+# and holding the pipes, so the wait timed out and the transport was collected+# after the loop closed ("Event loop is closed", #534).+_OWN_GROUP = os.name != "nt"+++def _kill_probe(proc: asyncio.subprocess.Process) -> None:+ """SIGKILL the probe's whole process group (POSIX), else just the child."""+ pid = getattr(proc, "pid", None)+ killpg = getattr(os, "killpg", None)+ if _OWN_GROUP and killpg is not None and isinstance(pid, int) and pid > 0:+ try:+ killpg(pid, 9) # SIGKILL; the group id is the leader's pid+ return+ except ProcessLookupError:+ return # the whole group is already gone+ except OSError:+ pass # not our group after all: fall back to the child alone+ proc.kill()async def _cancel_probes(tasks: list[asyncio.Future[CliStatus]]) -> None:@@ -90,9 +111,11 @@ async def _cancel_probes(tasks: list[asyncio.Future[CliStatus]]) -> None:async def _stop_probe_process(proc: asyncio.subprocess.Process, name: str) -> None:"""Reap a cancelled or timed-out probe within the existing cleanup budget."""- if proc.returncode is None:+ # Even a child that already exited may have left its own children in the+ # group (they hold the pipes), so the group is always signalled.+ if proc.returncode is None or _OWN_GROUP:try:- proc.kill()+ _kill_probe(proc)except ProcessLookupError:pass # The child exited between the returncode check and kill.try:@@ -194,6 +217,7 @@ class CliStatusProber:stderr=PIPE,env={**os.environ, "CI": "true"},creationflags=NO_WINDOW_CREATIONFLAGS,+ start_new_session=_OWN_GROUP,)try:out_b, err_b = await asyncio.wait_for(proc.communicate(), timeout=CHECK_TIMEOUT_S)@@ -239,6 +263,7 @@ class CliStatusProber:stderr=PIPE,env={**os.environ, "CI": "true"},creationflags=NO_WINDOW_CREATIONFLAGS,+ start_new_session=_OWN_GROUP,)try:out_b, err_b = await asyncio.wait_for(proc.communicate(), timeout=AUTH_TIMEOUT_S)diff --git a/tests/unit/clis/test_prober_process_group.py b/tests/unit/clis/test_prober_process_group.pynew file mode 100644index 0000000000..ca80767e6a--- /dev/null+++ b/tests/unit/clis/test_prober_process_group.py@@ -0,0 +1,110 @@+"""A stopped CLI probe takes what it spawned with it (#534).++``wrangler --version`` re-launches itself as a child ``node``. Killing only the+probe left that child running past ``jarvis serve``'s exit, holding the pipes,+so the wait timed out and the transport was collected after the loop closed.+"""++from __future__ import annotations++import asyncio+import os+import sys+import time+from pathlib import Path+from typing import Any++import pytest++from dodaios.clis import prober as prober_mod+from dodaios.clis.prober import CliStatusProber+from dodaios.clis.spec import AuthConfig, CliSpec, InstallMethods, RiskConfig+++class _Proc:+ def __init__(self, pid: Any) -> None:+ self.pid = pid+ self.returncode: int | None = None+ self.killed = False++ def kill(self) -> None:+ self.killed = True+++def test_a_posix_stop_signals_the_whole_group(monkeypatch: pytest.MonkeyPatch) -> None:+ sent: list[tuple[int, int]] = []+ monkeypatch.setattr(prober_mod, "_OWN_GROUP", True)+ monkeypatch.setattr(+ prober_mod.os, "killpg", lambda pid, sig: sent.append((pid, sig)), raising=False+ )+ proc = _Proc(4321)+ prober_mod._kill_probe(proc) # type: ignore[arg-type]+ assert sent == [(4321, 9)]+ assert proc.killed is False+++def test_without_a_group_only_the_child_is_killed(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(prober_mod, "_OWN_GROUP", False)+ proc = _Proc(4321)+ prober_mod._kill_probe(proc) # type: ignore[arg-type]+ assert proc.killed is True+++def test_a_group_that_is_not_ours_falls_back_to_the_child(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def _denied(_pid: int, _sig: int) -> None:+ raise PermissionError++ monkeypatch.setattr(prober_mod, "_OWN_GROUP", True)+ monkeypatch.setattr(prober_mod.os, "killpg", _denied, raising=False)+ proc = _Proc(4321)+ prober_mod._kill_probe(proc) # type: ignore[arg-type]+ assert proc.killed is True+++def _spec(binary: str) -> CliSpec:+ return CliSpec(+ name="slowcli",+ display_name="SLOWCLI",+ description="d",+ homepage="",+ binary_name=binary,+ check_command=(binary, "--version"),+ version_parse_regex=r"(\d+)",+ install=InstallMethods(manual_url="https://x"),+ auth=AuthConfig(type="none"),+ risk=RiskConfig(default_tier="monitor"),+ )++[email protected](sys.platform == "win32", reason="POSIX process groups")+async def test_a_timed_out_probe_leaves_no_grandchild(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ pid_file = tmp_path / "grandchild.pid"+ script = tmp_path / "slowcli"+ # Like wrangler: the CLI starts a child that keeps the pipes, then waits.+ script.write_text(+ f"#!/bin/sh\nsleep 60 &\necho $! > '{pid_file}'\nwait\n",+ encoding="utf-8",+ )+ script.chmod(0o755)+ monkeypatch.setattr(prober_mod.shutil, "which", lambda _name: str(script))+ monkeypatch.setattr(prober_mod, "CHECK_TIMEOUT_S", 1.0)++ installed, version, _path = await CliStatusProber()._probe_binary(_spec("slowcli"))++ assert installed is True and version is None+ grandchild = int(pid_file.read_text(encoding="utf-8").strip())+ deadline = time.monotonic() + 5+ while time.monotonic() < deadline:+ try:+ os.kill(grandchild, 0)+ except ProcessLookupError:+ break # killed with its group, and reaped by init+ await asyncio.sleep(0.05)+ else:+ os.kill(grandchild, 9)+ pytest.fail("the probe's grandchild outlived the probe")