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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(show-runtime): reap orphaned runtime servers in the UI server process (avibe#813) (#815)
Call White92785add5f41
diff --git a/core/show_runtime.py b/core/show_runtime.pyindex 788d6d8af..5cda60815 100644--- a/core/show_runtime.py+++ b/core/show_runtime.py@@ -150,6 +150,12 @@ class ShowRuntimeManager:self.runtime_dir.mkdir(parents=True, exist_ok=True)self.workspace_root.mkdir(parents=True, exist_ok=True)self.cache_root.mkdir(parents=True, exist_ok=True)+ # Reap any orphaned runtime server still bound to this workspace root before+ # spawning ours, so there is a single writer (avibe#813). self.stop() above+ # already released our own tracked child; anything left is a stray from a+ # prior avibe instance that died without reaping it (SIGKILL / crash). Run it+ # off the event loop: the psutil scan + terminate/kill can block for seconds.+ await asyncio.to_thread(self._sweep_orphan_runtime_servers)with self.stdout_path.open("w", encoding="utf-8") as stdout, self.stderr_path.open("w", encoding="utf-8") as stderr:@@ -300,6 +306,14 @@ class ShowRuntimeManager:except subprocess.TimeoutExpired:signal_process_tree(process, KILL_SIGNAL, logger, "show runtime")+ def _sweep_orphan_runtime_servers(self) -> None:+ """Best-effort reap of stray runtime servers bound to our workspace root."""+ keep_pid = self._process.pid if self._process else None+ try:+ sweep_orphan_show_runtime_servers(self.workspace_root, keep_pid=keep_pid)+ except Exception: # pragma: no cover - defensive; sweeping must never block spawn+ logger.debug("Orphan show runtime sweep skipped", exc_info=True)+async def _resolve_managed_command(self) -> list[str] | None:if self._command_explicit and self.command != _RUNTIME_BIN:self._install_reason = "runtime_command_missing"@@ -1009,6 +1023,89 @@ def stop_show_runtime_manager() -> None:_manager.stop()+def _is_runtime_server_cmdline(cmdline: list[str], workspace_root: str) -> bool:+ """True if ``cmdline`` is a Show Runtime server bound to ``workspace_root``.++ Requires the exact ``--workspace-root <workspace_root>`` arg pair AND a runtime+ signature (the always-present ``--fallback-delay-seconds`` flag, the ``cli.js``+ entrypoint, the managed bin, or a ``show-runtime`` path token), so an unrelated+ process that merely mentions the path is never matched.+ """+ if not cmdline:+ return False+ bound = any(+ token == "--workspace-root" and index + 1 < len(cmdline) and cmdline[index + 1] == workspace_root+ for index, token in enumerate(cmdline)+ )+ if not bound:+ return False+ return any(+ token == "--fallback-delay-seconds"+ or token.endswith("cli.js")+ or token.endswith(_RUNTIME_BIN)+ or "show-runtime" in token+ for token in cmdline+ )+++def sweep_orphan_show_runtime_servers(+ workspace_root: Path | str | None = None,+ *,+ keep_pid: int | None = None,+) -> list[int]:+ """Terminate any Show Runtime server still bound to ``workspace_root``.++ A prior avibe instance that died without reaping its child (SIGKILL / crash —+ ``atexit`` does not run) leaves a Node ``cli.js`` orphan reparented to init, still+ listening on its old port and able to warm/mutate this workspace root with stale+ in-memory templates (avibe-bot/avibe#813). The single-service-instance lock makes+ this process the only legitimate owner of the root, so any *other* process bound to+ it is an orphan and safe to reap.++ Best-effort and spawn-agnostic: complements the runtime's own parent-death self-exit+ (vibe-show-runtime#30) by also clearing orphans from builds that predate that+ backstop. Returns the pids swept (for logging/tests).+ """+ root = str(workspace_root) if workspace_root is not None else str(paths.get_show_pages_dir())+ try:+ import psutil+ except Exception: # pragma: no cover - psutil is a hard dependency in practice+ return []++ own_pid = os.getpid()+ swept: list[int] = []+ for proc in psutil.process_iter(["pid", "cmdline"]):+ try:+ pid = proc.info.get("pid")+ if pid is None or pid == own_pid or (keep_pid is not None and pid == keep_pid):+ continue+ if not _is_runtime_server_cmdline(proc.info.get("cmdline") or [], root):+ continue+ victims = proc.children(recursive=True)+ except (psutil.NoSuchProcess, psutil.AccessDenied):+ continue+ except Exception: # pragma: no cover - never let a stray psutil error block callers+ logger.debug("Failed to inspect process while sweeping show runtime orphans", exc_info=True)+ continue+ victims.append(proc)+ logger.warning(+ "Sweeping orphaned show runtime server pid=%s bound to workspace_root=%s", pid, root+ )+ for victim in victims:+ try:+ victim.terminate()+ except (psutil.NoSuchProcess, psutil.AccessDenied):+ continue+ _gone, alive = psutil.wait_procs(victims, timeout=3)+ for victim in alive:+ try:+ victim.kill()+ except (psutil.NoSuchProcess, psutil.AccessDenied):+ continue+ swept.append(pid)+ return swept++async def prewarm_show_runtime() -> ShowRuntimeResult:return await get_show_runtime_manager().ensure()diff --git a/tests/test_show_runtime_orphan_sweep.py b/tests/test_show_runtime_orphan_sweep.pynew file mode 100644index 000000000..ac9807134--- /dev/null+++ b/tests/test_show_runtime_orphan_sweep.py@@ -0,0 +1,190 @@+"""Regression tests for Show Runtime orphan reaping (avibe#813).++Covers the two avibe-side layers that stop a Node ``cli.js`` runtime server from+outliving the service that spawned it:++* the pure matcher that recognises a runtime server bound to a workspace root,+* the sweep that terminates such orphans (exercised against real processes), and+* the wiring that reaps the runtime on the controller's synchronous shutdown path.+"""++from __future__ import annotations++import asyncio+import subprocess+import sys+import time+from unittest.mock import patch++import psutil++from core import show_runtime+from core.show_runtime import _is_runtime_server_cmdline, sweep_orphan_show_runtime_servers+++def _runtime_cmdline(workspace_root: str) -> list[str]:+ """Mirror the argv shape spawned by ShowRuntimeManager.ensure()."""+ return [+ "node",+ "/opt/show-runtime/dist/cli.js",+ "--workspace-root",+ workspace_root,+ "--cache-root",+ "/tmp/cache",+ "--host",+ "127.0.0.1",+ "--port",+ "0",+ "--fallback-delay-seconds",+ "8",+ ]+++# --------------------------------------------------------------------------- matcher+++def test_matcher_matches_runtime_bound_to_root():+ root = "/tmp/avibe-show/ws"+ assert _is_runtime_server_cmdline(_runtime_cmdline(root), root) is True+++def test_matcher_rejects_different_workspace_root():+ assert _is_runtime_server_cmdline(_runtime_cmdline("/tmp/a"), "/tmp/b") is False+++def test_matcher_rejects_unrelated_process_mentioning_path():+ root = "/tmp/avibe-show/ws"+ # A tool that merely references the path but is not the runtime server.+ assert _is_runtime_server_cmdline(["grep", "-r", "needle", root], root) is False+++def test_matcher_requires_signature_not_just_the_flag():+ root = "/tmp/avibe-show/ws"+ # Exact --workspace-root pair but no runtime signature -> not a match.+ assert _is_runtime_server_cmdline(["some-tool", "--workspace-root", root], root) is False+++def test_matcher_matches_managed_bin_without_cli_js():+ root = "/tmp/avibe-show/ws"+ cmd = [f"/home/avibe/.local/bin/{show_runtime._RUNTIME_BIN}", "--workspace-root", root, "--fallback-delay-seconds", "8"]+ assert _is_runtime_server_cmdline(cmd, root) is True+++def test_matcher_handles_empty_cmdline():+ assert _is_runtime_server_cmdline([], "/tmp/x") is False+++# ----------------------------------------------------------------------------- sweep+++def _spawn_fake_orphan(workspace_root: str) -> subprocess.Popen:+ """Spawn a real, long-lived process whose argv matches a runtime server.++ psutil reads argv, so a plain Python sleeper with a runtime-shaped command+ line is indistinguishable from a real orphan for the purposes of the sweep.+ ``start_new_session`` mirrors the real spawn (its own session/pgroup).+ """+ argv = [+ sys.executable,+ "-c",+ "import time; time.sleep(120)",+ "cli.js",+ "--workspace-root",+ workspace_root,+ "--fallback-delay-seconds",+ "8",+ ]+ return subprocess.Popen(argv, start_new_session=True)+++def _gone(pid: int, timeout: float = 5.0) -> bool:+ """True once ``pid`` no longer exists (a reaped zombie counts as gone)."""+ deadline = time.time() + timeout+ while time.time() < deadline:+ if not psutil.pid_exists(pid):+ return True+ try:+ if psutil.Process(pid).status() == psutil.STATUS_ZOMBIE:+ return True+ except psutil.NoSuchProcess:+ return True+ time.sleep(0.05)+ return False+++def _reap(proc: subprocess.Popen) -> None:+ try:+ if proc.poll() is None:+ proc.kill()+ proc.wait(timeout=5)+ except Exception:+ pass+++def test_sweep_kills_orphan_bound_to_root(tmp_path):+ root = str(tmp_path / "show")+ proc = _spawn_fake_orphan(root)+ try:+ swept = sweep_orphan_show_runtime_servers(root)+ assert proc.pid in swept+ assert _gone(proc.pid), "orphan bound to the workspace root should be terminated"+ finally:+ _reap(proc)+++def test_sweep_spares_process_on_a_different_root(tmp_path):+ ours = str(tmp_path / "ours")+ other = str(tmp_path / "other")+ proc = _spawn_fake_orphan(other)+ try:+ swept = sweep_orphan_show_runtime_servers(ours)+ assert proc.pid not in swept+ assert proc.poll() is None, "a server on a different workspace root must be spared"+ finally:+ _reap(proc)+++def test_sweep_respects_keep_pid(tmp_path):+ root = str(tmp_path / "show")+ proc = _spawn_fake_orphan(root)+ try:+ swept = sweep_orphan_show_runtime_servers(root, keep_pid=proc.pid)+ assert proc.pid not in swept+ assert proc.poll() is None, "keep_pid (our own live child) must be spared"+ finally:+ _reap(proc)+++# ------------------------------------------------ UI server process lifecycle wiring+#+# The Node runtime is a child of the UI server process (run_ui_server), so the+# startup sweep and shutdown reap must live there — not in the controller process,+# which never spawns a runtime.+++def test_ui_server_registers_startup_sweep_and_shutdown_reap():+ from vibe import ui_server++ assert ui_server.sweep_orphan_show_runtime_servers_on_startup in ui_server.app.router.on_startup+ assert ui_server.stop_show_runtime_on_shutdown in ui_server.app.router.on_shutdown+++def test_startup_handler_sweeps_orphans():+ from vibe import ui_server++ with patch("core.show_runtime.sweep_orphan_show_runtime_servers") as sweep:+ asyncio.run(ui_server.sweep_orphan_show_runtime_servers_on_startup())++ sweep.assert_called_once()+++def test_shutdown_handler_stops_tracked_child_and_sweeps_strays():+ from vibe import ui_server++ with patch("core.show_runtime.stop_show_runtime_manager") as stop, patch(+ "core.show_runtime.sweep_orphan_show_runtime_servers"+ ) as sweep:+ ui_server.stop_show_runtime_on_shutdown()++ stop.assert_called_once()+ sweep.assert_called_once()diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 0f6bc6193..a6a2fa0ba 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -8455,10 +8455,35 @@ def _with_show_event_write_cookie(response: Response, session_id: str, *, enablereturn response+async def sweep_orphan_show_runtime_servers_on_startup() -> None:+ """Reap a Show Runtime server left bound to the workspace root by a prior UI+ server process that died without running its shutdown hook (SIGKILL / crash).++ The Node ``cli.js`` runtime is a child of THIS UI server process. On a hard+ death it is reparented to init and keeps serving stale code on its old port+ (avibe#813). ``vibe`` only spawns a new UI server when no healthy one exists,+ so at startup any runtime still on the root is an orphan and safe to sweep.++ Offloaded to a thread so the psutil scan + terminate/kill never blocks the+ event loop (and thus /health readiness) during startup."""+ from core.show_runtime import sweep_orphan_show_runtime_servers++ try:+ await asyncio.to_thread(sweep_orphan_show_runtime_servers)+ except Exception:+ logger.debug("startup show runtime orphan sweep skipped", exc_info=True)++def stop_show_runtime_on_shutdown() -> None:- from core.show_runtime import stop_show_runtime_manager+ from core.show_runtime import stop_show_runtime_manager, sweep_orphan_show_runtime_servers+ # Stop the tracked child (its process group, incl. esbuild workers), then sweep+ # the workspace root so any untracked stray from an earlier respawn is reaped too.stop_show_runtime_manager()+ try:+ sweep_orphan_show_runtime_servers()+ except Exception:+ logger.debug("shutdown show runtime orphan sweep skipped", exc_info=True)@app.route("/show/<session_id>")@@ -8830,6 +8855,7 @@ async def _stop_startup_dependency_reconcile() -> None:logger.debug("startup dependency reconcile shutdown raised", exc_info=True)+app.add_event_handler("startup", sweep_orphan_show_runtime_servers_on_startup)app.add_event_handler("startup", _start_startup_dependency_reconcile)app.add_event_handler("shutdown", _stop_startup_dependency_reconcile)app.add_event_handler("shutdown", stop_show_runtime_on_shutdown)