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): event-loop task snapshot endpoint to name busy-loop owners
Ruben Lütke5cfa0b685bed
diff --git a/jarvis/ui/web/diagnostics_routes.py b/jarvis/ui/web/diagnostics_routes.pynew file mode 100644index 0000000000..8a784b5c99--- /dev/null+++ b/jarvis/ui/web/diagnostics_routes.py@@ -0,0 +1,118 @@+"""Event-loop diagnostics — snapshot every asyncio task with its await stack.++Built to hunt the AP-20-class busy-loop where anyio's+``CancelScope._deliver_cancellation`` reschedules itself on every event-loop+iteration because some task inside the cancelled scope never finishes+(measured 2026-07-10/11: ~95 % of one core burned while the app idles).+py-spy cannot name the owner — the sampled stack only shows the event-loop+callback, and an elevated process denies attachment anyway — so the app+reports on itself from inside the loop.++Read-only, stdlib-only, and imported lazily by ``server.py`` like every other+route module (AP-26: nothing here runs at boot; the handler only does work+when called).+"""+from __future__ import annotations++import asyncio+import contextlib+from typing import Any++from fastapi import APIRouter++router = APIRouter(prefix="/api/diagnostics", tags=["diagnostics"])++# Stack frames reported per task. Enough to see the await chain that pins a+# task inside a cancelled scope without shipping megabytes of JSON.+_STACK_LIMIT = 16+++def _task_snapshot(task: asyncio.Task[Any]) -> dict[str, Any]:+ """One task as a JSON-safe dict; private-attr reads are best-effort.++ ``cancelling()`` (Py 3.11+) is the number of pending cancel requests —+ a task that stays alive with ``cancelling > 0`` across two snapshots is+ exactly the busy-loop culprit this endpoint exists to name.+ """+ try:+ stack_frames = task.get_stack(limit=_STACK_LIMIT)+ stack = [+ f"{f.f_code.co_name} ({f.f_code.co_filename}:{f.f_lineno})"+ for f in stack_frames+ ]+ except Exception as exc: # noqa: BLE001 — diagnostics must never raise+ stack = [f"<stack unavailable: {exc}>"]++ cancelling = 0+ with contextlib.suppress(Exception): # pre-3.11 or exotic task impl+ cancelling = task.cancelling()++ must_cancel = None+ fut_waiter = None+ with contextlib.suppress(Exception): # CPython-private, absent elsewhere+ must_cancel = bool(task._must_cancel) # type: ignore[attr-defined]+ waiter = task._fut_waiter # type: ignore[attr-defined]+ fut_waiter = repr(waiter)[:300] if waiter is not None else None++ exception = None+ if task.done() and not task.cancelled():+ with contextlib.suppress(Exception):+ exc_obj = task.exception()+ exception = repr(exc_obj)[:300] if exc_obj is not None else None++ return {+ "name": task.get_name(),+ "coro": repr(task.get_coro())[:300],+ "done": task.done(),+ "cancelled": task.cancelled(),+ "cancelling": cancelling,+ "must_cancel": must_cancel,+ "fut_waiter": fut_waiter,+ "exception": exception,+ "stack": stack,+ }++[email protected]("/event-loop-tasks")+async def event_loop_tasks() -> dict[str, Any]:+ """Snapshot all tasks on the serving loop, suspects first.++ Suspects (``cancelling > 0`` or ``must_cancel``) sort to the top: those+ are the tasks anyio is trying — and failing — to cancel, i.e. the owners+ of a ``_deliver_cancellation`` busy-loop. Two snapshots a few seconds+ apart separate a task that is legitimately shutting down from one that is+ stuck forever.+ """+ tasks = [_task_snapshot(t) for t in asyncio.all_tasks()]+ tasks.sort(+ key=lambda t: (t["cancelling"], 1 if t["must_cancel"] else 0),+ reverse=True,+ )+ return {+ "total": len(tasks),+ "suspects": sum(+ 1 for t in tasks if t["cancelling"] or t["must_cancel"]+ ),+ "tasks": tasks,+ }++[email protected]("/event-loop-lag")+async def event_loop_lag() -> dict[str, Any]:+ """Measure scheduling lag of the serving loop.++ Sleeps 0 four times and reports how long each round-trip through the+ ready queue took. A healthy idle loop yields microseconds; a loop being+ spammed by a rescheduling callback (the busy-loop signature) shows+ consistently elevated lag.+ """+ loop = asyncio.get_running_loop()+ lags_ms: list[float] = []+ for _ in range(4):+ t0 = loop.time()+ await asyncio.sleep(0)+ lags_ms.append((loop.time() - t0) * 1000.0)+ return {"lags_ms": lags_ms, "max_ms": max(lags_ms)}+++__all__ = ["router"]diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex aee87039a4..c98302a736 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -231,6 +231,7 @@ class WebServer:from .drop_routes import router as drop_routerfrom .contacts_routes import router as contacts_routerfrom .control_routes import router as control_router+ from .diagnostics_routes import router as diagnostics_routerfrom .dictionary_routes import router as dictionary_routerfrom .docs_routes import router as docs_routerfrom .federation_proxy_routes import router as federation_proxy_router@@ -282,6 +283,9 @@ class WebServer:conductor_router = Noneapp.include_router(mcp_router)app.include_router(tools_router)+ # Event-loop diagnostics (read-only) — names the owner of an AP-20+ # cancellation busy-loop from inside the loop; see diagnostics_routes.+ app.include_router(diagnostics_router)app.include_router(provider_router)app.include_router(antigravity_router)app.include_router(claude_router)diff --git a/tests/unit/ui/web/test_diagnostics_routes.py b/tests/unit/ui/web/test_diagnostics_routes.pynew file mode 100644index 0000000000..d6f84acb3d--- /dev/null+++ b/tests/unit/ui/web/test_diagnostics_routes.py@@ -0,0 +1,122 @@+"""REST-route tests for the event-loop diagnostics endpoints.++The endpoint exists to NAME the owner of an AP-20-class cancellation+busy-loop (anyio ``_deliver_cancellation`` rescheduling forever because a+task inside the cancelled scope never finishes). The tests verify the two+signals the hunt relies on: a pending-cancel task surfaces with+``cancelling > 0`` and sorts to the top, and every snapshot carries a usable+await stack.++Helper tasks are spawned/torn down through tiny in-app routes because the+TestClient owns the event loop — test code never touches the loop directly.+Snapshots are taken first and asserted after cleanup so a failing assertion+cannot leak a pending task into loop teardown.+"""+from __future__ import annotations++import asyncio+from typing import Any++from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.ui.web.diagnostics_routes import router+++def _app() -> FastAPI:+ app = FastAPI()+ app.include_router(router)+ return app+++def test_event_loop_tasks_reports_running_tasks():+ app = _app()++ async def _sleeper() -> None:+ await asyncio.sleep(30)++ @app.get("/spawn-sleeper")+ async def spawn_sleeper() -> dict[str, bool]:+ task = asyncio.ensure_future(_sleeper())+ task.set_name("diag-test-sleeper")+ app.state.sleeper = task+ return {"ok": True}++ @app.get("/kill-sleeper")+ async def kill_sleeper() -> dict[str, bool]:+ app.state.sleeper.cancel()+ try:+ await app.state.sleeper+ except asyncio.CancelledError:+ pass+ return {"ok": True}++ with TestClient(app) as client:+ assert client.get("/spawn-sleeper").status_code == 200+ body: dict[str, Any] = client.get("/api/diagnostics/event-loop-tasks").json()+ assert client.get("/kill-sleeper").status_code == 200++ assert body["total"] >= 1+ named = [t for t in body["tasks"] if t["name"] == "diag-test-sleeper"]+ assert named, "spawned task must appear in the snapshot"+ entry = named[0]+ assert entry["cancelling"] == 0+ assert entry["done"] is False+ assert any("_sleeper" in frame for frame in entry["stack"])+++def test_cancel_refusing_task_sorts_first_with_cancelling_count():+ app = _app()+ stop = asyncio.Event()++ async def _refuses_cancel() -> None:+ # Deliberate AP-20 reproduction: swallow the cancel and keep looping —+ # exactly the shape that pins a CancelScope. The ``stop`` event is the+ # escape hatch the real bug lacks, so the TEST can always terminate it.+ while not stop.is_set():+ try:+ await asyncio.sleep(30)+ except asyncio.CancelledError:+ continue++ @app.get("/spawn-zombie")+ async def spawn_zombie() -> dict[str, bool]:+ task = asyncio.ensure_future(_refuses_cancel())+ task.set_name("diag-test-zombie")+ # Let the task take its first step into ``sleep`` before cancelling;+ # a cancel BEFORE the first step lands outside the try and kills it.+ await asyncio.sleep(0)+ task.cancel()+ app.state.zombie = task+ return {"ok": True}++ @app.get("/kill-zombie")+ async def kill_zombie() -> dict[str, bool]:+ stop.set()+ task = app.state.zombie+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass+ return {"ok": True}++ with TestClient(app) as client:+ assert client.get("/spawn-zombie").status_code == 200+ body: dict[str, Any] = client.get("/api/diagnostics/event-loop-tasks").json()+ assert client.get("/kill-zombie").status_code == 200++ named = [t for t in body["tasks"] if t["name"] == "diag-test-zombie"]+ assert named, "zombie task must appear in the snapshot"+ assert named[0]["cancelling"] >= 1 or named[0]["must_cancel"]+ assert body["suspects"] >= 1+ # Suspects sort to the top of the list.+ assert body["tasks"][0]["cancelling"] >= 1 or body["tasks"][0]["must_cancel"]+++def test_event_loop_lag_returns_measurements():+ app = _app()+ with TestClient(app) as client:+ body = client.get("/api/diagnostics/event-loop-lag").json()+ assert len(body["lags_ms"]) == 4+ assert body["max_ms"] >= 0.0