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
test(conftest): reap every process an opted-in test leaves running, however the test or run ends (#2439)
Call Whitec02458f3b26a
diff --git a/pyproject.toml b/pyproject.tomlindex bd6f4ce4d..029d8399f 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -171,6 +171,7 @@ markers = ["uses_real_paths: opt out of the autouse home/config isolation so the test can exercise real path resolvers (must remain read-only)","no_sqlite_template: opt out of the pre-migrated SQLite template for migration/bootstrap tests","allow_foreign_signals(reason): opt out of the autouse guard that refuses os.kill/os.killpg to processes the test did not start (state the reason)",+ "reap_processes: kill every process the test started that is still running when it ends, and after a killed run (tests/process_reaper.py)","real_web_push_sender: opt out of the autouse stub that keeps the delayed Web Push sender from outliving a test, for tests that drive the sender directly","real_catalog_refresh: opt out of the autouse stub that keeps the remote model catalog and models.dev refreshes from outliving a test, for tests that drive a refresh directly",]diff --git a/tests/agent_core/tools/test_bash.py b/tests/agent_core/tools/test_bash.pyindex b5f12cc7e..279de7403 100644--- a/tests/agent_core/tools/test_bash.py+++ b/tests/agent_core/tools/test_bash.py@@ -22,6 +22,9 @@ from core.agent_core.tools.jobs import LocalJobHostfrom tests import hang_guardfrom tests.agent_core.tools.conftest import instance, result_text+# Starts real job wrappers: none may outlive its test (tests/process_reaper.py).+pytestmark = pytest.mark.reap_processes+LABEL = "Output log (first 1.0MB, then the last 2.0MB in tail.log beside it)"diff --git a/tests/agent_core/tools/test_jobs.py b/tests/agent_core/tools/test_jobs.pyindex ca3d1efbd..50aa9578d 100644--- a/tests/agent_core/tools/test_jobs.py+++ b/tests/agent_core/tools/test_jobs.py@@ -23,6 +23,9 @@ import core.agent_core.tools.jobs as jobs_modulefrom core.agent_core.tools.jobs import JobStartError, LocalJobHostfrom tests.agent_core.tools.conftest import instance+# Starts real job wrappers: none may outlive its test (tests/process_reaper.py).+pytestmark = pytest.mark.reap_processes+class Crash(Exception):passdiff --git a/tests/conftest.py b/tests/conftest.pyindex 283641e7f..a6ea44fb6 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -72,6 +72,7 @@ import psutilimport pytestfrom sqlalchemy.exc import SAWarning+from tests import process_reaperfrom tests.fake_pid_helpers import PID_LIMITREAL_USER_HOME = Path.home()@@ -177,6 +178,49 @@ def pytest_configure(config):)+# Every process a `reap_processes` test starts ends with it (tests/process_reaper.py):+# the running test's record, the run's warden, and what the reaper had to kill.+_active_test_processes: process_reaper.TestProcesses | None = None+_process_warden: process_reaper.Warden | None = None+_reaped_processes: list[str] = []+_TEST_PROCESSES = pytest.StashKey[process_reaper.TestProcesses]()++[email protected](autouse=True)+def _record_test_processes(request):+ """For a ``reap_processes`` test, record every process it starts; ``pytest_runtest_teardown`` kills+ what is still running.++ Opt-in: only the suites that start real children carry the marker. A fixture,+ so the record begins after every module- and session-scoped fixture is set+ up: what those start belongs to them, not to this test. The warden starts+ with the first marked test, so a run without one never has it.+ """++ global _active_test_processes, _process_warden+ if _SIGNAL_GUARD_SUPPORTED and request.node.get_closest_marker("reap_processes") is not None:+ if _process_warden is None:+ _process_warden = process_reaper.Warden()+ _active_test_processes = request.node.stash[_TEST_PROCESSES] = process_reaper.TestProcesses(+ _process_warden+ )+ yield++[email protected](wrapper=True)+def pytest_runtest_teardown(item):+ """Reap after every finalizer of the test has run, so a process a fixture stops is gone first."""++ global _active_test_processes+ try:+ return (yield)+ finally:+ _active_test_processes = None+ processes = item.stash.get(_TEST_PROCESSES, None)+ if processes is not None:+ _reaped_processes.extend(f"{item.nodeid}: {each}" for each in processes.reap())++def _module_uses_default_sqlite_state(request: pytest.FixtureRequest) -> bool:"""Avoid creating a migration template for tests that never use SQLite state."""@@ -721,6 +765,9 @@ def _recording_popen_init(popen, *args, **kwargs):guard = _active_signal_guardif guard is not None:guard.owned.add(popen.pid)+ processes = _active_test_processes+ if processes is not None:+ processes.record(popen.pid)@wraps(_REAL_PSUTIL_PROCESS_INIT)@@ -995,6 +1042,10 @@ def pytest_sessionstart(session: pytest.Session) -> None:def pytest_terminal_summary(terminalreporter) -> None:+ if _reaped_processes:+ terminalreporter.section("processes still running when their test ended were killed", yellow=True)+ for line in _reaped_processes:+ terminalreporter.line(line, yellow=True)written = list(_real_home_writes)terminalreporter.config.stash[_REPORTED_WRITES] = len(written)if written:@@ -1009,6 +1060,8 @@ def pytest_unconfigure(config: pytest.Config) -> None:# daemon threads can outlive this hook, and restoring the real values here# would hand them the real home again. Only a write during interpreter# shutdown, after pytest has returned its status, is refused without failing.+ if _process_warden is not None:+ _process_warden.close()shutil.rmtree(_SESSION_HOME, ignore_errors=True)for message in _real_home_writes[config.stash.get(_REPORTED_WRITES, 0) :]:sys.stderr.write(f"refused a write under the real Avibe home: {message}\n")diff --git a/tests/process_reaper.py b/tests/process_reaper.pynew file mode 100644index 000000000..3b1b0030f--- /dev/null+++ b/tests/process_reaper.py@@ -0,0 +1,288 @@+"""Every process a ``reap_processes`` test starts ends with that test, however it ends.++A test that starts a real process and then fails, or waits on a gate until+``hang_guard`` gives up, never reaches its own cleanup. The process it started+kept running: a job wrapper the test had stopped with SIGSTOP, and mock Model+Hub engines, outlived their deleted worktrees by days. Two owners close that.++- ``TestProcesses.reap`` runs once every fixture of a marked test is torn down+ (``tests/conftest.py``). It kills each process the test started that is still+ running: every ``subprocess.Popen`` child the test recorded, with the process+ group the child founded, and every other new descendant of this pytest+ process, each with its own descendants.+- A pytest that is killed outright (SIGKILL, the CI watchdog's ``_exit``) runs+ no teardown. The warden, a process started with the first marked test, reads+ the running test's recorded children from a pipe. When pytest is gone,+ however it ended, the warden kills each one still running and the group it+ founded.++Opt-in, for the suites whose children are real and long-lived: the job wrapper+tests (``tests/agent_core/tools/test_bash.py``, ``test_jobs.py``,+``tests/test_watch_job_target.py``) and the mock-engine tests+(``tests/test_model_hub_runtime.py``, ``test_model_hub_local_error_details.py``).+Each starts its children through ``subprocess.Popen`` in a session of their own,+which is what the record covers. A marked test starts no ``multiprocessing``+helper, which serves a whole run and would be reaped with the test.++Invariant: once a marked test has ended, no process it started is still+running, and when a run is killed, none its running test started is. A process+is killed, not waited for, so a test that needs one to finish waits for it in+its body. Every signal is proven to reach what the test started:++- a process is matched by pid and creation time, so a reused pid is never+ signalled;+- a group is signalled only while its recorded leader still runs, or while+ that pid names no process at all, which leaves only the leader's orphans in+ it. A pid reused by any live process makes the record stale. The warden+ forgets each test's records once its reap has confirmed them gone.++Reports name a process by pid and executable name only: an argv can carry a+credential.++POSIX only, like the foreign-signal guard whose ``Popen`` hook records spawns.+"""++from __future__ import annotations++import os+import signal+import subprocess+import sys+import time+from typing import NamedTuple++import psutil+import pytest++from tests import hang_guard++# Captured before tests/conftest.py guards them: the reaper may signal what no test may.+_KILL = os.kill+_KILLPG = getattr(os, "killpg", None)+_GETPGID = getattr(os, "getpgid", None)+_GETPGRP = getattr(os, "getpgrp", None)+++class _Spawn(NamedTuple):+ created: float+ # The spawn leads a process group of its own (``start_new_session``).+ founded_group: bool+++def _created(pid: int) -> float | None:+ try:+ return psutil.Process(pid).create_time()+ except psutil.Error:+ return None+++def _same(pid: int, created: float) -> psutil.Process | None:+ try:+ process = psutil.Process(pid)+ if process.create_time() == created and process.status() != psutil.STATUS_ZOMBIE:+ return process+ except psutil.Error:+ pass+ return None+++def _group_is_ours(leader: int, created: float) -> bool:+ """Whether group ``leader`` still holds only what the recorded leader started."""+ try:+ return psutil.Process(leader).create_time() == created+ except psutil.NoSuchProcess:+ # No process holds the pid, so no other process can lead a group by it.+ return True+ except psutil.Error:+ return False+++def _descendants() -> dict[int, float]:+ found: dict[int, float] = {}+ for process in psutil.Process().children(recursive=True):+ try:+ found[process.pid] = process.create_time()+ except psutil.Error:+ pass+ return found+++def _group_members(groups: set[int]) -> list[psutil.Process]:+ members = []+ for process in psutil.process_iter():+ try:+ if _GETPGID(process.pid) in groups and process.status() != psutil.STATUS_ZOMBIE:+ members.append(process)+ except (OSError, psutil.Error):+ pass+ return members+++def _describe(pid: int) -> str:+ try:+ return f"{pid} ({psutil.Process(pid).name()})"+ except psutil.Error:+ return str(pid)+++class TestProcesses:+ """One test's spawns, and the descendants this pytest process had before it began."""++ __test__ = False++ def __init__(self, warden: "Warden | None") -> None:+ self._warden = warden+ self._before = _descendants()+ self._spawned: dict[int, _Spawn] = {}++ def record(self, pid: int) -> None:+ """Called for every ``subprocess.Popen`` child the test starts, once the child exists."""+ created = _created(pid)+ if created is None:+ return+ try:+ founded_group = _GETPGID(pid) == pid != _GETPGRP()+ except OSError:+ founded_group = False+ self._spawned[pid] = _Spawn(created, founded_group)+ if self._warden is not None:+ self._warden.record(pid, created, founded_group)++ def reap(self) -> list[str]:+ """Kill what the test left running and wait until it is gone; describe each process killed."""+ __tracebackhide__ = True+ targets: dict[int, float] = {}++ def add(process: psutil.Process) -> None:+ try:+ for each in (process, *process.children(recursive=True)):+ targets.setdefault(each.pid, each.create_time())+ except psutil.Error:+ pass++ for pid, created in _descendants().items():+ if self._before.get(pid) != created and (process := _same(pid, created)) is not None:+ add(process)+ for pid, spawn in self._spawned.items():+ if (process := _same(pid, spawn.created)) is not None:+ add(process)+ # A group outlives its leader: what a spawned shell put in the background stays in it.+ groups = {+ pid for pid, spawn in self._spawned.items() if spawn.founded_group and _group_is_ours(pid, spawn.created)+ }+ for member in _group_members(groups) if groups else ():+ add(member)+ targets.pop(os.getpid(), None)+ reaped = [_describe(pid) for pid, created in targets.items() if _same(pid, created) is not None]+ for pgid in groups:+ try:+ _KILLPG(pgid, signal.SIGKILL)+ except OSError:+ pass+ for pid, created in targets.items():+ if _same(pid, created) is not None:+ try:+ _KILL(pid, signal.SIGKILL)+ except OSError:+ pass+ give_up = time.monotonic() + hang_guard.HANG_GUARD_SECONDS+ while running := [pid for pid, created in targets.items() if _same(pid, created) is not None]:+ if time.monotonic() >= give_up:+ pytest.fail(+ f"hung for {hang_guard.HANG_GUARD_SECONDS:.0f}s waiting for SIGKILLed processes to end: "+ + ", ".join(map(_describe, running))+ )+ time.sleep(0.01)+ if self._warden is not None:+ self._warden.settle()+ return reaped+++# Runs as ``python -I -c _WARDEN <pytest pid>`` with the record pipe on stdin. A+# line is "<pid> <creation time> <1 if it founded its group>", or "settled" once+# the running test's reap has confirmed every record gone. EOF, or a parent+# that is no longer pytest, means the run is over.+_WARDEN = r"""+import os, select, signal, sys+import psutil++pytest_pid = int(sys.argv[1])+records = {}+pending = b""+while True:+ ready, _, _ = select.select([0], [], [], 1.0)+ if not ready:+ if os.getppid() != pytest_pid:+ break+ continue+ chunk = os.read(0, 65536)+ if not chunk:+ break+ *lines, pending = (pending + chunk).split(b"\n")+ for line in lines:+ if line == b"settled":+ records.clear()+ continue+ pid, created, founded_group = line.split()+ records[int(pid)] = (float(created), founded_group == b"1")+for pid, (created, founded_group) in records.items():+ try:+ process = psutil.Process(pid)+ same = process.create_time() == created+ except psutil.NoSuchProcess:+ process, same = None, False+ except psutil.Error:+ continue+ if same:+ try:+ tree = [*process.children(recursive=True), process]+ except psutil.Error:+ # It ended after the identity check; its group is still handled below.+ tree = []+ for each in tree:+ try:+ each.send_signal(signal.SIGKILL)+ except psutil.Error:+ pass+ # The group is the leader's while it runs, or while no process holds its pid.+ if founded_group and (same or process is None):+ try:+ os.killpg(pid, signal.SIGKILL)+ except OSError:+ pass+"""+++class Warden:+ """The run's last owner of its spawns: it acts once this pytest process is gone."""++ def __init__(self) -> None:+ read_end, self._write_end = os.pipe()+ try:+ # Its own session, so a signal to pytest's process group cannot end it first.+ self._process = subprocess.Popen(+ [sys.executable, "-I", "-c", _WARDEN, str(os.getpid())],+ stdin=read_end,+ start_new_session=True,+ )+ finally:+ os.close(read_end)++ def _send(self, line: str) -> None:+ try:+ os.write(self._write_end, f"{line}\n".encode())+ except BrokenPipeError:+ # The warden is gone; the per-test reaper still owns every spawn.+ pass++ def record(self, pid: int, created: float, founded_group: bool) -> None:+ self._send(f"{pid} {created!r} {int(founded_group)}")++ def settle(self) -> None:+ """Every record so far is confirmed gone: forget them, so none can go stale."""+ self._send("settled")++ def close(self) -> None:+ """End the run: the warden kills whatever recorded process is still running, then exits."""+ os.close(self._write_end)+ self._process.wait()diff --git a/tests/test_model_hub_local_error_details.py b/tests/test_model_hub_local_error_details.pyindex 94c382687..280ba5ac0 100644--- a/tests/test_model_hub_local_error_details.py+++ b/tests/test_model_hub_local_error_details.py@@ -27,6 +27,9 @@ from vibe.model_hub_runtime.installer import EngineRuntimeManagerfrom vibe.model_hub_runtime.state import EngineStateStorefrom vibe.model_hub_runtime.supervisor import EngineSupervisor, EngineUnavailableError+# Starts real mock engines: none may outlive its test (tests/process_reaper.py).+pytestmark = pytest.mark.reap_processes+@pytest.mark.parametrize("code", [errno.ENOSPC, errno.EACCES, errno.EROFS, errno.EMFILE])@pytest.mark.parametrize("stage", ["install_lock", "invoke_spawn", "record_read", "record_write"])diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex d526a3062..328333089 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -73,6 +73,9 @@ from vibe.model_hub_runtime.supervisor import (EngineUnavailableError,)+# Starts real mock engines: none may outlive its test (tests/process_reaper.py).+pytestmark = pytest.mark.reap_processes+MODEL_HUB_FIXTURES = Path(__file__).parent / "fixtures" / "model_hub"STREAM_TRANSPORT_BOUNDARIES = json.loads(diff --git a/tests/test_process_reaper.py b/tests/test_process_reaper.pynew file mode 100644index 000000000..283fed386--- /dev/null+++ b/tests/test_process_reaper.py@@ -0,0 +1,171 @@+"""No process a ``reap_processes`` test starts outlives it, however it ends (tests/process_reaper.py).++The run-level cases run a pytest of their own with this suite's conftest, so the+reaper and the warden act exactly as they do for every marked test file.+"""++from __future__ import annotations++import os+import subprocess+import sys+from pathlib import Path++import psutil+import pytest++from tests import hang_guard, process_reaper++pytestmark = pytest.mark.skipif(os.name == "nt", reason="the reaper records spawns on POSIX only")++REPO_ROOT = Path(__file__).resolve().parents[1]+SUMMARY = "processes still running when their test ended were killed"++# What leaked before: a child stopped with SIGSTOP in a session of its own (the+# job wrapper the deadline test stops), and a grandchild a spawned shell put in+# the background, orphaned once the shell exits and found only through its group.+INNER = '''+import os+import signal+import subprocess+import sys+from pathlib import Path++import psutil+import pytest++RECORD = Path(os.environ["REAPER_PROBE_RECORD"])+pytestmark = pytest.mark.reap_processes+++def _spawn_tree():+ stopped = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(600)"], start_new_session=True)+ os.kill(stopped.pid, signal.SIGSTOP)+ shell = subprocess.Popen(+ ["sh", "-c", "sleep 600 & echo $!"], start_new_session=True, stdout=subprocess.PIPE, text=True+ )+ orphan = int(shell.stdout.readline())+ shell.wait()+ RECORD.write_text(+ "".join(f"{pid} {psutil.Process(pid).create_time()!r}\\n" for pid in (stopped.pid, orphan))+ )+++def test_a_failing_body():+ _spawn_tree()+ raise AssertionError("fails on purpose")+++def test_then_nothing_it_started_is_running():+ for line in RECORD.read_text().splitlines():+ pid, created = line.split()+ try:+ process = psutil.Process(int(pid))+ assert process.create_time() != float(created) or process.status() == psutil.STATUS_ZOMBIE+ except psutil.NoSuchProcess:+ pass++[email protected]_foreign_signals(reason="the run kills itself, as the CI watchdog does")+def test_a_killed_run():+ _spawn_tree()+ os.kill(os.getpid(), signal.SIGKILL)+'''+++# A run without a marked test is untouched: no warden, nothing recorded.+UNMARKED = '''+import psutil+++def test_an_unmarked_run_starts_no_warden():+ assert psutil.Process().children() == []+'''+++def _run_inner(tmp_path: Path, selection: str, source: str = INNER) -> tuple[subprocess.CompletedProcess, Path]:+ inner = tmp_path / "test_inner.py"+ inner.write_text(source)+ record = tmp_path / "spawned"+ result = subprocess.run(+ [sys.executable, "-m", "pytest", "-p", "tests.conftest", "-p", "no:cacheprovider", "-q", str(inner), "-k", selection],+ cwd=REPO_ROOT,+ env={**os.environ, "REAPER_PROBE_RECORD": str(record)},+ capture_output=True,+ text=True,+ timeout=hang_guard.HANG_GUARD_SECONDS,+ )+ return result, record+++def _running(record: Path) -> list[int]:+ running = []+ for line in record.read_text().splitlines():+ pid, created = line.split()+ if process_reaper._same(int(pid), float(created)) is not None:+ running.append(int(pid))+ return running+++def test_a_failed_test_leaves_nothing_it_started_running(tmp_path):+ result, record = _run_inner(tmp_path, "failing_body or nothing_it_started")++ output = result.stdout + result.stderr+ assert result.returncode == 1, output+ assert "1 failed, 1 passed" in output, output+ reported = output.split(SUMMARY)[1]+ assert "test_a_failing_body" in reported+ # A report names the process, never its arguments, which can carry a credential.+ assert "time.sleep" not in reported and "sleep 600" not in reported+ assert _running(record) == []+++async def test_a_killed_run_leaves_nothing_it_started_running(tmp_path):+ result, record = _run_inner(tmp_path, "killed_run")++ assert result.returncode == -9, result.stdout + result.stderr+ # The warden acts once it sees the run gone, after this pytest saw it exit.+ await hang_guard.until(lambda: _running(record) == [], "the warden to kill what the killed run started")+++def test_a_run_without_a_marked_test_has_no_warden(tmp_path):+ result, _ = _run_inner(tmp_path, "unmarked", UNMARKED)++ assert result.returncode == 0, result.stdout + result.stderr+++def group_leader():+ """A live process leading its own group, as a stranger that reused a recorded pid would."""+ process = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(600)"], start_new_session=True)+ try:+ yield process.pid, psutil.Process(process.pid).create_time()+ finally:+ process.kill()+ process.wait()+++def test_a_reap_never_signals_a_group_whose_pid_now_names_another_process(group_leader):+ pid, created = group_leader+ processes = process_reaper.TestProcesses(None)+ processes._spawned[pid] = process_reaper._Spawn(created - 1.0, founded_group=True)++ assert processes.reap() == []++ assert process_reaper._same(pid, created) is not None++[email protected]("settled", [False, True], ids=["stale", "settled"])+def test_the_warden_never_signals_a_record_it_cannot_prove_is_still_the_runs(group_leader, settled):+ pid, created = group_leader+ warden = process_reaper.Warden()+ if settled:+ # Forgotten once a reap confirmed the test's records gone, even an exact match.+ warden.record(pid, created, founded_group=True)+ warden.settle()+ else:+ warden.record(pid, created - 1.0, founded_group=True)++ warden.close()++ assert process_reaper._same(pid, created) is not Nonediff --git a/tests/test_watch_job_target.py b/tests/test_watch_job_target.pyindex 4cef0e463..0f26090f3 100644--- a/tests/test_watch_job_target.py+++ b/tests/test_watch_job_target.py@@ -46,6 +46,9 @@ from vibe.ui_server import app as ui_appfrom tests.ui_server_test_helpers import csrf_headers+# Starts real job wrappers: none may outlive its test (tests/process_reaper.py).+pytestmark = pytest.mark.reap_processes+SESSION_ID = "ses_job_watch"