The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(e2e): dashboard teardown waits for sandbox processes instead of killing foreign PIDs
teknium119d56f216646
diff --git a/tests/e2e/core/dashboard/_helpers.py b/tests/e2e/core/dashboard/_helpers.pyindex 7d4be162050..2c8e62af717 100644--- a/tests/e2e/core/dashboard/_helpers.py+++ b/tests/e2e/core/dashboard/_helpers.py@@ -31,6 +31,8 @@ import yamlfrom tests.fakes.fake_llm_provider import FakeLLMServer+from . import _reaper+REPO_ROOT = Path(__file__).resolve().parents[4]TOKEN_HEADER = "X-Hermes-Session-Token"PROVIDER_KEY_ENV = "DASH_PROVIDER_KEY" # same NAME in every profile's .env, distinct VALUE@@ -129,6 +131,7 @@ class Profile:class Sandbox:root: Pathprofiles: dict[str, Profile]+ _released: bool = False@propertydef home(self) -> Path:@@ -141,31 +144,28 @@ class Sandbox:def env(self, extra: dict[str, str] | None = None) -> dict[str, str]:return hermetic_env(self.home, extra)- def stop(self) -> None:- for p in self.profiles.values():- if p.srv is not None:- p.srv.stop()- reap_sandbox(self.home)-+ def finish(self, *also: _reaper.Finder) -> None:+ """Stop the providers, then wait for every sandbox process (HOME in this sandbox, plus+ whatever ``also`` reports) to exit on its own; see ``_reaper``. Survivors past the+ deadline are killed and fail the test as a leak, AFTER all cleanup has run. Call from a+ fixture finalizer: a teardown error is reported on its own and never merges into a strict+ xfail's call outcome."""+ try:+ for p in self.profiles.values():+ if p.srv is not None:+ p.srv.stop()+ leaks = _reaper.reap(_reaper.with_home(self.home), *also)+ finally:+ if not self._released:+ self._released = True+ _reaper.release_orphans()+ if leaks:+ raise SandboxLeak(f"{len(leaks)} sandbox process(es) outlived the test by "+ f"{_reaper.REAP_TIMEOUT:.0f}s and were killed:\n " + "\n ".join(leaks))-def reap_sandbox(home: Path) -> list[int]:- """SIGKILL every process whose environment points HOME into this sandbox.- Detached children (``hermes gateway restart`` spawned by a dashboard action, keep-alive PTY- helpers) start their own session and escape the dashboard's process group; without this a- regression that lets such a route fire would leak processes past the test."""- needle = f"HOME={home}".encode()- killed = []- for entry in Path("/proc").iterdir():- if not entry.name.isdigit() or int(entry.name) == os.getpid():- continue- try:- if needle in (entry / "environ").read_bytes().split(b"\0"):- os.kill(int(entry.name), signal.SIGKILL)- killed.append(int(entry.name))- except (OSError, ProcessLookupError):- continue- return killed+class SandboxLeak(AssertionError):+ """A process spawned inside the sandbox was still running after teardown's deadline."""def write_profile_home(p: Profile, extra_config: dict[str, Any] | None = None) -> None:@@ -190,6 +190,7 @@ def make_sandbox(root: Path, names: tuple[str, ...] = ("default",),that accepts only its own key, so every recorded request proves WHO sent it."""hermes_home = root / "home" / ".hermes"profiles: dict[str, Profile] = {}+ _reaper.adopt_orphans() # before any spawn: every detached descendant stays reapablefor name in names:home = hermes_home if name == "default" else hermes_home / "profiles" / namep = Profile(name=name, home=home)@@ -303,30 +304,10 @@ class Dashboard:self._log.close()-def pid_alive(pid: int) -> bool:- try:- os.kill(pid, 0)- except ProcessLookupError:- return False- except PermissionError:- return True- stat = Path(f"/proc/{pid}/stat")- return not (stat.exists() and stat.read_text().split(") ", 1)[-1].startswith("Z"))---def group_pids(pgid: int) -> list[int]:- """Live, non-zombie pids of a process group (the dashboard runs as its own group leader)."""- out: list[int] = []- for d in Path("/proc").iterdir():- if not d.name.isdigit():- continue- try:- fields = (d / "stat").read_text().rsplit(")", 1)[1].split()- except OSError:- continue- if fields[0] != "Z" and int(fields[2]) == pgid:- out.append(int(d.name))- return out+def group_members(pgid: int) -> dict[_reaper.Identity, str]:+ """Live members of a process group (the dashboard runs as its own group leader), by identity."""+ return {(pid, int(fields[19])): _reaper.cmdline(pid)+ for pid, fields in _reaper.all_stats().items() if int(fields[2]) == pgid}# State readers -------------------------------------------------------------------------------------diff --git a/tests/e2e/core/dashboard/_issue_helpers.py b/tests/e2e/core/dashboard/_issue_helpers.pyindex 9c39bcc4e01..f3f8d233700 100644--- a/tests/e2e/core/dashboard/_issue_helpers.py+++ b/tests/e2e/core/dashboard/_issue_helpers.py@@ -31,8 +31,9 @@ from typing import Anyimport httpxfrom tests.e2e.core.dashboard._helpers import (- _READY_RE, _TOKEN_RE, Dashboard, Sandbox, group_pids, kill_group, poll,+ _READY_RE, _TOKEN_RE, Dashboard, Sandbox, group_members, kill_group, poll,)+from tests.e2e.core.dashboard._reaper import kill_identifiedclass KnownIssue(AssertionError):@@ -117,13 +118,11 @@ class PtyDashboard(Dashboard):def close(self) -> None:with contextlib.suppress(Exception):self.http.close()- pids = group_pids(self.proc.pid)+ members = group_members(self.proc.pid)kill_group(self.proc) # SIGKILL: a wedged worker thread blocks any graceful exitwith contextlib.suppress(Exception):self.proc.wait(timeout=15)- for pid in pids: # anything that left the group (setsid'd MCP children) but was ours- with contextlib.suppress(ProcessLookupError, PermissionError):- os.kill(pid, signal.SIGKILL)+ kill_identified(members) # recorded members that left the group since (setsid'd MCP children)if self.pty_master >= 0:with contextlib.suppress(OSError):os.close(self.pty_master)diff --git a/tests/e2e/core/dashboard/_pty_helpers.py b/tests/e2e/core/dashboard/_pty_helpers.pyindex 87bf104ab1c..e70d7d8d580 100644--- a/tests/e2e/core/dashboard/_pty_helpers.py+++ b/tests/e2e/core/dashboard/_pty_helpers.py@@ -12,18 +12,15 @@ separate writes, and the CR is only sent once the text is echoed in the composerProcess bookkeeping (``ProcessLedger``) records every descendant of the dashboard by (pid, starttime) plus the session ids they lead: ``ptyprocess`` makes each TUI a session leader outside thedashboard's process group, so a group kill does not reach it and only the dashboard's own shutdown-path can.+path can. Cleanup of what it records goes through ``_reaper`` like every other sandbox process."""from __future__ import annotationsimport json-import osimport re-import signalimport threadingimport time-from pathlib import Pathfrom typing import Any, Callablefrom websockets.exceptions import ConnectionClosed@@ -31,6 +28,8 @@ from websockets.sync.client import connectfrom tests.e2e.core.terminal._vt import Screen+from ._reaper import Identity, all_stats, cmdline+_WS = re.compile(r"\s+")_DIGITS = re.compile(r"\d")_SCROLLBAR = "│┃║▐▕█░▒▓"@@ -167,45 +166,19 @@ class WsTerm:# -- process bookkeeping ----------------------------------------------------------------------------def _stat(pid: int) -> list[str] | None:- """Fields after ``comm`` of a live, non-zombie process (state is index 0)."""- try:- fields = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()- except (OSError, IndexError):- return None- return None if fields[0] in ("Z", "X") else fields---def _start_time(pid: int) -> int | None:- fields = _stat(pid)- return int(fields[19]) if fields else None---def cmdline(pid: int) -> str:- try:- return Path(f"/proc/{pid}/cmdline").read_bytes().replace(b"\0", b" ").decode(errors="replace").strip()- except OSError:- return "?"---def _all_stats() -> dict[int, list[str]]:- out = {}- for entry in os.listdir("/proc"):- if entry.isdigit() and (fields := _stat(int(entry))) is not None:- out[int(entry)] = fields- return out--class ProcessLedger:- """Every process the dashboard (transitively) spawned, keyed by (pid, start time)."""+ """Every process the dashboard (transitively) spawned, keyed by (pid, start time).++ ``identities`` is a ``_reaper`` finder: the fixture hands it to ``Sandbox.finish`` so the+ ledger's processes go through the same wait-then-identity-checked-kill as the sandbox's."""def __init__(self, root_pid: int) -> None:self.root_pid = root_pid- self.seen: dict[tuple[int, int], str] = {}+ self.seen: dict[Identity, str] = {}self.sids: set[int] = set()def snapshot(self) -> list[int]:- stats = _all_stats()+ stats = all_stats()children: dict[int, list[int]] = {}for pid, fields in stats.items():children.setdefault(int(fields[1]), []).append(pid)@@ -222,22 +195,9 @@ class ProcessLedger:self.seen.setdefault((pid, int(stats[pid][19])), cmdline(pid))return sorted(found)- def survivors(self) -> list[str]:- live = {pid for pid, started in self.seen if _start_time(pid) == started}- live |= {pid for pid, fields in _all_stats().items() if int(fields[3]) in self.sids}- return [f"{pid}: {cmdline(pid)[:160]}" for pid in sorted(live)]-- def kill_survivors(self) -> list[str]:- """Hard cleanup of exactly the processes recorded here (identity-checked, never by pattern).- Uses the real ``kill(2)``: a survivor reparented to init is outside pytest's subtree, which- the suite-wide live-system guard would otherwise refuse, yet it is provably ours (same pid- AND kernel start time as recorded while it descended from the dashboard)."""- import posix- left = self.survivors()- for (pid, started) in list(self.seen):- if _start_time(pid) == started:- try:- posix.kill(pid, signal.SIGKILL)- except (ProcessLookupError, PermissionError):- pass- return left+ def identities(self) -> dict[Identity, str]:+ """Recorded processes plus current members of any recorded PTY session."""+ live = dict(self.seen)+ live.update({(pid, int(fields[19])): cmdline(pid)+ for pid, fields in all_stats().items() if int(fields[3]) in self.sids})+ return livediff --git a/tests/e2e/core/dashboard/_reaper.py b/tests/e2e/core/dashboard/_reaper.pynew file mode 100644index 00000000000..631c1441197--- /dev/null+++ b/tests/e2e/core/dashboard/_reaper.py@@ -0,0 +1,161 @@+"""The ONE place the dashboard lane cleans up processes a test left behind.++Two problems, one mechanism:++* Detached children escape every handle the test holds. ``gateway/shutdown_forensics.py``+ runs a ``timeout 5 bash -c ...`` diagnostic in its own session on every gateway shutdown,+ ``ptyprocess`` makes each TUI a session leader, MCP stdio servers ``setsid``. When their parent+ dies they are reparented, by default to init.+* A process reparented to init is outside the pytest process subtree, so the live-system guards+ (``tests/conftest.py`` and the developer plugin) refuse to signal it, and+ ``@pytest.mark.live_system_guard_bypass`` cannot help: the plugin re-arms in+ ``pytest_runtest_teardown`` before fixture finalizers run, so a bypass never covers teardown.++``adopt_orphans()`` makes the pytest process the child subreaper (``PR_SET_CHILD_SUBREAPER``):+an orphaned descendant reparents to pytest instead of init and stays inside the subtree the+guards allow. Nothing is exempted from the guard; a process that did not descend from this pytest+process can never be adopted, so it stays refused.++``reap()`` then waits (with a deadline) for everything a test spawned to exit on its own. Only+processes still alive at the deadline are SIGKILLed, each checked against the (pid, kernel start+time) recorded when it was first seen, so a recycled pid is never hit. The killed ones come back as+the leak report.+"""++from __future__ import annotations++import ctypes+import os+import signal+import sys+import time+from pathlib import Path+from typing import Callable++Identity = tuple[int, int] # (pid, kernel start time in clock ticks)+Finder = Callable[[], dict[Identity, str]]++REAP_TIMEOUT = 30.0 # the gateway's shutdown diagnostic self-terminates within ``timeout 5``+_PR_SET_CHILD_SUBREAPER = 36+_adopters = 0+++def _set_subreaper(on: bool) -> None:+ libc = ctypes.CDLL(None, use_errno=True)+ if libc.prctl(_PR_SET_CHILD_SUBREAPER, int(on), 0, 0, 0) != 0:+ raise OSError(ctypes.get_errno(), "prctl(PR_SET_CHILD_SUBREAPER) failed")+++def adopt_orphans() -> None:+ """Start adopting orphaned descendants (refcounted; pair with ``release_orphans``)."""+ global _adopters+ if sys.platform.startswith("linux") and _adopters == 0:+ _set_subreaper(True)+ _adopters += 1+++def release_orphans() -> None:+ """Stop adopting once no sandbox needs it. Processes already adopted stay our children."""+ global _adopters+ _adopters = max(0, _adopters - 1)+ if sys.platform.startswith("linux") and _adopters == 0:+ _set_subreaper(False)+++def stat(pid: int) -> list[str] | None:+ """``/proc/<pid>/stat`` fields after ``comm`` (state is index 0, ppid 1, sid 3, start 19)."""+ try:+ return Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()+ except (OSError, IndexError):+ return None+++def start_time(pid: int) -> int | None:+ """Kernel start time of a live, non-zombie process; None when it is gone or a zombie."""+ fields = stat(pid)+ return int(fields[19]) if fields and fields[0] not in ("Z", "X") else None+++def cmdline(pid: int) -> str:+ try:+ return Path(f"/proc/{pid}/cmdline").read_bytes().replace(b"\0", b" ").decode(errors="replace").strip()+ except OSError:+ return "?"+++def all_stats() -> dict[int, list[str]]:+ """Every live, non-zombie process."""+ out = {}+ for entry in os.listdir("/proc"):+ if entry.isdigit() and (fields := stat(int(entry))) is not None and fields[0] not in ("Z", "X"):+ out[int(entry)] = fields+ return out+++def with_home(home: Path) -> Finder:+ """Every live process whose environment points HOME into ``home`` (the sandbox), except us."""+ needle = f"HOME={home}".encode()++ def find() -> dict[Identity, str]:+ found = {}+ for pid in all_stats():+ if pid == os.getpid():+ continue+ try:+ if needle not in Path(f"/proc/{pid}/environ").read_bytes().split(b"\0"):+ continue+ except OSError:+ continue+ if (started := start_time(pid)) is not None:+ found[(pid, started)] = cmdline(pid)+ return found+ return find+++def _collect_zombies(idents: dict[Identity, str]) -> None:+ """``waitpid`` the adopted ones that already exited, so no zombie outlives the test."""+ for pid, _ in idents:+ fields = stat(pid)+ if fields and fields[0] == "Z" and int(fields[1]) == os.getpid():+ try:+ os.waitpid(pid, os.WNOHANG)+ except ChildProcessError:+ pass+++def kill_identified(idents: dict[Identity, str]) -> list[str]:+ """SIGKILL exactly the recorded processes that are still the SAME process (pid and start time)."""+ killed = []+ for (pid, started), cmd in idents.items():+ if start_time(pid) != started:+ continue+ try:+ os.kill(pid, signal.SIGKILL)+ except ProcessLookupError:+ continue+ killed.append(f"{pid}: {cmd[:160]}")+ return killed+++def reap(*finders: Finder, timeout: float = REAP_TIMEOUT) -> list[str]:+ """Wait up to ``timeout`` s for every process the finders report to exit by itself, then kill+ the survivors (identity-checked). Returns the killed ones: an empty list means nothing leaked."""+ seen: dict[Identity, str] = {}+ deadline = time.monotonic() + timeout+ while True:+ for find in finders:+ seen.update(find())+ _collect_zombies(seen)+ live = {ident: cmd for ident, cmd in seen.items() if start_time(ident[0]) == ident[1]}+ if not live:+ return []+ if time.monotonic() >= deadline:+ break+ time.sleep(0.1)+ killed = kill_identified(live)+ settle = time.monotonic() + 10+ while time.monotonic() < settle and any(start_time(pid) == started for pid, started in live):+ _collect_zombies(live)+ time.sleep(0.05)+ _collect_zombies(live)+ return killeddiff --git a/tests/e2e/core/dashboard/test_api_session_chat_limits.py b/tests/e2e/core/dashboard/test_api_session_chat_limits.pyindex 82105207902..ed87b72dae1 100644--- a/tests/e2e/core/dashboard/test_api_session_chat_limits.py+++ b/tests/e2e/core/dashboard/test_api_session_chat_limits.py@@ -43,7 +43,7 @@ def gateway(tmp_path_factory: pytest.TempPathFactory) -> Iterator[tuple[Sandbox,finally:if gw is not None:gw.stop()- sb.stop()+ sb.finish()def _long_message(n: int) -> tuple[str, str, str]:diff --git a/tests/e2e/core/dashboard/test_dashboard_auth.py b/tests/e2e/core/dashboard/test_dashboard_auth.pyindex 48571210175..6340e16837d 100644--- a/tests/e2e/core/dashboard/test_dashboard_auth.py+++ b/tests/e2e/core/dashboard/test_dashboard_auth.py@@ -54,7 +54,7 @@ def dash(tmp_path_factory: pytest.TempPathFactory):yield dfinally:d.close()- sb.stop()+ sb.finish()@pytest.fixture(scope="module")diff --git a/tests/e2e/core/dashboard/test_dashboard_mcp_install.py b/tests/e2e/core/dashboard/test_dashboard_mcp_install.pyindex d61baac86cf..7f2c0c9ee6a 100644--- a/tests/e2e/core/dashboard/test_dashboard_mcp_install.py+++ b/tests/e2e/core/dashboard/test_dashboard_mcp_install.py@@ -27,7 +27,7 @@ from pathlib import Pathimport pytestimport yaml-from tests.e2e.core.dashboard._helpers import make_sandbox+from tests.e2e.core.dashboard._helpers import Sandbox, make_sandboxfrom tests.e2e.core.dashboard._issue_helpers import Issue120527, PtyDashboard, xfail_knownINSTALL_DEADLINE_S = 30.0 # a healthy install (write config + spawn/probe a local server) takes ~2 s@@ -43,6 +43,15 @@ KNOWN: dict[str, tuple[str, type]] = {}+def sb(tmp_path: Path):+ sandbox = make_sandbox(tmp_path)+ try:+ yield sandbox+ finally:+ sandbox.finish()++def _write_catalog(root: Path, name: str) -> Path:catalog = root / "optional-mcps"(catalog / name).mkdir(parents=True)@@ -68,12 +77,11 @@ def _ws_opens(url: str, timeout: float) -> str:return f"{type(exc).__name__}: {exc}"-def _install_and_probe(tmp_path: Path, *, tty: bool, wedge_exc: type[AssertionError]) -> dict:+def _install_and_probe(sb: Sandbox, tmp_path: Path, *, tty: bool, wedge_exc: type[AssertionError]) -> dict:"""Install the fixture entry through the dashboard, then probe the server's liveness.Raises ``wedge_exc`` when the install misses its deadline or a follow-up request stalls;returns the installed ``mcp_servers.<name>`` block when the install answered 200."""- sb = make_sandbox(tmp_path)name = f"dashfix-{sb.profiles['default'].tag}"catalog = _write_catalog(tmp_path, name)dash = PtyDashboard(sb, tmp_path / "dashboard.log", extra_env={"HERMES_OPTIONAL_MCPS": str(catalog)}, tty=tty)@@ -124,18 +132,17 @@ def _install_and_probe(tmp_path: Path, *, tty: bool, wedge_exc: type[AssertionErfinally:pool.shutdown(wait=False, cancel_futures=True)dash.close()- sb.stop()-def test_catalog_install_from_headless_dashboard_completes_with_all_probed_tools(tmp_path: Path) -> None:+def test_catalog_install_from_headless_dashboard_completes_with_all_probed_tools(sb: Sandbox, tmp_path: Path) -> None:"""Control (enforced): the same install from a stdin=/dev/null dashboard answers 200 promptly,leaves the server responsive, and — the manifest declaring no default_enabled — writes no toolfilter, so both probed fixture tools stay enabled."""- block = _install_and_probe(tmp_path, tty=False, wedge_exc=AssertionError)+ block = _install_and_probe(sb, tmp_path, tty=False, wedge_exc=AssertionError)assert block, "headless install did not answer 200"assert block.get("enabled") is True and "tools" not in block, f"unexpected tool filter: {block}"@xfail_known(KNOWN, "test_catalog_install_from_tty_launched_dashboard_never_wedges_the_server")-def test_catalog_install_from_tty_launched_dashboard_never_wedges_the_server(tmp_path: Path) -> None:- _install_and_probe(tmp_path, tty=True, wedge_exc=Issue120527)+def test_catalog_install_from_tty_launched_dashboard_never_wedges_the_server(sb: Sandbox, tmp_path: Path) -> None:+ _install_and_probe(sb, tmp_path, tty=True, wedge_exc=Issue120527)diff --git a/tests/e2e/core/dashboard/test_dashboard_profiles.py b/tests/e2e/core/dashboard/test_dashboard_profiles.pyindex 6e03f0462d7..4316cb35b8b 100644--- a/tests/e2e/core/dashboard/test_dashboard_profiles.py+++ b/tests/e2e/core/dashboard/test_dashboard_profiles.py@@ -44,7 +44,7 @@ def fleet(tmp_path_factory: pytest.TempPathFactory):yield sb, dfinally:d.close()- sb.stop()+ sb.finish()def _files(sb: H.Sandbox) -> dict[str, bytes]:diff --git a/tests/e2e/core/dashboard/test_dashboard_pty.py b/tests/e2e/core/dashboard/test_dashboard_pty.pyindex 947f6f3d0d8..074c06c3ec3 100644--- a/tests/e2e/core/dashboard/test_dashboard_pty.py+++ b/tests/e2e/core/dashboard/test_dashboard_pty.py@@ -17,8 +17,9 @@ Contract under test (``hermes_cli/web_routers/chat_ws.py::pty_ws`` + ``hermes_clNot a cell: "dashboard shutdown leaves no TUI behind". It holds, but it cannot be made red from thedashboard side: with ``PtySessionRegistry.close_all`` disabled (and even with the child ignoringSIGHUP) the TUI still exits when the dying dashboard's PTY master closes (kernel hangup / EIO) and-its ``tui_gateway`` exits on stdin EOF. The fixture still waits for, reports and reaps any-descendant that outlives the dashboard, so a leak cannot poison later tests.+its ``tui_gateway`` exits on stdin EOF. The fixture still waits for every descendant to exit and+fails the test (after an identity-checked kill) on any that outlives the dashboard, so a leak is+reported and cannot poison later tests."""from __future__ import annotations@@ -182,14 +183,7 @@ def dash_env(tmp_path: Path):try:dash.close()finally:- try:- poll(lambda: not ledger.survivors(), 30, "dashboard descendants to exit")- except AssertionError:- pass- left = ledger.kill_survivors()- if left:- print("teardown killed dashboard leftovers:\n " + "\n ".join(left), file=sys.stderr)- sb.stop()+ sb.finish(ledger.identities)def _assert_labelled(term: WsTerm, profile: str) -> None:diff --git a/tests/e2e/core/dashboard/test_dashboard_sessions.py b/tests/e2e/core/dashboard/test_dashboard_sessions.pyindex 1434ba8eff5..508bde2c508 100644--- a/tests/e2e/core/dashboard/test_dashboard_sessions.py+++ b/tests/e2e/core/dashboard/test_dashboard_sessions.py@@ -80,7 +80,7 @@ def env(tmp_path_factory: pytest.TempPathFactory):yield sb, p, dfinally:d.close()- sb.stop()+ sb.finish()def _read_round(d: H.Dashboard, committed: Callable[[], int]) -> list[str]: