Skip to content

The agent that grows with you

fix(process_registry): scope background processes of a supervised dashboard/serve backend

unsupportedpastels4ad9f3ca2801
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index fdbc439b1d1..3850afa7ecc 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -1560,6 +1560,12 @@ def start_server(
apply_nofile_soft_limit()
+ # Background processes this backend spawns get their own systemd scope when it runs
+ # under a service manager, like the supervised gateway's (#132358).
+ from tools.process_registry import mark_backend_host
+
+ mark_backend_host()
+
import uvicorn # noqa: F401 — fail fast (before any side effects) when the dashboard extra is missing
try:
diff --git a/tests/tools/test_process_registry_pty_kill.py b/tests/tools/test_process_registry_pty_kill.py
index 6bf756baa9b..b737abbda67 100644
--- a/tests/tools/test_process_registry_pty_kill.py
+++ b/tests/tools/test_process_registry_pty_kill.py
@@ -1,27 +1,30 @@
-"""Killing a PTY process must return even when a descendant escaped into its own session.
+"""Killing a PTY background process must return, and must reach descendants that escape it.
-The escapee keeps the PTY slave open, so the reader thread stays blocked in ``read()`` holding
-the PTY file object's buffer lock. Closing the PTY from the kill path waited on that lock until
-the escapee exited (forever, for a long-lived one), so the kill never returned. Real PTY, real
-processes: a fake PTY cannot hold the lock.
+An escapee (a descendant that ``setsid()``s into its own session) keeps the PTY slave open, so
+the reader thread stays blocked in ``read()`` holding the PTY file object's buffer lock. Closing
+the PTY from the kill path waited on that lock until the escapee exited (forever, for a
+long-lived one), so the kill never returned. And unless the process runs in its own systemd
+scope, nothing reaps the escapee: a supervised dashboard / serve backend now gets that scope
+like the supervised gateway does. Real PTY, real processes: a fake PTY cannot hold the lock.
"""
+import os
import shutil
import sys
import threading
import time
+from types import SimpleNamespace
import pytest
import tools.process_registry as module
from tools.process_registry import ProcessRegistry
-pytest.importorskip("ptyprocess")
-pytestmark = pytest.mark.skipif(
+_POSIX_PTY = pytest.mark.skipif(
sys.platform == "win32" or shutil.which("setsid") is None, reason="POSIX PTY + setsid")
-# The escapee exits on its own (it is reparented to init, outside what a test may signal).
-# Before the fix the kill could only return once it had, so the kill deadline is shorter.
+# The unscoped escapee exits on its own (it is reparented to init, outside what a test may
+# signal). Before the fix the kill could only return once it had, so the kill deadline is shorter.
_ESCAPEE_LIFETIME_S = 8
_KILL_DEADLINE_S = 5
@@ -35,22 +38,45 @@ def _wait_for(predicate, timeout):
return predicate()
-def test_kill_returns_while_escaped_descendant_holds_the_pty(tmp_path, monkeypatch):
- # No systemd scope: stopping one would reap the escapee and hide the hang.
- monkeypatch.setattr(module, "_is_supervised_gateway_process", lambda: False)
+def _pid_alive(pid):
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ return False
+ except PermissionError:
+ return True
+ return True
+
+
+def _spawn_with_escapee(registry, tmp_path, escapee_lifetime):
pidfile = tmp_path / "escapee.pid"
- registry = ProcessRegistry()
session = registry.spawn_local(
- f"setsid sh -c 'echo $$ > {pidfile}; exec sleep {_ESCAPEE_LIFETIME_S}' & sleep 120",
+ f"setsid sh -c 'echo $$ > {pidfile}; exec sleep {escapee_lifetime}' & sleep 120",
cwd=str(tmp_path), use_pty=True)
assert _wait_for(lambda: pidfile.exists() and pidfile.read_text().strip(), 5)
+ return session, int(pidfile.read_text())
+
+def _kill_within_deadline(registry, session):
result = {}
killer = threading.Thread(
target=lambda: result.update(registry.kill_process(session.id)), daemon=True)
killer.start()
killer.join(_KILL_DEADLINE_S)
assert not killer.is_alive(), "kill_process blocked closing the PTY under a live reader"
+ return result
+
+
+@_POSIX_PTY
+def test_kill_returns_while_escaped_descendant_holds_the_pty(tmp_path, monkeypatch):
+ pytest.importorskip("ptyprocess")
+ # No systemd scope: stopping one would reap the escapee and hide the hang.
+ monkeypatch.setattr(module, "_is_supervised_gateway_process", lambda: False)
+ monkeypatch.setattr(module, "_is_supervised_backend_host", lambda: False, raising=False)
+ registry = ProcessRegistry()
+ session, _ = _spawn_with_escapee(registry, tmp_path, _ESCAPEE_LIFETIME_S)
+
+ result = _kill_within_deadline(registry, session)
assert result["status"] == "killed"
assert session.id in registry._finished
@@ -60,3 +86,45 @@ def test_kill_returns_while_escaped_descendant_holds_the_pty(tmp_path, monkeypat
assert reader is not None
assert _wait_for(lambda: not reader.is_alive(), _ESCAPEE_LIFETIME_S + 5)
assert session._pty.closed
+
+
[email protected]("marked, supervised, scoped", [
+ (True, True, True), # dashboard / serve run by a service manager
+ (True, False, False), # dashboard / serve started from a shell
+ (False, True, False), # a CLI or terminal child that only inherited the supervisor env
+])
+def test_supervised_backend_host_scopes_background_processes(monkeypatch, marked, supervised, scoped):
+ monkeypatch.setattr(module, "_IS_LINUX", True)
+ monkeypatch.setattr(module, "_is_supervised_gateway_process", lambda: False)
+ monkeypatch.setattr(module, "_systemd_run_user_scope_available", lambda: True)
+ monkeypatch.setattr(module, "_build_systemd_scope_argv",
+ lambda argv, unit_suffix: ["systemd-run", "--unit", unit_suffix, *argv])
+ monkeypatch.setattr(module, "_backend_host", marked, raising=False)
+ monkeypatch.setattr("gateway.restart.is_supervised_gateway_launch", lambda *a, **k: supervised)
+ session = SimpleNamespace(systemd_unit="")
+
+ argv = ProcessRegistry._scope_argv(ProcessRegistry(), session, "echo hi", "proc_x", "PTY")
+
+ assert (argv[0] == "systemd-run") is scoped
+ assert bool(session.systemd_unit) is scoped
+
+
+@_POSIX_PTY
+def test_scoped_backend_kill_reaps_an_escaped_descendant(tmp_path, monkeypatch):
+ pytest.importorskip("ptyprocess")
+ if sys.platform != "linux" or not module._systemd_run_user_scope_available():
+ pytest.skip("needs systemd-run --user --scope (a reachable user bus)")
+ monkeypatch.setattr(module, "_is_supervised_gateway_process", lambda: False)
+ monkeypatch.setattr(module, "_backend_host", True, raising=False)
+ monkeypatch.setattr("gateway.restart.is_supervised_gateway_launch", lambda *a, **k: True)
+ registry = ProcessRegistry()
+ session, escapee = _spawn_with_escapee(registry, tmp_path, 120)
+ try:
+ assert session.systemd_unit.startswith("hermes-worker-")
+ result = _kill_within_deadline(registry, session)
+ assert result["status"] == "killed"
+ # Stopping the scope reaps the whole cgroup, the escapee included.
+ assert _wait_for(lambda: not _pid_alive(escapee), 10), "escaped descendant survived the kill"
+ finally:
+ if session.systemd_unit:
+ module._stop_systemd_unit(session.systemd_unit)
diff --git a/tools/process_registry.py b/tools/process_registry.py
index ca6848b8298..67117cced85 100644
--- a/tools/process_registry.py
+++ b/tools/process_registry.py
@@ -306,6 +306,36 @@ def _is_supervised_gateway_process() -> bool:
return False
+# Set by the dashboard / ``serve`` web backend when it starts (``web_server.start_server``).
+# Process-local on purpose: an environment marker would be inherited by every terminal
+# child and CLI the backend spawns, which must not count as the backend itself.
+_backend_host = False
+
+
+def mark_backend_host() -> None:
+ """Mark this process as a long-lived dashboard / ``serve`` backend."""
+ global _backend_host
+ _backend_host = True
+
+
+def _is_supervised_backend_host() -> bool:
+ """Whether this process is a dashboard / ``serve`` backend run by a service manager.
+
+ Like the supervised gateway, it hosts agent turns for remote clients with nobody at a
+ terminal, so its background processes need their own scope: an OOM must not take the
+ backend down, and a kill must reach descendants that ``setsid()`` away from the PTY or
+ process group (stopping the scope reaps the whole cgroup)."""
+ if not _backend_host:
+ return False
+ try:
+ from gateway.restart import is_supervised_gateway_launch
+
+ return is_supervised_gateway_launch()
+ except Exception as exc:
+ logger.debug("Could not verify supervised backend launch: %s", exc)
+ return False
+
+
def _build_systemd_scope_argv(shell_argv: List[str], unit_suffix: str) -> List[str]:
"""Wrap *shell_argv* in a ``systemd-run --user --scope`` invocation with its own
memory accounting, so an OOM in the worker cannot kill the gateway cgroup.
@@ -1263,8 +1293,9 @@ class ProcessRegistry(ProcessCheckpointMixin):
the supervised gateway (own cgroup: an OOM kills only the worker, not the
gateway and its messaging control plane)."""
argv = [_find_shell(), "-lic", f"set +m; {safe_command}"]
- # This applies to both pipe mode and the PTY path above. See #70716.
- in_supervised_gateway = _IS_LINUX and _is_supervised_gateway_process()
+ # This applies to both pipe mode and the PTY path above. See #70716. A supervised
+ # dashboard / serve backend gets the same isolation (#132358).
+ in_supervised_gateway = _IS_LINUX and (_is_supervised_gateway_process() or _is_supervised_backend_host())
if in_supervised_gateway and _systemd_run_user_scope_available():
session.systemd_unit = f"hermes-worker-{unit_suffix}.scope"
return _build_systemd_scope_argv(argv, unit_suffix=unit_suffix)