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
feat(diagnostics): report a stalled event loop from off the loop
Ruben Lütkef0b83061c954
diff --git a/jarvis/core/loop_watchdog.py b/jarvis/core/loop_watchdog.pynew file mode 100644index 0000000000..5588446eb5--- /dev/null+++ b/jarvis/core/loop_watchdog.py@@ -0,0 +1,193 @@+"""Notice when the serving event loop stops serving — and say what is holding it.++Every WebSocket, every HTTP route and every brain turn shares one asyncio loop.+A single synchronous call on it stops all of them at once, and the symptom the+user reports is never "the loop is blocked": it is that the window says "Not+responding", that clicks land late, and that characters typed into an+Agentic-IDE pane appear seconds after they were typed — because a keystroke is+a WebSocket frame waiting behind whatever is running.++The diagnostics route ``/api/diagnostics/event-loop-lag`` already measures this,+but it cannot report the case that matters: it runs ON the loop, so a loop that+has stopped answers nothing at all. On 2026-07-28 the backend sat inside+``tomllib`` for over ten minutes and every probe from the outside — health+included — timed out with no explanation anywhere. Finding out what it was+required attaching a sampling profiler to a live process.++So this watchdog lives OFF the loop, in a plain daemon thread, and asks the one+question that survives a stall: did the loop run anything since I last looked?+When it did not, the offending Python stack goes into the log, which is where+the next person to hit this will actually look.+"""+from __future__ import annotations++import sys+import threading+import time+import traceback+from collections.abc import Callable+from typing import TYPE_CHECKING++if TYPE_CHECKING: # pragma: no cover - typing only+ import asyncio++#: How often the watchdog asks the loop to prove it is alive.+DEFAULT_INTERVAL_S = 5.0++#: Silence beyond this is reported. Well above an ordinary slow moment — a+#: garbage collection pause, a big JSON response, a burst of terminal output —+#: because a watchdog that cries wolf gets muted, and the failure it exists for+#: lasts minutes, not milliseconds.+DEFAULT_STALL_S = 15.0++#: A stall that persists is logged again at this interval rather than once per+#: check, so a loop wedged for ten minutes leaves a readable trail instead of+#: 120 identical blocks.+DEFAULT_REPEAT_S = 60.0+++class EventLoopWatchdog:+ """Watch one asyncio loop from a thread that the loop cannot block.++ The mechanism is deliberately the cheapest thing that still proves+ liveness: schedule a callback, see whether it ran. A loop executing+ anything at all drains its ready queue and the beat comes back within+ milliseconds; a loop stuck inside one synchronous call never reaches it, no+ matter how healthy the process looks from the outside.++ Args:+ loop: The loop to watch.+ interval_s: Seconds between liveness probes.+ stall_s: Silence beyond this is reported.+ repeat_s: How often an ongoing stall is re-reported.+ on_stall: Receives ``(stalled_seconds, stack_text)``. Defaults to a+ loguru warning. Injected so the behaviour is testable without+ asserting on log output.+ """++ def __init__(+ self,+ loop: asyncio.AbstractEventLoop,+ *,+ interval_s: float = DEFAULT_INTERVAL_S,+ stall_s: float = DEFAULT_STALL_S,+ repeat_s: float = DEFAULT_REPEAT_S,+ on_stall: Callable[[float, str], None] | None = None,+ ) -> None:+ self._loop = loop+ self._interval_s = max(0.1, float(interval_s))+ self._stall_s = max(self._interval_s, float(stall_s))+ self._repeat_s = max(self._interval_s, float(repeat_s))+ self._on_stall = on_stall or _log_stall+ self._stop = threading.Event()+ self._thread: threading.Thread | None = None+ # Guards the two timestamps below, which the loop thread writes and the+ # watchdog thread reads.+ self._lock = threading.Lock()+ self._last_beat = time.monotonic()+ #: Thread id of the loop, learned from the loop itself rather than+ #: assumed — the backend loop does not run on the thread that built it.+ self._loop_thread_id: int | None = None+ self._reported_at: float | None = None++ # ------------------------------------------------------------------+ # Lifecycle+ # ------------------------------------------------------------------+ def start(self) -> None:+ """Begin watching. Idempotent; safe to call on a loop already running."""+ if self._thread is not None:+ return+ self._stop.clear()+ with self._lock:+ self._last_beat = time.monotonic()+ self._thread = threading.Thread(+ target=self._run,+ name="jarvis-loop-watchdog",+ daemon=True,+ )+ self._thread.start()++ def stop(self, *, timeout: float = 2.0) -> None:+ """Stop watching and wait briefly for the thread to unwind."""+ self._stop.set()+ thread = self._thread+ self._thread = None+ if thread is not None and thread.is_alive():+ thread.join(timeout=timeout)++ # ------------------------------------------------------------------+ # Internals+ # ------------------------------------------------------------------+ def _beat(self) -> None:+ """Runs ON the loop — the proof that it is still executing callbacks."""+ with self._lock:+ self._last_beat = time.monotonic()+ self._reported_at = None+ # Learned here rather than at construction: whoever built the watchdog+ # is usually not the thread the loop ends up running on.+ self._loop_thread_id = threading.get_ident()++ def _run(self) -> None:+ while not self._stop.is_set():+ # A closing loop rejects the callback; that is a shutdown, not a+ # stall, and the watchdog simply retires with it.+ try:+ self._loop.call_soon_threadsafe(self._beat)+ except RuntimeError:+ return+ except Exception: # noqa: BLE001 - a watchdog never takes the app down+ return++ if self._stop.wait(self._interval_s):+ return++ with self._lock:+ silent_for = time.monotonic() - self._last_beat+ reported_at = self._reported_at++ if silent_for < self._stall_s:+ continue+ now = time.monotonic()+ if reported_at is not None and now - reported_at < self._repeat_s:+ continue+ with self._lock:+ self._reported_at = now+ try:+ self._on_stall(silent_for, self._loop_stack())+ except Exception: # noqa: BLE001, S110 - reporting never kills the watchdog+ pass++ def _loop_stack(self) -> str:+ """The Python stack of the loop thread, as of now.++ This is the whole value of the watchdog: not that something is slow,+ but which call it is sitting in. ``sys._current_frames`` reads it+ without a debugger, a profiler, or cooperation from the wedged thread.+ """+ thread_id = self._loop_thread_id+ if thread_id is None:+ return "<loop thread never identified — it has not run a callback yet>"+ frame = sys._current_frames().get(thread_id)+ if frame is None:+ return f"<no frame for loop thread {thread_id}>"+ return "".join(traceback.format_stack(frame))+++def _log_stall(stalled_s: float, stack_text: str) -> None:+ """Default reporter: one warning naming the duration and the guilty stack."""+ from loguru import logger++ logger.warning(+ "Event loop STALLED for {:.1f}s — every WebSocket, HTTP route and "+ "brain turn is blocked behind this call. Stack of the loop thread:\n{}",+ stalled_s,+ stack_text,+ )+++__all__ = [+ "DEFAULT_INTERVAL_S",+ "DEFAULT_REPEAT_S",+ "DEFAULT_STALL_S",+ "EventLoopWatchdog",+]diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex cce8601f4e..43cd1a41c6 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -853,6 +853,8 @@ class DesktopApp:self._backend_thread: threading.Thread | None = Noneself._backend_loop: asyncio.AbstractEventLoop | None = None+ # Off-loop stall reporter, armed once the backend loop starts serving.+ self._loop_watchdog: Any = Noneself._server: WebServer | None = None# Serve-first bootstrap: binds the admin port before the heavy build so# /api/health answers immediately and the window can appear (see@@ -1978,13 +1980,52 @@ class DesktopApp:loop.create_task(_heavy_backend_bg(), name="heavy-backend")loop.call_soon(self._start_virtual_cursor)+ # Watch this loop from OFF it, for the rest of the process's life.+ # Everything the user touches — every WebSocket frame, every route,+ # every brain turn — is serialized through the loop below, so one+ # synchronous call on it stops all of them at once. That failure+ # reaches the user as "Not responding" in the title bar and as+ # keystrokes arriving seconds late in an Agentic-IDE pane, and it+ # cannot be diagnosed from the inside: the diagnostics route that+ # measures loop lag runs ON the loop and answers nothing while it+ # is wedged (2026-07-28 — ten minutes of silence, health included,+ # and a sampling profiler attached to the live process was the only+ # way to learn it was a TOML parse). Costs one sleeping thread.+ self._start_loop_watchdog(loop)loop.run_forever()finally:+ self._stop_loop_watchdog()try:loop.close()except Exception: # noqa: BLE001pass+ # ---- Event-loop watchdog -------------------------------------------------++ def _start_loop_watchdog(self, loop: asyncio.AbstractEventLoop) -> None:+ """Arm the off-loop stall reporter. Never fatal — it is a diagnostic."""+ try:+ from jarvis.core.loop_watchdog import EventLoopWatchdog++ watchdog = EventLoopWatchdog(loop)+ watchdog.start()+ self._loop_watchdog = watchdog+ except Exception: # noqa: BLE001 — a watchdog must never break boot+ from loguru import logger as _wd_log++ _wd_log.opt(exception=True).debug("Event-loop watchdog not armed.")++ def _stop_loop_watchdog(self) -> None:+ """Retire the watchdog with the loop it watches."""+ watchdog = getattr(self, "_loop_watchdog", None)+ if watchdog is None:+ return+ self._loop_watchdog = None+ try:+ watchdog.stop()+ except Exception: # noqa: BLE001, S110 — teardown of a diagnostic+ pass+def _start_virtual_cursor(self) -> None:"""Arm the Jarvis cursor identity and (optionally) the click-pulse overlay.diff --git a/tests/unit/core/test_loop_watchdog.py b/tests/unit/core/test_loop_watchdog.pynew file mode 100644index 0000000000..3f3e0aaf13--- /dev/null+++ b/tests/unit/core/test_loop_watchdog.py@@ -0,0 +1,182 @@+"""The off-loop watchdog that names whatever is blocking the serving loop.++The failure it exists for is not hypothetical: on 2026-07-28 the backend loop+sat inside a synchronous TOML parse for over ten minutes, every probe from+outside timed out, and nothing in the log said why. These tests pin the two+properties that make the difference — it must fire while the loop is genuinely+wedged, and it must not fire for a loop that is merely busy or idle.+"""+from __future__ import annotations++import asyncio+import threading+import time++import pytest++from jarvis.core.loop_watchdog import EventLoopWatchdog+++class _Recorder:+ """Collects stall reports without going anywhere near the logger."""++ def __init__(self) -> None:+ self.calls: list[tuple[float, str]] = []+ self.seen = threading.Event()++ def __call__(self, stalled_s: float, stack: str) -> None:+ self.calls.append((stalled_s, stack))+ self.seen.set()+++def _run_loop_in_thread() -> tuple[asyncio.AbstractEventLoop, threading.Thread]:+ """A real loop on its own thread — the shape the backend actually runs."""+ loop = asyncio.new_event_loop()+ ready = threading.Event()++ def _serve() -> None:+ asyncio.set_event_loop(loop)+ loop.call_soon(ready.set)+ loop.run_forever()++ thread = threading.Thread(target=_serve, name="test-loop", daemon=True)+ thread.start()+ assert ready.wait(5.0), "the test loop never started"+ return loop, thread+++def live_loop():+ loop, thread = _run_loop_in_thread()+ yield loop+ loop.call_soon_threadsafe(loop.stop)+ thread.join(timeout=5.0)+ loop.close()+++def test_a_healthy_loop_is_never_reported(live_loop):+ """An idle loop answers every beat, so nothing is logged."""+ recorder = _Recorder()+ watchdog = EventLoopWatchdog(+ live_loop, interval_s=0.05, stall_s=0.5, on_stall=recorder+ )+ watchdog.start()+ try:+ time.sleep(1.2) # comfortably longer than the stall threshold+ finally:+ watchdog.stop()+ assert recorder.calls == [], "a responsive loop must stay silent"+++def test_a_blocked_loop_is_reported(live_loop):+ """A synchronous call on the loop is exactly what must be caught."""+ recorder = _Recorder()+ watchdog = EventLoopWatchdog(+ live_loop, interval_s=0.05, stall_s=0.4, on_stall=recorder+ )+ watchdog.start()+ release = threading.Event()++ def _wedge() -> None:+ # Stands in for the real thing: one synchronous call the loop cannot+ # yield out of. time.sleep holds the loop exactly as a slow parse does.+ release.wait(3.0)++ try:+ live_loop.call_soon_threadsafe(_wedge)+ assert recorder.seen.wait(4.0), "a wedged loop went unreported"+ finally:+ release.set()+ watchdog.stop()++ stalled_s, stack = recorder.calls[0]+ assert stalled_s >= 0.4+ assert "_wedge" in stack, f"the report must name the blocking call, got:\n{stack}"+++def test_an_ongoing_stall_is_not_repeated_every_check(live_loop):+ """A wedged loop leaves a readable trail, not one block per interval."""+ recorder = _Recorder()+ watchdog = EventLoopWatchdog(+ live_loop,+ interval_s=0.05,+ stall_s=0.2,+ repeat_s=30.0, # far beyond the test's lifetime+ on_stall=recorder,+ )+ watchdog.start()+ release = threading.Event()++ try:+ live_loop.call_soon_threadsafe(lambda: release.wait(2.0))+ assert recorder.seen.wait(3.0)+ time.sleep(0.6) # many further checks, all inside the same stall+ finally:+ release.set()+ watchdog.stop()++ assert len(recorder.calls) == 1, (+ f"an ongoing stall must be reported once per repeat window, "+ f"got {len(recorder.calls)}"+ )+++def test_recovery_re_arms_the_report(live_loop):+ """After the loop frees itself, a LATER stall is reported again."""+ recorder = _Recorder()+ watchdog = EventLoopWatchdog(+ live_loop, interval_s=0.05, stall_s=0.2, repeat_s=30.0, on_stall=recorder+ )+ watchdog.start()++ try:+ first = threading.Event()+ live_loop.call_soon_threadsafe(lambda: first.wait(1.0))+ assert recorder.seen.wait(3.0)+ first.set()++ time.sleep(0.3) # let the loop beat again — this clears the report+ recorder.seen.clear()++ second = threading.Event()+ live_loop.call_soon_threadsafe(lambda: second.wait(1.0))+ assert recorder.seen.wait(3.0), "a fresh stall after recovery went unreported"+ second.set()+ finally:+ watchdog.stop()++ assert len(recorder.calls) == 2+++def test_stop_is_idempotent_and_start_does_not_double_up(live_loop):+ """Lifecycle calls are safe to repeat — boot paths retry things."""+ watchdog = EventLoopWatchdog(live_loop, interval_s=0.05, stall_s=5.0)+ watchdog.start()+ watchdog.start() # must not spawn a second thread+ watchdog.stop()+ watchdog.stop() # must not raise+++def test_a_closed_loop_retires_the_watchdog_quietly():+ """Shutdown is not a stall — the watchdog goes down with the loop."""+ loop, thread = _run_loop_in_thread()+ recorder = _Recorder()+ watchdog = EventLoopWatchdog(+ loop, interval_s=0.05, stall_s=0.2, on_stall=recorder+ )+ watchdog.start()++ loop.call_soon_threadsafe(loop.stop)+ thread.join(timeout=5.0)+ loop.close()++ time.sleep(0.5)+ watchdog.stop()+ assert recorder.calls == [], "a closed loop must not be reported as stalled"+++def test_stack_is_reported_even_before_any_beat_landed(live_loop):+ """The reporter never raises, even asked before the loop identified itself."""+ watchdog = EventLoopWatchdog(live_loop, interval_s=5.0, stall_s=5.0)+ text = watchdog._loop_stack()+ assert isinstance(text, str) and text