Skip to content

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.

fix(clis): bound post-kill wait and bootstrap so a wedged CLI probe cannot hang the brain build

Ruben Lütke673c5ebc083e
diff --git a/jarvis/clis/prober.py b/jarvis/clis/prober.py
index e7cf1adb00..6ff43e4309 100644
--- a/jarvis/clis/prober.py
+++ b/jarvis/clis/prober.py
@@ -28,6 +28,13 @@ log = logging.getLogger(__name__)
CHECK_TIMEOUT_S = 10.0
AUTH_TIMEOUT_S = 15.0
+# After a timed-out probe is kill()ed, how long to wait for the OS to reap it
+# before giving up. A .cmd/.bat shim's actual child process can survive
+# kill() (the shim exits, the grandchild lives on) — an unbounded
+# ``await proc.wait()`` here would then hang the probe (and the synchronous
+# bootstrap path that awaits it, see jarvis/clis/loader.py) forever. A leaked
+# zombie process beats an infinite hang.
+KILL_WAIT_TIMEOUT_S = 2.0
class CliStatusProber:
@@ -81,7 +88,13 @@ class CliStatusProber:
out_b, err_b = await asyncio.wait_for(proc.communicate(), timeout=CHECK_TIMEOUT_S)
except TimeoutError:
proc.kill()
- await proc.wait()
+ try:
+ await asyncio.wait_for(proc.wait(), timeout=KILL_WAIT_TIMEOUT_S)
+ except TimeoutError:
+ log.warning(
+ "probe-binary(%s): child survived kill() — leaking the "
+ "zombie instead of hanging the probe.", spec.name,
+ )
return True, None, path
except FileNotFoundError:
return False, None, None
@@ -120,7 +133,13 @@ class CliStatusProber:
out_b, err_b = await asyncio.wait_for(proc.communicate(), timeout=AUTH_TIMEOUT_S)
except TimeoutError:
proc.kill()
- await proc.wait()
+ try:
+ await asyncio.wait_for(proc.wait(), timeout=KILL_WAIT_TIMEOUT_S)
+ except TimeoutError:
+ log.warning(
+ "probe-auth(%s): child survived kill() — leaking the "
+ "zombie instead of hanging the probe.", spec.name,
+ )
return "unknown"
exit_code = proc.returncode or 0
except FileNotFoundError:
diff --git a/jarvis/clis/registry.py b/jarvis/clis/registry.py
index 12eddafc13..413e285b47 100644
--- a/jarvis/clis/registry.py
+++ b/jarvis/clis/registry.py
@@ -16,6 +16,14 @@ from jarvis.clis.usage_log import UsageLog
log = logging.getLogger(__name__)
+# Defence-in-depth ceiling around ``probe_all`` (Prober already bounds each
+# individual probe, see jarvis/clis/prober.py CHECK_TIMEOUT_S/AUTH_TIMEOUT_S/
+# KILL_WAIT_TIMEOUT_S). This is a second, coarser backstop: bootstrap() is
+# awaited synchronously by the headless CLI path
+# (``asyncio.run(registry.bootstrap())`` in jarvis/clis/loader.py) and must
+# never hang the whole process even if a probe somehow still wedges.
+_BOOTSTRAP_CEILING_S = 30.0
+
class CliToolRegistry:
def __init__(
@@ -40,7 +48,19 @@ class CliToolRegistry:
async def bootstrap(self) -> None:
specs = list(self._catalog.all().values())
- self._status_cache = await self._prober.probe_all(specs)
+ try:
+ self._status_cache = await asyncio.wait_for(
+ self._prober.probe_all(specs), timeout=_BOOTSTRAP_CEILING_S
+ )
+ except TimeoutError:
+ log.warning(
+ "cli-registry: probe_all exceeded the %.0fs bootstrap ceiling — "
+ "keeping %d CLI(s) at 'unknown' status instead of hanging boot.",
+ _BOOTSTRAP_CEILING_S, len(specs),
+ )
+ self._status_cache = {
+ spec.name: CliStatus(error="probe_all timed out") for spec in specs
+ }
self._tools = {}
for spec in specs:
status = self._status_cache.get(spec.name)
diff --git a/tests/unit/clis/test_prober_kill_wait_timeout.py b/tests/unit/clis/test_prober_kill_wait_timeout.py
new file mode 100644
index 0000000000..9d0b6586b8
--- /dev/null
+++ b/tests/unit/clis/test_prober_kill_wait_timeout.py
@@ -0,0 +1,122 @@
+"""Regression tests: a probed child process that survives ``kill()`` must
+not wedge the prober (or the synchronous ``asyncio.run(bootstrap())`` path
+in jarvis/clis/loader.py) forever.
+
+Before this fix, ``proc.kill(); await proc.wait()`` had no timeout — a
+``.cmd``/``.bat`` shim's actual grandchild process surviving the kill signal
+would hang the probe indefinitely.
+"""
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+import pytest
+
+from jarvis.clis import prober as prober_mod
+from jarvis.clis.prober import CliStatusProber
+from jarvis.clis.spec import AuthConfig, CliSpec, InstallMethods, RiskConfig
+
+
+class _HangingProcess:
+ """Fake subprocess whose ``communicate()``/``wait()`` never return —
+ simulates a shim child that survives ``kill()``."""
+
+ def __init__(self) -> None:
+ self.killed = False
+ self.returncode: int | None = None
+
+ async def communicate(self) -> tuple[bytes, bytes]:
+ await asyncio.sleep(3600)
+ return b"", b"" # pragma: no cover
+
+ def kill(self) -> None:
+ self.killed = True
+
+ async def wait(self) -> int:
+ await asyncio.sleep(3600)
+ return 0 # pragma: no cover
+
+
+def _spec(name: str = "gh") -> CliSpec:
+ return CliSpec(
+ name=name,
+ display_name=name.upper(),
+ description="d",
+ homepage="",
+ binary_name=name,
+ check_command=(name, "--version"),
+ version_parse_regex=r"(\d+)",
+ install=InstallMethods(manual_url="https://x"),
+ auth=AuthConfig(type="oauth_cli", status_command=(name, "auth", "status")),
+ risk=RiskConfig(default_tier="monitor"),
+ )
+
+
+async def test_probe_binary_returns_when_kill_wait_hangs(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(prober_mod, "CHECK_TIMEOUT_S", 0.01)
+ monkeypatch.setattr(prober_mod, "KILL_WAIT_TIMEOUT_S", 0.01)
+ monkeypatch.setattr(prober_mod.shutil, "which", lambda _name: "/usr/bin/gh")
+
+ async def _fake_exec(*_args: Any, **_kwargs: Any) -> _HangingProcess:
+ return _HangingProcess()
+
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", _fake_exec)
+
+ prober = CliStatusProber()
+ # Outer safety net: if the fix regresses, this fails loudly instead of
+ # hanging the whole test run forever.
+ installed, version, path = await asyncio.wait_for(
+ prober._probe_binary(_spec()), timeout=2.0
+ )
+ assert installed is True
+ assert version is None
+ assert path == "/usr/bin/gh"
+
+
+async def test_probe_auth_returns_unknown_when_kill_wait_hangs(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(prober_mod, "AUTH_TIMEOUT_S", 0.01)
+ monkeypatch.setattr(prober_mod, "KILL_WAIT_TIMEOUT_S", 0.01)
+ monkeypatch.setattr(
+ prober_mod, "resolve_executable", lambda name: f"/usr/bin/{name}"
+ )
+
+ async def _fake_exec(*_args: Any, **_kwargs: Any) -> _HangingProcess:
+ return _HangingProcess()
+
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", _fake_exec)
+
+ prober = CliStatusProber()
+ status = await asyncio.wait_for(prober._probe_auth(_spec()), timeout=2.0)
+ assert status == "unknown"
+
+
+async def test_probe_completes_end_to_end_when_both_stages_hang(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Full ``probe()`` (binary + auth) must return a status, never hang, even
+ when BOTH the version-check and the auth-status child survive kill()."""
+ monkeypatch.setattr(prober_mod, "CHECK_TIMEOUT_S", 0.01)
+ monkeypatch.setattr(prober_mod, "AUTH_TIMEOUT_S", 0.01)
+ monkeypatch.setattr(prober_mod, "KILL_WAIT_TIMEOUT_S", 0.01)
+ monkeypatch.setattr(prober_mod.shutil, "which", lambda _name: "/usr/bin/gh")
+ monkeypatch.setattr(
+ prober_mod, "resolve_executable", lambda name: f"/usr/bin/{name}"
+ )
+
+ async def _fake_exec(*_args: Any, **_kwargs: Any) -> _HangingProcess:
+ return _HangingProcess()
+
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", _fake_exec)
+
+ prober = CliStatusProber()
+ status = await asyncio.wait_for(prober.probe(_spec()), timeout=2.0)
+ assert status.installed is True
+ assert status.auth_status == "unknown"
diff --git a/tests/unit/clis/test_registry_bootstrap_ceiling.py b/tests/unit/clis/test_registry_bootstrap_ceiling.py
new file mode 100644
index 0000000000..7bb8a95695
--- /dev/null
+++ b/tests/unit/clis/test_registry_bootstrap_ceiling.py
@@ -0,0 +1,87 @@
+"""Regression test: ``CliToolRegistry.bootstrap()`` must never hang forever.
+
+``CliStatusProber`` already bounds each individual probe (CHECK_TIMEOUT_S /
+AUTH_TIMEOUT_S / KILL_WAIT_TIMEOUT_S). This is a defence-in-depth backstop
+around the ``probe_all`` gather call site: if a prober implementation still
+wedges (e.g. a future bug reintroduces an unbounded await), the outer
+ceiling must still let ``bootstrap()`` return with an honest "unknown"
+status instead of hanging the caller — notably the SYNCHRONOUS
+``asyncio.run(registry.bootstrap())`` path in ``jarvis/clis/loader.py``,
+which would otherwise wedge the whole process.
+"""
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+
+import pytest
+
+from jarvis.clis import registry as registry_mod
+from jarvis.clis.registry import CliToolRegistry
+from jarvis.clis.spec import AuthConfig, CliSpec, CliStatus, InstallMethods, RiskConfig
+from jarvis.clis.usage_log import UsageLog
+
+
+class _FakeCatalog:
+ def __init__(self, specs: dict[str, CliSpec]) -> None:
+ self._specs = specs
+
+ def all(self) -> dict[str, CliSpec]:
+ return dict(self._specs)
+
+ def get(self, name: str) -> CliSpec | None:
+ return self._specs.get(name)
+
+
+class _HangingProber:
+ """Simulates a wedged prober whose ``probe_all`` never returns."""
+
+ async def probe_all(self, specs: list[CliSpec]) -> dict[str, CliStatus]:
+ await asyncio.sleep(3600)
+ return {} # pragma: no cover
+
+ async def probe(self, spec: CliSpec) -> CliStatus:
+ await asyncio.sleep(3600)
+ return CliStatus() # pragma: no cover
+
+
+def _spec(name: str) -> CliSpec:
+ return CliSpec(
+ name=name,
+ display_name=name.upper(),
+ description="d",
+ homepage="",
+ binary_name=name,
+ check_command=(name, "--version"),
+ version_parse_regex=r"(\d+)",
+ install=InstallMethods(manual_url="https://x"),
+ auth=AuthConfig(type="none"),
+ risk=RiskConfig(default_tier="monitor"),
+ )
+
+
+async def test_bootstrap_returns_unknown_statuses_when_probe_all_hangs(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(registry_mod, "_BOOTSTRAP_CEILING_S", 0.05)
+
+ specs = {"gh": _spec("gh"), "docker": _spec("docker")}
+ reg = CliToolRegistry(
+ catalog=_FakeCatalog(specs), # type: ignore[arg-type]
+ prober=_HangingProber(), # type: ignore[arg-type]
+ usage_log=UsageLog(db_path=tmp_path / "u.db"),
+ )
+
+ # Outer safety net: if the ceiling regresses, this fails loudly instead
+ # of hanging the whole test run forever.
+ await asyncio.wait_for(reg.bootstrap(), timeout=2.0)
+
+ statuses = reg.all_status()
+ assert set(statuses) == {"gh", "docker"}
+ for status in statuses.values():
+ assert status.installed is False
+ assert status.error == "probe_all timed out"
+ # A timed-out bootstrap must not crash or expose any usable tool.
+ assert reg.active_tools() == []
+ assert reg.is_bootstrapped() is True