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): isolate managed child process groups

cyhae68bc0c2856
diff --git a/core/process_isolation.py b/core/process_isolation.py
new file mode 100644
index 000000000..5e67404ee
--- /dev/null
+++ b/core/process_isolation.py
@@ -0,0 +1,107 @@
+"""Helpers for isolating and terminating managed child processes."""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import os
+import signal
+import subprocess
+from typing import Any
+
+KILL_SIGNAL = getattr(signal, "SIGKILL", signal.SIGTERM)
+
+
+def isolated_subprocess_kwargs() -> dict[str, Any]:
+ """Return subprocess kwargs that put a child outside this process group."""
+ if os.name == "nt":
+ return {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP}
+ return {"start_new_session": True}
+
+
+def _safe_signal_process_group(pid: int, sig: int, logger: logging.Logger, label: str) -> bool:
+ if os.name == "nt" or not hasattr(os, "getpgid") or not hasattr(os, "killpg"):
+ return False
+ try:
+ pgid = os.getpgid(pid)
+ own_pgid = os.getpgrp()
+ except ProcessLookupError:
+ return True
+ except Exception:
+ logger.debug("Failed to inspect process group for %s pid=%s", label, pid, exc_info=True)
+ return False
+ if pgid == own_pgid:
+ logger.error(
+ "Refusing to signal %s process group for pid=%s because it matches the Vibe Remote service pgid=%s",
+ label,
+ pid,
+ own_pgid,
+ )
+ return False
+ try:
+ os.killpg(pgid, sig)
+ return True
+ except ProcessLookupError:
+ return True
+ except Exception:
+ logger.debug("Failed to signal %s process group pgid=%s", label, pgid, exc_info=True)
+ return False
+
+
+def signal_process_tree(process: Any, sig: int, logger: logging.Logger, label: str) -> None:
+ """Signal a managed process group, falling back to the direct process."""
+ pid = getattr(process, "pid", None)
+ if isinstance(pid, int) and _safe_signal_process_group(pid, sig, logger, label):
+ return
+
+ try:
+ if sig == signal.SIGTERM:
+ process.terminate()
+ elif sig == KILL_SIGNAL:
+ process.kill()
+ else:
+ process.send_signal(sig)
+ except ProcessLookupError:
+ return
+
+
+async def terminate_process_tree(
+ process: Any,
+ logger: logging.Logger,
+ label: str,
+ *,
+ terminate_timeout: float = 3.0,
+) -> None:
+ """Terminate a managed subprocess without signaling the service group."""
+ if getattr(process, "returncode", None) is not None:
+ return
+
+ signal_process_tree(process, signal.SIGTERM, logger, label)
+ try:
+ await asyncio.wait_for(process.wait(), timeout=terminate_timeout)
+ return
+ except asyncio.TimeoutError:
+ pass
+
+ signal_process_tree(process, KILL_SIGNAL, logger, label)
+ try:
+ await process.wait()
+ except ProcessLookupError:
+ return
+
+
+async def terminate_and_communicate(
+ process: Any,
+ logger: logging.Logger,
+ label: str,
+ *,
+ terminate_timeout: float = 3.0,
+) -> tuple[bytes, bytes]:
+ """Terminate a process tree and drain stdout/stderr."""
+ if getattr(process, "returncode", None) is None:
+ signal_process_tree(process, signal.SIGTERM, logger, label)
+ try:
+ return await asyncio.wait_for(process.communicate(), timeout=terminate_timeout)
+ except asyncio.TimeoutError:
+ signal_process_tree(process, KILL_SIGNAL, logger, label)
+ return await process.communicate()
diff --git a/core/watches.py b/core/watches.py
index b901b6c02..ed601ae49 100644
--- a/core/watches.py
+++ b/core/watches.py
@@ -13,6 +13,7 @@ from typing import Any, Optional
from uuid import uuid4
from config import paths
+from core.process_isolation import isolated_subprocess_kwargs, terminate_and_communicate
from core.scheduled_tasks import TaskExecutionStore
logger = logging.getLogger(__name__)
@@ -467,6 +468,7 @@ class ManagedWatchService:
cwd=watch.cwd or None,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
+ **isolated_subprocess_kwargs(),
)
else:
process = await asyncio.create_subprocess_exec(
@@ -474,6 +476,7 @@ class ManagedWatchService:
cwd=watch.cwd or None,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
+ **isolated_subprocess_kwargs(),
)
self._active_pids[watch.id] = process.pid
self._write_runtime_state()
@@ -484,12 +487,10 @@ class ManagedWatchService:
stdout, stderr = await process.communicate()
timed_out = False
except asyncio.CancelledError:
- process.kill()
- await process.communicate()
+ await terminate_and_communicate(process, logger, f"watch {watch.id}")
raise
except asyncio.TimeoutError:
- process.kill()
- stdout, stderr = await process.communicate()
+ stdout, stderr = await terminate_and_communicate(process, logger, f"watch {watch.id}")
return _CycleResult(exit_code=124, stdout="", stderr=stderr.decode("utf-8", errors="replace"), timed_out=True)
finally:
self._active_pids.pop(watch.id, None)
diff --git a/modules/agents/codex/transport.py b/modules/agents/codex/transport.py
index fb0d8d955..48adf1eac 100644
--- a/modules/agents/codex/transport.py
+++ b/modules/agents/codex/transport.py
@@ -10,6 +10,8 @@ import signal
from asyncio.subprocess import Process
from typing import Any, Awaitable, Callable, Optional
+from core.process_isolation import KILL_SIGNAL, isolated_subprocess_kwargs, signal_process_tree
+
logger = logging.getLogger(__name__)
STREAM_BUFFER_LIMIT = 128 * 1024 * 1024 # 128 MB
@@ -70,7 +72,7 @@ class CodexTransport:
stderr=asyncio.subprocess.PIPE,
cwd=self._cwd,
limit=STREAM_BUFFER_LIMIT,
- **({"preexec_fn": os.setsid} if hasattr(os, "setsid") else {}),
+ **isolated_subprocess_kwargs(),
)
logger.info("Codex app-server started (pid=%s)", self._process.pid)
@@ -116,18 +118,12 @@ class CodexTransport:
except asyncio.TimeoutError:
logger.warning("Codex app-server did not exit gracefully, sending SIGTERM")
try:
- if hasattr(os, "getpgid"):
- os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
- else:
- proc.terminate()
+ signal_process_tree(proc, signal.SIGTERM, logger, "Codex app-server")
await asyncio.wait_for(proc.wait(), timeout=3.0)
except (asyncio.TimeoutError, ProcessLookupError):
logger.warning("Codex app-server did not respond to SIGTERM, sending SIGKILL")
try:
- if hasattr(os, "getpgid"):
- os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
- else:
- proc.kill()
+ signal_process_tree(proc, KILL_SIGNAL, logger, "Codex app-server")
await proc.wait()
except ProcessLookupError:
pass
diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.py
index 55e29cb27..0810f5eb4 100644
--- a/modules/agents/opencode/server.py
+++ b/modules/agents/opencode/server.py
@@ -7,7 +7,6 @@ from contextlib import asynccontextmanager
import json
import logging
import os
-import signal
import socket
import subprocess
import time
@@ -18,6 +17,7 @@ from typing import Any, Dict, List, Optional
import aiohttp
from config import paths
+from core.process_isolation import isolated_subprocess_kwargs, terminate_process_tree
from vibe import runtime
from vibe.opencode_config import load_first_opencode_user_config
@@ -450,11 +450,7 @@ class OpenCodeServerManager:
async def _start_server(self) -> None:
if self._process and self._process.returncode is None:
- try:
- self._process.terminate()
- await asyncio.wait_for(self._process.wait(), timeout=5)
- except Exception:
- self._process.kill()
+ await terminate_process_tree(self._process, logger, "OpenCode server", terminate_timeout=5)
# Ensure any stale pid file is cleared before starting.
self._clear_pid_file()
@@ -477,6 +473,7 @@ class OpenCodeServerManager:
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL,
env=env,
+ **isolated_subprocess_kwargs(),
)
if self._process and self._process.pid:
self._write_pid_file(self._process.pid)
diff --git a/tests/test_process_isolation.py b/tests/test_process_isolation.py
new file mode 100644
index 000000000..2c472357b
--- /dev/null
+++ b/tests/test_process_isolation.py
@@ -0,0 +1,56 @@
+from __future__ import annotations
+
+import asyncio
+import logging
+import os
+import signal
+from types import SimpleNamespace
+
+import pytest
+
+from core.process_isolation import KILL_SIGNAL, isolated_subprocess_kwargs, signal_process_tree
+
+
+def test_isolated_subprocess_kwargs_start_new_session_on_posix() -> None:
+ if os.name == "nt":
+ assert "creationflags" in isolated_subprocess_kwargs()
+ else:
+ assert isolated_subprocess_kwargs() == {"start_new_session": True}
+
+
+def test_signal_process_tree_refuses_own_process_group_on_posix(monkeypatch: pytest.MonkeyPatch) -> None:
+ if os.name == "nt":
+ pytest.skip("process group guard is POSIX-specific")
+
+ sent: list[tuple[int, int]] = []
+ process = SimpleNamespace(
+ pid=12345,
+ terminate=lambda: sent.append(("terminate", 0)), # type: ignore[list-item]
+ kill=lambda: sent.append(("kill", 0)), # type: ignore[list-item]
+ )
+ monkeypatch.setattr(os, "getpgid", lambda pid: os.getpgrp())
+ monkeypatch.setattr(os, "killpg", lambda pgid, sig: sent.append((pgid, sig)))
+
+ signal_process_tree(process, signal.SIGTERM, logging.getLogger(__name__), "test process")
+
+ assert sent == [("terminate", 0)]
+
+
+def test_asyncio_subprocess_is_spawned_outside_parent_process_group_on_posix() -> None:
+ if os.name == "nt":
+ pytest.skip("POSIX process-group assertion")
+
+ async def _run() -> None:
+ process = await asyncio.create_subprocess_exec(
+ "python3",
+ "-c",
+ "import time; time.sleep(30)",
+ **isolated_subprocess_kwargs(),
+ )
+ try:
+ assert os.getpgid(process.pid) != os.getpgrp()
+ finally:
+ signal_process_tree(process, KILL_SIGNAL, logging.getLogger(__name__), "test process")
+ await process.wait()
+
+ asyncio.run(_run())
diff --git a/tests/test_watches.py b/tests/test_watches.py
index c27de137a..283b2bcde 100644
--- a/tests/test_watches.py
+++ b/tests/test_watches.py
@@ -231,7 +231,7 @@ def test_managed_watch_service_stop_terminates_running_waiter(tmp_path: Path) ->
runtime_store=runtime_store,
)
- async def _run() -> int:
+ async def _run() -> tuple[int, int | None]:
service.start()
for _ in range(100):
pid = service._active_pids.get(watch.id)
@@ -240,10 +240,14 @@ def test_managed_watch_service_stop_terminates_running_waiter(tmp_path: Path) ->
await asyncio.sleep(0.02)
else:
raise AssertionError("waiter pid was never recorded")
+ pgid = os.getpgid(pid) if hasattr(os, "getpgid") else None
await service.stop()
- return pid
+ return pid, pgid
- pid = asyncio.run(_run())
+ pid, pgid = asyncio.run(_run())
+
+ if pgid is not None:
+ assert pgid != os.getpgrp()
with pytest.raises(ProcessLookupError):
os.kill(pid, 0)