Skip to content

The agent that grows with you

fix(process_registry): drop dashboard/serve worker scoping; make the hang test catch the hang

unsupportedpastels8ffb3c655000
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index 3850afa7ecc..fdbc439b1d1 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -1560,12 +1560,6 @@ 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 132b17e4896..8dac830063d 100644
--- a/tests/tools/test_process_registry_pty_kill.py
+++ b/tests/tools/test_process_registry_pty_kill.py
@@ -1,19 +1,16 @@
-"""Killing a PTY background process must return, and must reach descendants that escape it.
+"""Killing a PTY background process must return while a descendant that escapes it holds the PTY.
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.
+long-lived one), so the kill never returned. Once killed, the session's output stays as the
+kill reported it. 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
@@ -23,12 +20,16 @@ from tools.process_registry import ProcessRegistry
_POSIX_PTY = pytest.mark.skipif(
sys.platform == "win32" or shutil.which("setsid") is None, reason="POSIX PTY + setsid")
-# 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.
+# 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.
_ESCAPEE_LIFETIME_S = 8
_KILL_DEADLINE_S = 5
-# The scoped kill reaps the escapee at once; the bound only matters when the scope is missing.
-_SCOPED_ESCAPEE_LIFETIME_S = 30
+
+
+def unscoped(monkeypatch):
+ # No systemd scope: stopping one would reap the escapee and hide the hang.
+ monkeypatch.setattr(module, "_is_supervised_gateway_process", lambda: False)
def _wait_for(predicate, timeout):
@@ -40,32 +41,32 @@ def _wait_for(predicate, timeout):
return predicate()
-def _pid_alive(pid):
- try:
- os.kill(pid, 0)
- except ProcessLookupError:
- return False
- except PermissionError:
- return True
- return True
+def _terminate_owned(session):
+ """Failure-path cleanup: stop the PTY child this test spawned (never the reparented escapee)."""
+ if not session.exited and session._pty is not None:
+ try:
+ session._pty.terminate(force=True)
+ except Exception:
+ pass
-def _spawn_with_escapee(registry, tmp_path, escapee_lifetime, late_output=""):
+def _spawn_with_escapee(registry, tmp_path, late_output=""):
pidfile = tmp_path / "escapee.pid"
- # ``late_output`` is printed by the escapee to the PTY after the test has killed the session.
+ # Without ``late_output`` the escapee never writes to the PTY, so nothing ends the reader's
+ # blocked read before the kill deadline. ``late_output`` is printed after the test has
+ # killed the session.
late = f"sleep 2; echo {late_output}; " if late_output else ""
- # The escapee's pid is read as the PPID of a grandchild, not as ``$$``: on the
- # scoped path ``systemd-run --scope`` (systemd >= 254) expands the command line
- # itself and turns ``$$`` into a literal ``$`` before the shell sees it.
+ # The escapee's pid is read as the PPID of a grandchild, not as ``$$``: under
+ # ``systemd-run --scope`` with environment expansion, ``$$`` reaches the shell as ``$``.
session = registry.spawn_local(
- f"setsid sh -c 'sh -c \"echo \\$PPID\" > {pidfile}; {late}exec sleep {escapee_lifetime}' & sleep 120",
+ f"setsid sh -c 'sh -c \"echo \\$PPID\" > {pidfile}; {late}exec sleep {_ESCAPEE_LIFETIME_S}' & sleep 120",
cwd=str(tmp_path), use_pty=True)
try:
assert _wait_for(lambda: pidfile.exists() and pidfile.read_text().strip(), 5)
- return session, int(pidfile.read_text())
except BaseException:
_terminate_owned(session)
raise
+ return session
def _kill_within_deadline(registry, session):
@@ -78,48 +79,57 @@ def _kill_within_deadline(registry, session):
return result
-def _terminate_owned(session):
- """Failure-path cleanup: stop the PTY child this test spawned (never the reparented escapee)."""
- if session.systemd_unit:
- module._stop_systemd_unit(session.systemd_unit)
- if not session.exited and session._pty is not None:
- try:
- session._pty.terminate(force=True)
- except Exception:
- pass
+def _wait_for_reader_close(session):
+ # The reader outlives the kill and closes the PTY itself once its read ends (when the
+ # escapee exits), so the master FD is still released.
+ reader = session._reader_thread
+ assert reader is not None
+ assert _wait_for(lambda: not reader.is_alive(), _ESCAPEE_LIFETIME_S + 7)
+ assert session._pty.closed
@_POSIX_PTY
-def test_kill_returns_while_escaped_descendant_holds_the_pty(tmp_path, monkeypatch):
+def test_kill_returns_while_escaped_descendant_holds_the_pty(tmp_path, unscoped):
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, late_output="LATE-ESCAPEE-OUTPUT")
-
- result = _kill_within_deadline(registry, session)
+ session = _spawn_with_escapee(registry, tmp_path)
+ try:
+ result = _kill_within_deadline(registry, session)
+ finally:
+ _terminate_owned(session)
assert result["status"] == "killed"
assert session.id in registry._finished
+ _wait_for_reader_close(session)
- # The reader stays alive past the kill and closes the PTY itself once its read ends (here
- # after it drains the escapee's late output), so the master FD is still released.
- reader = session._reader_thread
- assert reader is not None
- assert _wait_for(lambda: not reader.is_alive(), _ESCAPEE_LIFETIME_S + 7)
- assert session._pty.closed
- # What the escapee printed after the kill was drained, not added to the killed session.
+
+@_POSIX_PTY
+def test_output_after_the_kill_is_not_added_to_the_killed_session(tmp_path, monkeypatch, unscoped):
+ pytest.importorskip("ptyprocess")
+ registry = ProcessRegistry()
+ emit, emitted = registry._emit_output, []
+
+ def recording_emit(session, text):
+ emitted.append(text)
+ emit(session, text)
+
+ registry._emit_output = recording_emit
+ session = _spawn_with_escapee(registry, tmp_path, late_output="LATE-ESCAPEE-OUTPUT")
+ try:
+ result = _kill_within_deadline(registry, session)
+ finally:
+ _terminate_owned(session)
+ assert result["status"] == "killed"
+ # The reader drains what the escapee printed after the kill, but does not keep it.
+ _wait_for_reader_close(session)
assert "LATE-ESCAPEE-OUTPUT" not in session.output_buffer
+ assert not any("LATE-ESCAPEE-OUTPUT" in text for text in emitted)
@_POSIX_PTY
-def test_chunk_read_before_the_kill_is_not_added_after_it(tmp_path, monkeypatch):
+def test_chunk_read_before_the_kill_is_not_added_after_it(tmp_path, unscoped):
# The reader has read a chunk but not yet buffered it when the kill snapshots the output
# and sets ``exited``. The chunk must not land in the killed session afterwards.
pytest.importorskip("ptyprocess")
- monkeypatch.setattr(module, "_is_supervised_gateway_process", lambda: False)
- monkeypatch.setattr(module, "_is_supervised_backend_host", lambda: False, raising=False)
registry = ProcessRegistry()
entered, release = threading.Event(), threading.Event()
ingest, emit, emitted = registry._ingest_output, registry._emit_output, []
@@ -148,70 +158,3 @@ def test_chunk_read_before_the_kill_is_not_added_after_it(tmp_path, monkeypatch)
assert "RACE-MARKER" not in result.get("output", "")
assert "RACE-MARKER" not in session.output_buffer
assert not any("RACE-MARKER" in text for text in emitted)
-
-
[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, _SCOPED_ESCAPEE_LIFETIME_S)
- 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:
- _terminate_owned(session)
-
-
-def test_start_server_marks_the_process_as_backend_host(monkeypatch):
- # The scope gate is only as good as the startup wiring: the real dashboard / serve entry
- # point must mark the process before it serves anything.
- pytest.importorskip("uvicorn")
- from hermes_cli import web_server
-
- class _StopBoot(Exception):
- pass
-
- seen = []
-
- def _auth_gate(*_args, **_kwargs):
- seen.append(module._backend_host)
- raise _StopBoot
-
- monkeypatch.setattr(module, "_backend_host", False, raising=False)
- monkeypatch.setattr("hermes_cli.resource_limits.apply_nofile_soft_limit", lambda: None)
- monkeypatch.setattr("hermes_cli.nous_auth_keepalive.start_nous_auth_keepalive", lambda: None)
- monkeypatch.setattr(web_server, "_configure_auth_gate", _auth_gate)
-
- with pytest.raises(_StopBoot):
- web_server.start_server(open_browser=False, headless=True)
-
- assert seen == [True], "start_server reached its auth gate without marking the backend host"
diff --git a/tools/process_registry.py b/tools/process_registry.py
index 63cff8b2f54..80b5173da27 100644
--- a/tools/process_registry.py
+++ b/tools/process_registry.py
@@ -306,36 +306,6 @@ 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.
@@ -1306,9 +1276,8 @@ 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. 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())
+ # This applies to both pipe mode and the PTY path above. See #70716.
+ in_supervised_gateway = _IS_LINUX and _is_supervised_gateway_process()
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)