Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(runtime): read runtime command markers off the controller loop (#2770)

Call White1ff3251e3aae
diff --git a/core/runtime_commands.py b/core/runtime_commands.py
index 6d1a82ba4..20cfed33e 100644
--- a/core/runtime_commands.py
+++ b/core/runtime_commands.py
@@ -67,7 +67,7 @@ class RuntimeCommandWatcher:
if self._task and not self._task.done():
return
try:
- self._directory.mkdir(parents=True, exist_ok=True)
+ await asyncio.to_thread(self._directory.mkdir, parents=True, exist_ok=True)
except OSError as exc:
logger.warning("Runtime command watcher disabled: %s", exc)
return
@@ -100,10 +100,21 @@ class RuntimeCommandWatcher:
continue
async def _sweep_once(self) -> None:
+ # The directory lives on the state disk, so reading it runs on a
+ # thread: a slow disk stalled the controller loop for 2.6 s in this
+ # listing (#2768). The refreshes themselves run on the loop, in the
+ # order the scan found their markers.
+ for backend, marker in await asyncio.to_thread(self._scan):
+ await self._handle_restart(backend, marker)
+
+ def _scan(self) -> list[tuple[str, Path]]:
+ """The restart markers to handle, after dropping unknown ones and orphaned ``.err`` companions."""
+
try:
entries = list(self._directory.iterdir())
except FileNotFoundError:
- return
+ return []
+ pending: list[tuple[str, Path]] = []
for marker in entries:
if not marker.is_file():
continue
@@ -125,7 +136,8 @@ class RuntimeCommandWatcher:
logger.debug("Ignoring unsupported backend marker: %s", backend)
marker.unlink(missing_ok=True)
continue
- await self._handle_restart(backend, marker)
+ pending.append((backend, marker))
+ return pending
@staticmethod
def _maybe_evict_stale_err(err_marker: Path) -> None:
@@ -150,7 +162,11 @@ class RuntimeCommandWatcher:
logger.debug("Could not evict stale err marker %s: %s", err_marker, exc)
async def _handle_restart(self, backend: str, marker: Path) -> None:
- metadata = self._read_marker_metadata(marker)
+ # Checked again just before the refresh: while an earlier marker's
+ # refresh ran, the requester may have timed out and removed this one.
+ metadata = await asyncio.to_thread(self._pending_metadata, marker)
+ if metadata is None:
+ return
if metadata:
logger.info("Runtime command: refresh backend=%s metadata=%s", backend, metadata)
else:
@@ -160,21 +176,29 @@ class RuntimeCommandWatcher:
)
if handler is None:
logger.warning("AgentAuthService missing _refresh_backend_runtime; dropping marker")
- self._fail_marker(marker, "refresh handler unavailable")
+ await asyncio.to_thread(self._fail_marker, marker, "refresh handler unavailable")
return
try:
await handler(backend)
except Exception as exc:
logger.error("Backend refresh failed for %s: %s", backend, exc, exc_info=True)
- self._fail_marker(marker, str(exc) or exc.__class__.__name__)
+ await asyncio.to_thread(self._fail_marker, marker, str(exc) or exc.__class__.__name__)
return
# Success path: silently drop the marker so the UI server reads the
# absence-of-``.err`` as a clean ack.
try:
- marker.unlink(missing_ok=True)
+ await asyncio.to_thread(marker.unlink, missing_ok=True)
except OSError as exc: # pragma: no cover - best-effort cleanup
logger.debug("Could not remove marker %s: %s", marker, exc)
+ @classmethod
+ def _pending_metadata(cls, marker: Path) -> Optional[dict]:
+ """The marker's metadata while its request still stands; None once the marker is gone."""
+
+ if not marker.is_file():
+ return None
+ return cls._read_marker_metadata(marker)
+
@staticmethod
def _read_marker_metadata(marker: Path) -> dict:
try:
diff --git a/tests/test_runtime_commands.py b/tests/test_runtime_commands.py
index a757a93fb..68a6646e7 100644
--- a/tests/test_runtime_commands.py
+++ b/tests/test_runtime_commands.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio
import os
import sys
+import threading
import time
from pathlib import Path
from types import SimpleNamespace
@@ -157,3 +158,71 @@ def test_sweep_evicts_orphaned_err_companion(tmp_path: Path) -> None:
asyncio.run(watcher._sweep_once())
assert not err_marker.exists()
+
+
+def test_a_slow_directory_listing_never_holds_the_controller_loop(tmp_path: Path, monkeypatch) -> None:
+ """#2768: the sweep reads the state disk off the loop, so a slow disk delays only the sweep.
+
+ On a USB state disk the listing alone held the controller loop for 2.6 s,
+ and with it every Session.
+ """
+
+ calls: list[str] = []
+
+ async def handler(name: str) -> None:
+ calls.append(name)
+
+ watcher, marker = _make_watcher(tmp_path, handler)
+ listing = threading.Event()
+ loop_answered = threading.Event()
+ answered_during_listing: list[bool] = []
+ real_iterdir = Path.iterdir
+
+ def slow_iterdir(self):
+ if self == tmp_path:
+ listing.set()
+ answered_during_listing.append(loop_answered.wait(2))
+ return real_iterdir(self)
+
+ monkeypatch.setattr(Path, "iterdir", slow_iterdir)
+
+ async def scenario() -> None:
+ sweep = asyncio.create_task(watcher._sweep_once())
+ while not listing.is_set():
+ await asyncio.sleep(0.01)
+ # The loop is free to serve other work while the listing waits on the disk.
+ loop_answered.set()
+ await sweep
+
+ asyncio.run(asyncio.wait_for(scenario(), 10))
+
+ assert answered_during_listing == [True]
+ assert calls == ["opencode"]
+ assert not marker.exists()
+
+
+def test_a_marker_withdrawn_during_an_earlier_refresh_is_not_run(tmp_path: Path) -> None:
+ """A requester whose acknowledgement wait expired while another backend refreshed removed its marker.
+
+ The sweep found both markers before either refresh ran; the withdrawn one
+ must not run after the first refresh finishes.
+ """
+
+ markers = {name: tmp_path / f"restart-{name}.cmd" for name in ("claude", "opencode")}
+ calls: list[str] = []
+
+ async def handler(name: str) -> None:
+ calls.append(name)
+ for other, marker in markers.items():
+ if other != name:
+ marker.unlink(missing_ok=True)
+
+ auth_service = SimpleNamespace(_refresh_backend_runtime=handler)
+ watcher = RuntimeCommandWatcher(SimpleNamespace(agent_auth_service=auth_service), directory=tmp_path) # type: ignore[arg-type]
+ for marker in markers.values():
+ marker.write_text("{}", encoding="utf-8")
+
+ asyncio.run(watcher._sweep_once())
+
+ assert len(calls) == 1
+ assert not any(marker.exists() for marker in markers.values())