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(realtime): recover abandoned local pipeline slots
rubenluetke10-beepceacadae282f
diff --git a/jarvis/realtime/local_server/supervisor.py b/jarvis/realtime/local_server/supervisor.pyindex 13464d4bde..3cbbd8e563 100644--- a/jarvis/realtime/local_server/supervisor.py+++ b/jarvis/realtime/local_server/supervisor.py@@ -61,10 +61,12 @@ OWNED_STARTUP_TIMEOUT_S = RUNTIME_READY_TIMEOUT_S# The managed process is meant to be warm before a user calls. Poll its# ownership cheaply once a second so an idle native crash starts recovering-# immediately; probe the full model pool less often to catch a live-but-wedged-# child without filling the server log with health requests.+# immediately; probe the full model pool often enough that an abandoned+# capacity-one session cannot make the next caller wait minutes. Replacement+# still requires 30 seconds of continuously unavailable capacity and a second+# generation-bound probe under the lifecycle lease.RUNTIME_MONITOR_POLL_S = 1.0-RUNTIME_MONITOR_POOL_INTERVAL_S = 30.0+RUNTIME_MONITOR_POOL_INTERVAL_S = 5.0RUNTIME_MONITOR_UNREADY_GRACE_S = 30.0_MAX_POOL_RESPONSE_BYTES = 64 * 1024@@ -251,14 +253,31 @@ def probe_runtime(base_url: str, timeout: float = 0.75) -> dict[str, int] | Noneif not isinstance(state, str) or state not in allowed_states:return Nonestates.append(state)+ idle = states.count("idle")+ active = states.count("active")+ draining = states.count("draining")+ stuck = states.count("stuck")+ if in_use != active + draining + stuck:+ return Nonereturn {"size": size,"in_use": in_use,- "available": size - in_use,- "stuck": states.count("stuck"),+ "available": idle,+ "active": active,+ "draining": draining,+ "stuck": stuck,}+def _pool_has_no_usable_capacity(pool: dict[str, int]) -> bool:+ """Whether every slot is abandoned and no client is still connected."""+ return (+ pool.get("available") == 0+ and pool.get("active") == 0+ and pool.get("draining", 0) + pool.get("stuck", 0) == pool.get("size")+ )++def wait_until_ready(base_url: str,*,@@ -692,13 +711,22 @@ def _uses_loopback_bind(command: str) -> bool:return host is not None and _is_loopback(host.strip().strip("[]"))-def ensure_running(*, launch_command: str, base_url: str, reason: str) -> str:+def ensure_running(+ *,+ launch_command: str,+ base_url: str,+ reason: str,+ replace_unavailable_generation: tuple[int, float, str] | None = None,+) -> str:"""Start the server if — and only if — starting can help.Returns ``"already-running"`` (port served, or our recorded process isalive and presumably booting), ``"spawned"``, or ``"refused:<why>"``.The single spawn path for BOTH the boot-time prewarm and the connect-time- revive, which is what makes their race harmless.+ revive, which is what makes their race harmless. The monitor may also pass+ the exact generation it observed with no usable capacity; replacement then+ happens only after the pool and ownership are verified again under the+ lifecycle lease."""command = (launch_command or "").strip()if not command:@@ -752,6 +780,39 @@ def ensure_running(*, launch_command: str, base_url: str, reason: str) -> str:pool = Nonealive = Falseport_open = _port_open(port, timeout=0.25)+ if (+ pool is not None+ and replace_unavailable_generation is not None+ and _pool_has_no_usable_capacity(pool)+ ):+ if managed_root is None:+ return "refused:not-managed"+ if _owned_generation() != replace_unavailable_generation:+ return "refused:generation-changed"+ owned_command = _verified_owned_command()+ if (+ not alive+ or owned_command is None+ or managed_install_root(owned_command) != managed_root+ ):+ return "refused:unverified-owner"+ changed, message = _stop_owned_unlocked(+ owned_only=True,+ install_root=managed_root,+ )+ if not changed:+ log.warning(+ "local-realtime supervisor: unavailable pool cleanup failed (%s)",+ message,+ )+ return "refused:stuck-process"+ log.warning(+ "local-realtime supervisor: replaced an owned runtime whose "+ "entire pool remained unavailable without an active client"+ )+ pool = None+ alive = False+ port_open = _port_open(port, timeout=0.25)if pool is not None:return "already-running"if alive:@@ -961,6 +1022,7 @@ def _revive_from_monitor(base_url: str,reason: str,cancel_event: threading.Event,+ unavailable_generation: tuple[int, float, str] | None = None,) -> str:"""Run one generation-bound revive and return its explicit outcome."""try:@@ -975,6 +1037,7 @@ def _revive_from_monitor(launch_command=launch_command,base_url=base_url,reason=reason,+ replace_unavailable_generation=unavailable_generation,)if outcome != "spawned":return outcome@@ -1004,6 +1067,7 @@ def _runtime_monitor("""Detect an idle process exit promptly and a wedged pool conservatively."""next_pool_probe = time.monotonic() + RUNTIME_MONITOR_POOL_INTERVAL_Sunready_since: float | None = None+ unhealthy_kind = ""last_outcome = ""try:while not stop_event.wait(RUNTIME_MONITOR_POLL_S):@@ -1029,6 +1093,7 @@ def _runtime_monitor(if outcome == "ready":log.info("local-realtime monitor: crashed runtime recovered")unready_since = None+ unhealthy_kind = ""next_pool_probe = (time.monotonic() + RUNTIME_MONITOR_POOL_INTERVAL_S)@@ -1044,28 +1109,59 @@ def _runtime_monitor(if now < next_pool_probe:continuenext_pool_probe = now + RUNTIME_MONITOR_POOL_INTERVAL_S- if probe_runtime(base_url, timeout=0.75) is not None:+ pool = probe_runtime(base_url, timeout=0.75)+ kind = (+ "unready"+ if pool is None+ else "unavailable"+ if _pool_has_no_usable_capacity(pool)+ else ""+ )+ if not kind:unready_since = None+ unhealthy_kind = ""last_outcome = ""continue- if unready_since is None:+ if unready_since is None or unhealthy_kind != kind:unready_since = now+ unhealthy_kind = kind+ last_outcome = ""log.warning(- "local-realtime monitor: owned process stopped reporting "- "a ready model pool; waiting for a second failed probe"+ "local-realtime monitor: owned process has %s; waiting "+ "for the recovery grace period",+ (+ "no usable pool capacity and no active client"+ if kind == "unavailable"+ else "stopped reporting a ready model pool"+ ),)continueif now - unready_since < RUNTIME_MONITOR_UNREADY_GRACE_S:continue+ unavailable_generation = None+ if kind == "unavailable":+ unavailable_generation = _owned_generation()+ if unavailable_generation is None:+ outcome = "refused:unverified-generation"+ if outcome != last_outcome:+ log.warning(+ "local-realtime monitor: unavailable recovery "+ "deferred (%s)",+ outcome,+ )+ last_outcome = outcome+ continueoutcome = _revive_from_monitor(launch_command=launch_command,base_url=base_url,- reason="watchdog-unready",+ reason=f"watchdog-{kind}",cancel_event=stop_event,+ unavailable_generation=unavailable_generation,)if outcome == "ready":log.info("local-realtime monitor: wedged runtime recovered")unready_since = None+ unhealthy_kind = ""next_pool_probe = (time.monotonic() + RUNTIME_MONITOR_POOL_INTERVAL_S)diff --git a/tests/unit/realtime/local_server/test_supervisor.py b/tests/unit/realtime/local_server/test_supervisor.pyindex b53971b985..913a04c482 100644--- a/tests/unit/realtime/local_server/test_supervisor.py+++ b/tests/unit/realtime/local_server/test_supervisor.py@@ -81,11 +81,13 @@ def test_runtime_probe_requires_a_valid_loaded_pool(monkeypatch) -> None:return self._payload[:limit]payload = {- "size": 2,- "in_use": 1,+ "size": 4,+ "in_use": 3,"units": [{"index": 0, "state": "active", "session_id": "private"},{"index": 1, "state": "idle", "session_id": None},+ {"index": 2, "state": "draining", "session_id": "private"},+ {"index": 3, "state": "stuck", "session_id": "private"},],}class _Connection:@@ -103,16 +105,54 @@ def test_runtime_probe_requires_a_valid_loaded_pool(monkeypatch) -> None:monkeypatch.setattr(http.client, "HTTPConnection", _Connection)assert supervisor.probe_runtime("http://localhost:8765") == {- "size": 2,- "in_use": 1,+ "size": 4,+ "in_use": 3,"available": 1,- "stuck": 0,+ "active": 1,+ "draining": 1,+ "stuck": 1,}+ payload["in_use"] = 2+ assert supervisor.probe_runtime("http://localhost:8765") is None+ payload["in_use"] = 3payload["units"] = []assert supervisor.probe_runtime("http://localhost:8765") is None+def test_only_an_abandoned_full_pool_has_no_usable_capacity() -> None:+ assert supervisor._pool_has_no_usable_capacity(+ {+ "size": 1,+ "in_use": 1,+ "available": 0,+ "active": 0,+ "draining": 1,+ "stuck": 0,+ }+ )+ assert not supervisor._pool_has_no_usable_capacity(+ {+ "size": 1,+ "in_use": 1,+ "available": 0,+ "active": 1,+ "draining": 0,+ "stuck": 0,+ }+ )+ assert not supervisor._pool_has_no_usable_capacity(+ {+ "size": 2,+ "in_use": 1,+ "available": 1,+ "active": 0,+ "draining": 0,+ "stuck": 1,+ }+ )++def test_wait_until_ready_ignores_tcp_and_waits_for_the_pool(monkeypatch) -> None:answers = iter([None, None, {"size": 1, "in_use": 0, "available": 1, "stuck": 0}])monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: next(answers))@@ -658,6 +698,174 @@ def test_a_ready_owned_loopback_bind_is_not_restarted(monkeypatch, tmp_path) ->)+def test_an_abandoned_owned_pool_is_replaced_generation_safely(+ monkeypatch, tmp_path+) -> None:+ from jarvis.realtime.local_server import install++ supervisor._reset_for_tests()+ root = tmp_path / "local_realtime"+ command = f'"{root / "venv" / "server.exe"}" --mode realtime --ws_host 127.0.0.1'+ generation = (4711, 1000.0, "generation-a")+ pool = {+ "size": 1,+ "in_use": 1,+ "available": 0,+ "active": 0,+ "draining": 1,+ "stuck": 0,+ }+ monkeypatch.setattr(supervisor, "managed_install_root", lambda value: root)+ monkeypatch.setattr(install, "snapshot", lambda: {"running": False})+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: pool)+ monkeypatch.setattr(supervisor, "_port_open", lambda *args, **kwargs: False)+ monkeypatch.setattr(supervisor, "_owned_process", lambda: (4711, True))+ monkeypatch.setattr(supervisor, "_owned_generation", lambda: generation)+ monkeypatch.setattr(supervisor, "_verified_owned_command", lambda: command)+ stopped: list[Path] = []+ monkeypatch.setattr(+ supervisor,+ "_stop_owned_unlocked",+ lambda **kwargs: stopped.append(kwargs["install_root"]) or (True, "stopped"),+ )+ monkeypatch.setattr(supervisor, "_kill_by_install_root", lambda root: (0, 0))+ spawned: list[str] = []+ monkeypatch.setattr(+ supervisor,+ "_spawn",+ lambda candidate, **kwargs: spawned.append(candidate) or 7331,+ )+ monkeypatch.setattr(supervisor, "_write_pidfile", lambda *args: True)++ outcome = supervisor.ensure_running(+ launch_command=command,+ base_url="http://127.0.0.1:8765",+ reason="watchdog-unavailable",+ replace_unavailable_generation=generation,+ )++ assert outcome == "spawned"+ assert stopped == [root]+ assert spawned == [command]+++def test_unavailable_pool_replacement_skips_a_newer_generation(+ monkeypatch, tmp_path+) -> None:+ from jarvis.realtime.local_server import install++ root = tmp_path / "local_realtime"+ command = f'"{root / "venv" / "server.exe"}" --mode realtime --ws_host 127.0.0.1'+ expected = (4711, 1000.0, "generation-a")+ pool = {+ "size": 1,+ "in_use": 1,+ "available": 0,+ "active": 0,+ "draining": 0,+ "stuck": 1,+ }+ monkeypatch.setattr(supervisor, "managed_install_root", lambda value: root)+ monkeypatch.setattr(install, "snapshot", lambda: {"running": False})+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: pool)+ monkeypatch.setattr(supervisor, "_port_open", lambda *args, **kwargs: True)+ monkeypatch.setattr(supervisor, "_owned_process", lambda: (7331, True))+ monkeypatch.setattr(+ supervisor,+ "_owned_generation",+ lambda: (7331, 2000.0, "generation-b"),+ )+ monkeypatch.setattr(supervisor, "_verified_owned_command", lambda: command)++ def forbidden_stop(**kwargs):+ raise AssertionError("a stale monitor must not stop a newer child")++ monkeypatch.setattr(supervisor, "_stop_owned_unlocked", forbidden_stop)+ assert (+ supervisor.ensure_running(+ launch_command=command,+ base_url="http://127.0.0.1:8765",+ reason="watchdog-unavailable",+ replace_unavailable_generation=expected,+ )+ == "refused:generation-changed"+ )+++def test_active_full_pool_is_never_replaced(monkeypatch, tmp_path) -> None:+ from jarvis.realtime.local_server import install++ root = tmp_path / "local_realtime"+ command = f'"{root / "venv" / "server.exe"}" --mode realtime --ws_host 127.0.0.1'+ generation = (4711, 1000.0, "generation-a")+ pool = {+ "size": 1,+ "in_use": 1,+ "available": 0,+ "active": 1,+ "draining": 0,+ "stuck": 0,+ }+ monkeypatch.setattr(supervisor, "managed_install_root", lambda value: root)+ monkeypatch.setattr(install, "snapshot", lambda: {"running": False})+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: pool)+ monkeypatch.setattr(supervisor, "_port_open", lambda *args, **kwargs: True)+ monkeypatch.setattr(supervisor, "_owned_process", lambda: (4711, True))+ monkeypatch.setattr(supervisor, "_verified_owned_command", lambda: command)++ def forbidden_stop(**kwargs):+ raise AssertionError("a connected client must never be stopped")++ monkeypatch.setattr(supervisor, "_stop_owned_unlocked", forbidden_stop)+ assert (+ supervisor.ensure_running(+ launch_command=command,+ base_url="http://127.0.0.1:8765",+ reason="watchdog-unavailable",+ replace_unavailable_generation=generation,+ )+ == "already-running"+ )+++def test_recovered_pool_is_not_stopped_by_a_stale_unavailable_observation(+ monkeypatch, tmp_path+) -> None:+ from jarvis.realtime.local_server import install++ root = tmp_path / "local_realtime"+ command = f'"{root / "venv" / "server.exe"}" --mode realtime --ws_host 127.0.0.1'+ generation = (4711, 1000.0, "generation-a")+ pool = {+ "size": 1,+ "in_use": 0,+ "available": 1,+ "active": 0,+ "draining": 0,+ "stuck": 0,+ }+ monkeypatch.setattr(supervisor, "managed_install_root", lambda value: root)+ monkeypatch.setattr(install, "snapshot", lambda: {"running": False})+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: pool)+ monkeypatch.setattr(supervisor, "_port_open", lambda *args, **kwargs: True)+ monkeypatch.setattr(supervisor, "_owned_process", lambda: (4711, True))+ monkeypatch.setattr(supervisor, "_verified_owned_command", lambda: command)++ def forbidden_stop(**kwargs):+ raise AssertionError("a pool that recovered under the lease must stay alive")++ monkeypatch.setattr(supervisor, "_stop_owned_unlocked", forbidden_stop)+ assert (+ supervisor.ensure_running(+ launch_command=command,+ base_url="http://127.0.0.1:8765",+ reason="watchdog-unavailable",+ replace_unavailable_generation=generation,+ )+ == "already-running"+ )++def test_pid_reuse_is_never_trusted(monkeypatch, tmp_path) -> None:"""A rebooted machine can hand the recorded pid to an innocent process;a create_time mismatch must read as NOT ours."""@@ -845,6 +1053,91 @@ def test_runtime_monitor_restarts_and_rewarms_a_dead_owned_server(assert calls == ["ensure:watchdog-exit", "ready", "marker", "brain"]+def test_runtime_monitor_replaces_an_abandoned_pool_after_the_grace(+ monkeypatch, tmp_path+) -> None:+ root = tmp_path / "local_realtime"+ command = f'"{root / "server.exe"}" --mode realtime'+ generation = (4711, 1000.0, "generation-a")+ pool = {+ "size": 1,+ "in_use": 1,+ "available": 0,+ "active": 0,+ "draining": 1,+ "stuck": 0,+ }+ monkeypatch.setattr(supervisor, "RUNTIME_MONITOR_POLL_S", 0.0)+ monkeypatch.setattr(supervisor, "RUNTIME_MONITOR_POOL_INTERVAL_S", 0.0)+ monkeypatch.setattr(supervisor, "RUNTIME_MONITOR_UNREADY_GRACE_S", 0.0)+ monkeypatch.setattr(supervisor, "managed_install_root", lambda value: root)+ monkeypatch.setattr(supervisor, "_owned_process", lambda: (4711, True))+ monkeypatch.setattr(supervisor, "_owned_generation", lambda: generation)+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: pool)+ stop_event = threading.Event()+ revives: list[dict[str, Any]] = []++ def revive(**kwargs: Any) -> str:+ revives.append(kwargs)+ stop_event.set()+ return "ready"++ monkeypatch.setattr(supervisor, "_revive_from_monitor", revive)++ supervisor._runtime_monitor(+ command,+ "http://127.0.0.1:8765",+ stop_event,+ (command, "http://127.0.0.1:8765/v1/pool"),+ )++ assert len(revives) == 1+ assert revives[0]["reason"] == "watchdog-unavailable"+ assert revives[0]["unavailable_generation"] == generation+++def test_runtime_monitor_does_not_replace_a_connected_full_pool(+ monkeypatch, tmp_path+) -> None:+ root = tmp_path / "local_realtime"+ command = f'"{root / "server.exe"}" --mode realtime'+ pool = {+ "size": 1,+ "in_use": 1,+ "available": 0,+ "active": 1,+ "draining": 0,+ "stuck": 0,+ }++ class _OneIterationEvent(threading.Event):+ def __init__(self) -> None:+ super().__init__()+ self._waits = 0++ def wait(self, timeout: float) -> bool:+ del timeout+ self._waits += 1+ return self._waits > 1++ monkeypatch.setattr(supervisor, "RUNTIME_MONITOR_POOL_INTERVAL_S", 0.0)+ monkeypatch.setattr(supervisor, "managed_install_root", lambda value: root)+ monkeypatch.setattr(supervisor, "_owned_process", lambda: (4711, True))+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: pool)+ monkeypatch.setattr(+ supervisor,+ "_revive_from_monitor",+ lambda **kwargs: pytest.fail("an active call must never be replaced"),+ )++ supervisor._runtime_monitor(+ command,+ "http://127.0.0.1:8765",+ _OneIterationEvent(),+ (command, "http://127.0.0.1:8765/v1/pool"),+ )++def test_runtime_monitor_is_singleton_for_one_managed_generation(monkeypatch, tmp_path) -> None: