The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: descendant sweep spares the stopper, reports leftovers, and skips subtrees of unkillable roots
teknium11038e0fc7785
diff --git a/hermes_cli/dashboard_procs.py b/hermes_cli/dashboard_procs.pyindex 6d313cc75d9..7d2670b78d0 100644--- a/hermes_cli/dashboard_procs.py+++ b/hermes_cli/dashboard_procs.py@@ -301,6 +301,13 @@ def _is_detached_session_leader(pid: int, tty: str) -> bool:they are the user's, not the dashboard's, and must survive a dashboard stop. A hosted``hermes --tui`` child is a session leader too (``pty.fork``) but owns the pts whose master thedashboard held, so its tty column is set and it stays in the sweep.++ Known gap: the turn-isolation ``tui_gateway.compute_host`` and ``slash_worker`` children are+ launched the same way (``start_new_session=True``, no tty; ``compute_host`` also holds+ ``state.db``), so a wedged WAL holder of that class is spared here too. Their exit relies on+ their own ppid watchdogs (``compute_host._parent_guard_loop``,+ ``slash_worker._start_parent_death_watchdog``), not on this sweep. Discriminating by WAL-holder+ identity (``iter_deleted_sqlite_sidecar_holders``) was deliberately not done in this change."""if tty not in _NO_TTY:return False@@ -310,12 +317,15 @@ def _is_detached_session_leader(pid: int, tty: str) -> bool:return False-def _posix_descendants(roots: list[int]) -> dict[int, int | None]:- """``{pid: start_time}`` of every dashboard-owned descendant of *roots*, snapshotted BEFORE the- kill: once the root dies its children are reparented and the PPID link is gone. Detached session- leaders (see ``_is_detached_session_leader``) are pruned together with their own subtrees. The- start-time fingerprint is the PID-reuse guard (same one ``_kill_pids_windows`` uses).- Empty on scan failure → root-only kill, the historical behaviour.+def _posix_descendants(roots: list[int]) -> dict[int, tuple[int, int | None]]:+ """``{pid: (root, start_time)}`` of every dashboard-owned descendant of *roots*, snapshotted+ BEFORE the kill: once the root dies its children are reparented and the PPID link is gone.+ Detached session leaders (see ``_is_detached_session_leader``) are pruned together with their own+ subtrees. So is the calling process with its subtree and its ancestor chain: ``hermes dashboard+ --stop`` / ``hermes update`` run from a shell escape inside the hosted Chat TUI are same-session+ descendants of the backend, and sweeping them would SIGTERM the caller mid-run (POSIX twin of the+ Windows #98814 hazard). The start-time fingerprint is the PID-reuse guard (same one+ ``_kill_pids_windows`` uses). Empty on scan failure → root-only kill, the historical behaviour."""from gateway.status import get_process_start_timetry:@@ -323,18 +333,27 @@ def _posix_descendants(roots: list[int]) -> dict[int, int | None]:except (FileNotFoundError, subprocess.TimeoutExpired, OSError):return {}children: dict[int, list[tuple[int, str]]] = {}+ parent: dict[int, int] = {}for line in (result.stdout or "").splitlines():parts = line.split()if len(parts) == 3 and parts[0].isdigit() and parts[1].isdigit():children.setdefault(int(parts[1]), []).append((int(parts[0]), parts[2]))- found: dict[int, int | None] = {}- pending = list(roots)+ parent[int(parts[0])] = int(parts[1])+ me = os.getpid()+ ancestors: set[int] = set()+ cur = me+ while (cur := parent.get(cur, 0)) > 1 and cur not in ancestors:+ ancestors.add(cur)+ found: dict[int, tuple[int, int | None]] = {}+ pending = [(root, root) for root in roots]while pending:- for pid, tty in children.get(pending.pop(), ()):- if pid in found or pid in roots or _is_detached_session_leader(pid, tty):+ root, cur = pending.pop()+ for pid, tty in children.get(cur, ()):+ if pid in found or pid in roots or pid == me or _is_detached_session_leader(pid, tty):continue- found[pid] = get_process_start_time(pid)- pending.append(pid)+ if pid not in ancestors: # an ancestor of the caller is spared, but its other children are not+ found[pid] = (root, get_process_start_time(pid))+ pending.append((root, pid))return found@@ -356,7 +375,9 @@ def _kill_pids_posix(pids: list[int], killed: list[int], failed: list[tuple[int,"""SIGTERM, wait up to ``_POSIX_TERM_GRACE_SECONDS`` for graceful exit, SIGKILL survivors, thensweep the dashboard-owned descendants that outlived the root and wait for the tree to be gone.- *killed* / *failed* report the roots only; swept descendants are the roots' own teardown debt.+ *killed* reports the roots only; swept descendants are the roots' own teardown debt. A descendant+ still alive after its SIGKILL grace is appended to *failed*: the stop must not be declared+ complete while a wedged ui-tui still holds the deleted state.db-wal inode (#112631)."""import signal as _signal@@ -383,13 +404,15 @@ def _kill_pids_posix(pids: list[int], killed: list[int], failed: list[tuple[int,_send(pid, _signal.SIGKILL)# Snapshot identity must still match: a PID recycled during the grace is not ours to signal.- survivors = [p for p, start in descendants.items()+ survivors = [p for p, (_root, start) in descendants.items()if start is not None and get_process_start_time(p) == start]for sig in (_signal.SIGTERM, _signal.SIGKILL):for pid in survivors:with contextlib.suppress(OSError):os.kill(pid, sig)survivors = _wait_gone(survivors, _POSIX_DESCENDANT_GRACE_SECONDS)+ failed.extend((pid, "descendant of the stopped backend still alive after SIGKILL")+ for pid in survivors)def _kill_stale_dashboard_processes(@@ -845,9 +868,10 @@ def _reap_orphaned_desktop_local_serves(# A SIGKILLed backend never ran PTY_REGISTRY.close_all(): its hosted ui-tui / MCP trees would# keep the deleted state.db-wal inode open (#112631). The boot-path budget leaves no second# grace, and these trees already lost their Electron and their backend.+ # A root whose own kill raised (EPERM: not ours) keeps its subtree — do not orphan it half-way.from gateway.status import get_process_start_time- for pid, start in descendants.items():- if start is not None and get_process_start_time(pid) == start:+ for pid, (root, start) in descendants.items():+ if root not in failed and start is not None and get_process_start_time(pid) == start:with contextlib.suppress(OSError):os.kill(pid, signal_kill)with contextlib.suppress(Exception):diff --git a/tests/hermes_cli/test_dashboard_procs_kill_grace.py b/tests/hermes_cli/test_dashboard_procs_kill_grace.pyindex dc55ccc1112..f8d7b661495 100644--- a/tests/hermes_cli/test_dashboard_procs_kill_grace.py+++ b/tests/hermes_cli/test_dashboard_procs_kill_grace.py@@ -14,6 +14,7 @@ real signals, a real PTY.from __future__ import annotationsimport os+import pathlibimport signalimport subprocessimport sys@@ -24,6 +25,8 @@ import pytestfrom hermes_cli import dashboard_procs+_REPO_ROOT = pathlib.Path(dashboard_procs.__file__).resolve().parents[1]+pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX signal semantics only")# Mirrors the lifespan: sleep for the teardown budget on SIGTERM, then leave a marker and exit 0.@@ -175,3 +178,53 @@ def test_wedged_pty_descendant_is_gone_but_detached_bot_survives(tmp_path, monkefor pid in (tui_pid, bot_pid):if _pid_running(pid):os.kill(pid, signal.SIGKILL)+++# The stopper itself, run as a same-session child of the backend (a shell escape inside the hosted+# Chat TUI): `hermes dashboard --stop` / `hermes update` must not SIGTERM their own process.+_STOPPER_CHILD = textwrap.dedent(+ """+ import os, pathlib, sys+ from hermes_cli import dashboard_procs as dp+ dp._POSIX_TERM_GRACE_SECONDS = 0.5+ backend, marker = int(sys.argv[1]), pathlib.Path(sys.argv[2])+ snapshot = dp._posix_descendants([backend])+ killed, failed = [], []+ dp._kill_pids_posix([backend], killed, failed)+ marker.write_text(f"{os.getpid() in snapshot} {killed} {failed}")+ """+)++_BACKEND_WITH_STOPPER_CHILD = textwrap.dedent(+ f"""+ import os, pathlib, signal, subprocess, sys, time+ signal.signal(signal.SIGTERM, lambda *_: time.sleep(300))+ pathlib.Path(sys.argv[2]).write_text("ready")+ subprocess.Popen([sys.executable, "-c", {_STOPPER_CHILD!r}, str(os.getpid()), sys.argv[1]]).wait()+ time.sleep(300)+ """+)+++def test_stopper_running_as_backend_descendant_survives_the_sweep(tmp_path):+ """POSIX twin of the Windows #98814 hazard: the caller and its ancestors are not descendants+ to sweep, even when the stop runs from inside the backend's own process tree."""+ marker, ready = tmp_path / "marker", tmp_path / "ready"+ env = dict(os.environ, PYTHONPATH=os.pathsep.join(filter(None, [str(_REPO_ROOT), os.environ.get("PYTHONPATH")])))+ backend = subprocess.Popen(+ [sys.executable, "-c", _BACKEND_WITH_STOPPER_CHILD, str(marker), str(ready)], env=env,+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,+ )+ try:+ deadline = time.monotonic() + 30.0+ while backend.poll() is None and time.monotonic() < deadline:+ time.sleep(0.05)+ assert backend.returncode == -signal.SIGKILL, "the stopper never SIGKILLed the wedged backend"+ assert marker.exists(), "stopper died before finishing the stop: it swept itself"+ in_snapshot, _, rest = marker.read_text().partition(" ")+ assert in_snapshot == "False"+ assert rest == f"[{backend.pid}] []"+ finally:+ if backend.poll() is None:+ backend.kill()+ backend.wait(timeout=10)diff --git a/tests/hermes_cli/test_orphan_desktop_serve_reap.py b/tests/hermes_cli/test_orphan_desktop_serve_reap.pyindex 48b48ce40c2..d0dc26b61e7 100644--- a/tests/hermes_cli/test_orphan_desktop_serve_reap.py+++ b/tests/hermes_cli/test_orphan_desktop_serve_reap.py@@ -411,3 +411,41 @@ def test_reap_spare_lock_owned_backend_even_without_exclude_match(tmp_path):assert terms == []assert result["matched"] == []+++def test_reap_kills_descendants_of_killed_roots_but_spares_a_failed_roots_subtree():+ """#112631: a SIGKILLed backend never ran PTY_REGISTRY.close_all(), so the reaper sweeps its+ surviving hosted-TUI children — but only for roots it actually killed. A root whose own kill+ raised (EPERM: not ours) keeps its subtree intact instead of being orphaned half-way."""+ scanned = [+ (111, "hermes serve --host 127.0.0.1 --port 0"), # ours: killed, child 1111 swept+ (444, "hermes serve --host 127.0.0.1 --port 0"), # not ours: EPERM, child 4444 spared+ ]+ descendants = {1111: (111, 5.0), 4444: (444, 6.0)}+ start_times = {1111: 5.0, 4444: 6.0}+ sent: list[tuple[int, int]] = []++ def fake_kill(pid, sig):+ if pid == 444:+ raise PermissionError("Operation not permitted")+ sent.append((pid, sig))++ with (+ patch("hermes_cli.dashboard_procs._scan_dashboard_processes", return_value=scanned),+ patch("hermes_cli.dashboard_procs._process_ppid", return_value=1),+ patch("hermes_cli.dashboard_procs._posix_descendants", return_value=descendants) as snap,+ patch("gateway.status.get_process_start_time", side_effect=start_times.get),+ patch("psutil.pid_exists", return_value=True),+ patch("os.kill", side_effect=fake_kill),+ patch("sys.platform", "darwin"),+ ):+ os.environ.pop("HERMES_DESKTOP_CHILD_PID", None)+ result = _reap_orphaned_desktop_local_serves(+ sleep_fn=lambda _s: None, signal_term=15, signal_kill=9,+ process_age_seconds_fn=lambda _pid: 600.0,+ )++ snap.assert_called_once_with([111, 444]) # snapshotted before the kill reparents them+ assert result["killed"] == [111] and result["failed"] == [444]+ assert (1111, 9) in sent, "surviving child of the killed backend was not swept"+ assert not any(pid == 4444 for pid, _ in sent), "child of a root we could not kill was swept"