The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(windows-e2e): find serve/gateway orphans by profile ownership, not ancestry
teknium10616f7204970
diff --git a/.github/workflows/tests-os.yml b/.github/workflows/tests-os.ymlindex ed4b323b161..60551077325 100644--- a/.github/workflows/tests-os.yml+++ b/.github/workflows/tests-os.yml@@ -268,3 +268,23 @@ jobs:OPENROUTER_API_KEY: ""OPENAI_API_KEY: ""NOUS_API_KEY: ""++ - name: No leftover Python / Hermes processes+ # Backstop for the per-test ownership checks: a file killed by its 900 s timeout,+ # or a detached grandchild some test's cleanup missed, leaves an interpreter behind+ # (Windows never re-parents, so nothing reaps it). The runner itself runs no+ # python.exe / hermes.exe once the suite is done.+ if: always()+ shell: pwsh+ run: |+ $names = 'python.exe', 'pythonw.exe', 'hermes.exe'+ $deadline = (Get-Date).AddSeconds(20)+ do {+ $left = @(Get-CimInstance Win32_Process | Where-Object { $names -contains $_.Name.ToLower() })+ if ($left.Count -eq 0) { 'no leftover python/hermes processes'; exit 0 }+ Start-Sleep -Milliseconds 500+ } while ((Get-Date) -lt $deadline)+ foreach ($p in $left) {+ "::error::leftover pid=$($p.ProcessId) ppid=$($p.ParentProcessId): $($p.CommandLine)"+ }+ exit 1diff --git a/tests/e2e/core/windows/_helpers.py b/tests/e2e/core/windows/_helpers.pyindex 24e1401bc81..1984dea5711 100644--- a/tests/e2e/core/windows/_helpers.py+++ b/tests/e2e/core/windows/_helpers.py@@ -229,30 +229,86 @@ def process_tree(pid: int) -> list[Any]:return []-def survivors(procs: Iterable[Any], timeout: float) -> list[str]:- """Wait until every handle is gone; describe the ones still running at the deadline."""+def kill_tree(procs: Iterable[Any]) -> None:+ """Test cleanup only: hard-kill whatever this test spawned that is still alive."""import psutil- procs = list(procs)- _gone, alive = psutil.wait_procs(procs, timeout=timeout)- out = []- for p in alive:+ for p in procs:try:- out.append(f"{p.pid} {' '.join(p.cmdline())[:200]}")+ p.kill()+ except psutil.Error:+ pass+++def _under(path: str, root: str) -> bool:+ path = os.path.normcase(os.path.normpath(path))+ return path == root or path.startswith(root + os.sep)+++def _owned_by(proc: Any, root: str, home: str) -> bool:+ """One process belongs to the fake profile if its HERMES_HOME is that home, or its+ cwd or any argv element lives under the profile root. Environment and cwd are+ inherited by detached grandchildren, so they survive a broken parent link."""+ import psutil++ try:+ env = {k.upper(): v for k, v in proc.environ().items()}+ if "HERMES_HOME" in env and os.path.normcase(os.path.normpath(env["HERMES_HOME"])) == home:+ return True+ if _under(proc.cwd(), root):+ return True+ return any(_under(arg, root) or root + os.sep in os.path.normcase(arg) for arg in proc.cmdline())+ except (psutil.Error, OSError):+ return False+++def owned_processes(home: WinHome, *, since: float) -> list[Any]:+ """Every live process created at/after ``since`` (epoch s) that belongs to ``home``,+ whatever its parent. Windows never re-parents: a child of a killed process keeps a+ dangling ppid, so ``Process.children()`` (and ``taskkill /T``) cannot see it. Finding+ orphans needs ownership, not ancestry."""+ import psutil++ root = os.path.normcase(os.path.normpath(str(home.root)))+ hermes_home = os.path.normcase(os.path.normpath(str(home.hermes_home)))+ me = os.getpid()+ owned = []+ for proc in psutil.process_iter():+ try:+ if proc.pid == me or proc.create_time() < since - 1.0: # 1 s: create_time rounding+ continueexcept psutil.Error:continue- return out+ if _owned_by(proc, root, hermes_home):+ owned.append(proc)+ return owned-def kill_tree(procs: Iterable[Any]) -> None:- """Test cleanup only: hard-kill whatever this test spawned that is still alive."""+def describe(procs: Iterable[Any]) -> list[str]:import psutil+ out = []for p in procs:try:- p.kill()+ out.append(f"pid={p.pid} ppid={p.ppid()} {' '.join(p.cmdline())[:200]}")except psutil.Error:- pass+ continue+ return out+++def owned_survivors(home: WinHome, *, since: float, timeout: float) -> list[str]:+ """Poll until nothing owned by ``home`` is alive; describe what is left at the deadline."""+ deadline = time.monotonic() + timeout+ while True:+ left = describe(owned_processes(home, since=since))+ if not left or time.monotonic() >= deadline:+ return left+ time.sleep(0.25)+++def kill_owned(home: WinHome, *, since: float) -> None:+ """Test cleanup only: hard-kill every process this test's profile still owns."""+ kill_tree(owned_processes(home, since=since))def taskkill_tree(pid: int) -> subprocess.CompletedProcess:diff --git a/tests/e2e/core/windows/test_boot_lifecycle.py b/tests/e2e/core/windows/test_boot_lifecycle.pyindex 22ea50f0c77..fbbc6634cc9 100644--- a/tests/e2e/core/windows/test_boot_lifecycle.py+++ b/tests/e2e/core/windows/test_boot_lifecycle.py@@ -6,11 +6,13 @@printed, the prompt reached the wire, and both messages persisted to ``state.db`` underthe session id the CLI announced.* ``hermes serve`` (the Desktop backend) — announces its port on stdout, and after the- Desktop's Windows quit path (``taskkill /T /F``) leaves no process of its tree behind- and a fresh backend boots again over the leftover host records.+ Desktop's Windows quit path (``taskkill /T /F``) leaves no process behind that it+ spawned (found by ownership of the scratch profile, not by parent links, which a+ detached grandchild does not keep) and a fresh backend boots again over the leftover+ host records.* ``hermes gateway run`` + ``hermes gateway stop`` — the Windows graceful-stop IPC (stopmarker, not TerminateProcess) drains the gateway: it exits on its own, records- ``stopped``, removes its pid file, and nothing of its tree survives.+ ``stopped``, removes its pid file, and nothing it spawned survives."""from __future__ import annotations@@ -22,6 +24,7 @@ import reimport socketimport subprocessimport threading+import timefrom pathlib import Pathimport pytest@@ -32,13 +35,13 @@ from tests.e2e.core.windows._helpers import (hermes,hermes_argv,hermes_exe,- kill_tree,+ kill_owned,last_user,make_home,nonce,- process_tree,+ owned_processes,+ owned_survivors,run,- survivors,taskkill_tree,wait_until,)@@ -127,22 +130,27 @@ def _serve_ready(home: WinHome) -> tuple[subprocess.Popen, int]:def test_serve_tree_kill_leaves_no_orphans_and_reboots(tmp_path: Path) -> None:with FakeLLMServer() as srv:home = make_home(tmp_path, srv.base_url)- first, port = _serve_ready(home)- tree = process_tree(first.pid)- second = None+ started = time.time()try:+ first, port = _serve_ready(home)+ # Positive control: the ownership scan must see the backend itself, or an empty+ # scan after the kill would prove nothing.+ owned = {p.pid for p in owned_processes(home, since=started)}+ assert first.pid in owned, f"ownership scan cannot see serve pid {first.pid} (saw {owned})"+killed = taskkill_tree(first.pid)assert killed.returncode == 0, killed.stderr- left = survivors(tree, timeout=30)- assert not left, f"processes of the killed backend tree survived taskkill /T /F: {left}"+ # Ownership, not ancestry: anything the backend spawned detached (a broken+ # parent link taskkill /T cannot follow) still carries this profile's+ # HERMES_HOME / cwd, and is an orphan the Desktop quit leaves behind.+ left = owned_survivors(home, since=started, timeout=30)+ assert not left, f"processes of the killed backend outlived taskkill /T /F: {left}"wait_until(lambda: not _port_open(port), 30, f"port {port} to be released")second, port2 = _serve_ready(home)assert second.poll() is None and _port_open(port2)finally:- kill_tree(tree)- if second is not None:- kill_tree(process_tree(second.pid))+ kill_owned(home, since=started)def _gateway_state(home: WinHome) -> dict:@@ -157,15 +165,14 @@ def test_gateway_stop_drains_gracefully(tmp_path: Path) -> None:with FakeLLMServer() as srv:home = make_home(tmp_path, srv.base_url)log = tmp_path / "gateway.log"+ started = time.time()with log.open("wb") as fh:gw = subprocess.Popen(hermes_argv("gateway", "run"), cwd=home.project, env=home.env(),stdin=subprocess.DEVNULL, stdout=fh, stderr=subprocess.STDOUT)- tree: list = []try:wait_until(lambda: _gateway_state(home).get("gateway_state") == "running" or gw.poll() is not None,READY_TIMEOUT, "gateway_state.json to report running")assert gw.poll() is None, f"gateway exited {gw.returncode} during boot:\n{log.read_text(errors='replace')}"- tree = process_tree(gw.pid)res = hermes(home, "gateway", "stop")assert res.returncode == 0 and "Stopped" in res.stdout, res.tail()@@ -175,6 +182,7 @@ def test_gateway_stop_drains_gracefully(tmp_path: Path) -> None:f"gateway did not drain through its graceful path (rc={code}); last state {state}\n"f"{log.read_text(errors='replace')[-3000:]}")assert not (home.hermes_home / "gateway.pid").exists(), "gateway.pid left behind after stop"- assert not survivors(tree, timeout=30), "processes of the gateway tree survived stop"+ left = owned_survivors(home, since=started, timeout=30)+ assert not left, f"processes of the gateway survived stop: {left}"finally:- kill_tree(tree or process_tree(gw.pid))+ kill_owned(home, since=started)diff --git a/tests/e2e/core/windows/test_state_db_guard.py b/tests/e2e/core/windows/test_state_db_guard.pyindex f3889d025fd..ef711206b73 100644--- a/tests/e2e/core/windows/test_state_db_guard.py+++ b/tests/e2e/core/windows/test_state_db_guard.py@@ -10,6 +10,7 @@ once the gateway is stopped, so a refusal is about the holder and nothing else.from __future__ import annotationsimport json+import reimport subprocessfrom pathlib import Path@@ -64,7 +65,8 @@ def test_optimize_storage_refuses_while_gateway_holds_store(tmp_path: Path) -> Ngw.wait(timeout=60)quiet = hermes(home, "sessions", "optimize-storage")assert quiet.returncode == 0, f"optimize-storage fails even with no holder:\n{quiet.tail()}"- named = any(str(p.pid) in held.stdout for p in tree) # venv launcher OR its interpreter child+ # venv launcher OR its interpreter child; whole-number match (pid 12 is not in 4123).+ named = any(re.search(rf"\b{p.pid}\b", held.stdout) for p in tree)expect(refused and named,f"optimize-storage ran under a live gateway (pid {gw.pid}) instead of refusing:\n{held.tail()}")finally: