Skip to content

The agent that grows with you

fix(processes): signal a process group only when the child leads it

beardthelion956cd8dd3e65
diff --git a/agent/verify/runner.py b/agent/verify/runner.py
index 4016c1638be..d08549bbd2c 100644
--- a/agent/verify/runner.py
+++ b/agent/verify/runner.py
@@ -137,6 +137,10 @@ def _terminate_process_group(proc: subprocess.Popen) -> None:
pgid = getpgid(proc.pid)
except (ProcessLookupError, PermissionError):
pass
+ if pgid is not None and pgid != proc.pid:
+ # The child does not lead its own group, so it shares ours: killpg would
+ # signal the whole runner process tree. Signal the direct child only.
+ pgid = None
def stop(sig: int, fallback: Callable[[], None]) -> None:
if pgid is not None:
diff --git a/hermes_cli/pty_bridge.py b/hermes_cli/pty_bridge.py
index 653f780124b..6e8963dc873 100644
--- a/hermes_cli/pty_bridge.py
+++ b/hermes_cli/pty_bridge.py
@@ -284,6 +284,10 @@ class PtyBridge:
pgid = self._pgid
leader_was_alive = self._proc.isalive()
+ if pgid is not None and pgid != self._proc.pid:
+ # Not a group leader: the child shares OUR process group, so killpg would
+ # take the TUI down with it. Signal the child directly instead.
+ pgid = None
# Signal the whole process group, not just the PTY leader: the dashboard TUI starts helper
# children (e.g. the Python slash worker) and killing only the leader strands them.
diff --git a/tests/hermes_cli/test_pty_bridge.py b/tests/hermes_cli/test_pty_bridge.py
index 42ca2cd15ed..0bf3c005fab 100644
--- a/tests/hermes_cli/test_pty_bridge.py
+++ b/tests/hermes_cli/test_pty_bridge.py
@@ -271,12 +271,52 @@ class TestPtyBridgeClose:
bridge = PtyBridge.__new__(PtyBridge)
bridge._proc = fake
bridge._fd = -1
+ # recorded at spawn; the child leads its own group (pgid == pid)
+ bridge._pgid = 12345
+ bridge._closed = False
+
+ bridge.close()
+
+ assert sent == [(12345, signal.SIGHUP)]
+ assert bridge._closed is True
+
+ def test_close_never_killpgs_a_shared_group(self, monkeypatch):
+ """A child that does not lead its own group shares OURS — killpg would
+ signal the TUI's own process tree. The fallback is per-signal proc.kill."""
+ sent: list[tuple[int, signal.Signals]] = []
+ direct: list[signal.Signals] = []
+
+ class _FakeProc:
+ pid = 12345
+ fd = -1
+
+ def __init__(self):
+ self.alive = True
+
+ def isalive(self):
+ return self.alive
+
+ def kill(self, sig):
+ direct.append(sig)
+ self.alive = False
+
+ def close(self, force=False):
+ self.closed = force
+
+ fake = _FakeProc()
+ monkeypatch.setattr(os, "killpg", lambda pgid, sig: sent.append((pgid, sig)))
+
+ bridge = PtyBridge.__new__(PtyBridge)
+ bridge._proc = fake
+ bridge._fd = -1
+ # recorded at spawn: the child was found in OUR group (pgid != pid)
bridge._pgid = 67890
bridge._closed = False
bridge.close()
- assert sent == [(67890, signal.SIGHUP)]
+ assert sent == [] # the guard nulls the non-leader pgid: no group signal
+ assert direct == [signal.SIGHUP]
assert bridge._closed is True
def test_close_ends_helpers_that_outlive_a_dead_leader(self):
diff --git a/tests/tools/test_browser_process_tree.py b/tests/tools/test_browser_process_tree.py
index a56d2837b95..ab3d7f16bde 100644
--- a/tests/tools/test_browser_process_tree.py
+++ b/tests/tools/test_browser_process_tree.py
@@ -2,11 +2,13 @@
import os
import signal
+import subprocess
+import time
from unittest.mock import MagicMock, patch
import pytest
-from tools.browser_tool_lifecycle import _legacy_kill_process_tree
+from tools.browser_tool_lifecycle import _kill_process_tree, _legacy_kill_process_tree
@pytest.mark.platforms("posix")
@@ -57,4 +59,130 @@ def test_permission_denied_does_not_attempt_sigkill(monkeypatch):
def test_windows_taskkill_targets_tree_and_is_best_effort(error):
with patch("subprocess.run", side_effect=error) as run:
_legacy_kill_process_tree(MagicMock(pid=4321))
- assert run.call_args.args[0] == ["taskkill", "/PID", "4321", "/T", "/F"]
\ No newline at end of file
+ assert run.call_args.args[0] == ["taskkill", "/PID", "4321", "/T", "/F"]
+
+# ---------------------------------------------------------------------------
+# Group-leadership guard (#119149): a child that does not lead its own group
+# shares OURS — killpg would signal the whole Hermes/test-runner tree.
+# ---------------------------------------------------------------------------
+
+
+def test_posix_shared_group_is_never_killpgd(monkeypatch):
+ """A child spawned without start_new_session shares OUR process group, so
+ os.getpgid returns the caller's own pgid — killpg would signal the whole
+ Hermes/test-runner tree. Only a group leader may be killpg'd; the direct
+ child still gets proc.kill()."""
+ proc = MagicMock()
+ proc.pid = 999
+ monkeypatch.setattr(os, "getpgid", lambda pid: 555) # child's group != its pid
+ killpg_calls = []
+ monkeypatch.setattr(os, "killpg", lambda pgid, sig: killpg_calls.append((pgid, sig)))
+
+ _legacy_kill_process_tree(proc)
+
+ assert killpg_calls == []
+ proc.kill.assert_called_once()
+
+
+def test_real_shared_group_child_does_not_signal_us(monkeypatch):
+ """End-to-end through _kill_process_tree with the deadline helper forced
+ to fail: a real child in our own process group must be proc.kill()ed
+ without any killpg — if the group signal fired, this test process would
+ be dead before the assertion."""
+ from tools.browser_tool_lifecycle import _kill_process_tree
+
+ proc = subprocess.Popen(
+ ["sleep", "60"],
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+ try:
+ assert os.getpgid(proc.pid) == os.getpgid(0) # shared group precondition
+ monkeypatch.setattr(
+ "agent.deadline.kill_process_tree",
+ lambda *a, **k: (_ for _ in ()).throw(RuntimeError("deadline unavailable")),
+ )
+ _kill_process_tree(proc)
+ proc.wait(timeout=5)
+ assert proc.returncode is not None
+ finally:
+ if proc.poll() is None:
+ proc.kill()
+
+
+def test_real_shared_group_child_descendants_are_killed(tmp_path):
+ """A shared-group child's descendants can hold the capture pipe's write
+ end open past proc.kill() (the #68915 communicate() hang), so the
+ non-leader path must kill them individually. The grandchild is in OUR
+ process group: if the implementation regressed to killpg this test
+ process would die before the assertion."""
+ pid_file = tmp_path / "grandchild.pid"
+ proc = subprocess.Popen(
+ ["sh", "-c", f"sleep 60 & echo $! > {pid_file}; wait"],
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+ gcpid = None
+ try:
+ deadline = time.monotonic() + 5
+ while time.monotonic() < deadline:
+ text = pid_file.read_text().strip() if pid_file.exists() else ""
+ if text:
+ gcpid = int(text)
+ break
+ time.sleep(0.05)
+ assert gcpid is not None, "grandchild never wrote its pid file"
+ assert os.getpgid(proc.pid) == os.getpgid(0) # shared group precondition
+
+ _legacy_kill_process_tree(proc)
+ proc.wait(timeout=5)
+
+ deadline = time.monotonic() + 5
+ while time.monotonic() < deadline:
+ try:
+ os.kill(gcpid, 0)
+ except ProcessLookupError:
+ break
+ time.sleep(0.05)
+ else:
+ pytest.fail(f"grandchild pid {gcpid} survived the non-leader tree kill")
+ finally:
+ if proc.poll() is None:
+ proc.kill()
+ if gcpid is not None:
+ try:
+ os.kill(gcpid, signal.SIGKILL)
+ except OSError:
+ pass
+
+
+def test_real_group_leader_child_is_tree_killed(monkeypatch):
+ """Control: a child leading its own group (process_group=0) still gets the
+ group signal through the same fallback path."""
+ from tools.browser_tool_lifecycle import _kill_process_tree
+
+ proc = subprocess.Popen(
+ ["sleep", "60"],
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ process_group=0,
+ )
+ try:
+ assert os.getpgid(proc.pid) == proc.pid # leader precondition
+ monkeypatch.setattr(
+ "agent.deadline.kill_process_tree",
+ lambda *a, **k: (_ for _ in ()).throw(RuntimeError("deadline unavailable")),
+ )
+ _kill_process_tree(proc)
+ proc.wait(timeout=5)
+ assert proc.returncode is not None
+ finally:
+ if proc.poll() is None:
+ proc.kill()
diff --git a/tests/tools/test_local_setsid_descendant_sweep.py b/tests/tools/test_local_setsid_descendant_sweep.py
index 151583695c6..bc29e40af51 100644
--- a/tests/tools/test_local_setsid_descendant_sweep.py
+++ b/tests/tools/test_local_setsid_descendant_sweep.py
@@ -174,3 +174,48 @@ def test_kill_process_never_killpgs_the_callers_own_group(monkeypatch):
assert killpg_calls == []
assert killed == [12345]
+
+
[email protected](os.name != "posix", reason="POSIX process-group semantics")
+class TestReapUntrackedGroupGuard:
+ """ProcessRegistry._reap_untracked must never killpg a group the child does
+ not lead: a child that shares our process group would take the whole
+ process tree down with it."""
+
+ def test_shared_group_child_gets_proc_kill_only(self, monkeypatch):
+ from unittest.mock import MagicMock
+
+ from tools.process_registry import ProcessRegistry
+
+ reg = ProcessRegistry()
+ proc = MagicMock()
+ proc.pid = 999
+ session = SimpleNamespace(systemd_unit="")
+ monkeypatch.setattr(os, "getpgid", lambda pid: 555) # != pid: shared group
+ killpg_calls = []
+ monkeypatch.setattr(os, "killpg", lambda pgid, sig: killpg_calls.append((pgid, sig)))
+
+ reg._reap_untracked(session, proc)
+
+ assert killpg_calls == []
+ proc.kill.assert_called_once()
+
+ def test_group_leader_child_gets_the_group_signal(self, monkeypatch):
+ """Control: a start_new_session child leads its own group and is killed
+ through killpg so its descendants go with it."""
+ from unittest.mock import MagicMock
+
+ from tools.process_registry import ProcessRegistry
+
+ reg = ProcessRegistry()
+ proc = MagicMock()
+ proc.pid = 999
+ session = SimpleNamespace(systemd_unit="")
+ monkeypatch.setattr(os, "getpgid", lambda pid: 999) # == pid: group leader
+ killpg_calls = []
+ monkeypatch.setattr(os, "killpg", lambda pgid, sig: killpg_calls.append((pgid, sig)))
+
+ reg._reap_untracked(session, proc)
+
+ assert len(killpg_calls) == 1 and killpg_calls[0][0] == 999
+ proc.kill.assert_not_called()
diff --git a/tests/verify/test_environment_and_runner.py b/tests/verify/test_environment_and_runner.py
index 2778e5898a4..d81bced5f5a 100644
--- a/tests/verify/test_environment_and_runner.py
+++ b/tests/verify/test_environment_and_runner.py
@@ -2,6 +2,7 @@
import http.server
import json
+import os
import subprocess
import threading
import time
@@ -263,3 +264,68 @@ class TestReadiness:
finally:
server.shutdown()
thread.join(timeout=5)
+
+
[email protected](os.name != "posix", reason="POSIX process-group semantics")
+class TestTerminateProcessGroupGuard:
+ """_terminate_process_group must never killpg a group the child does not
+ lead: a child spawned without start_new_session shares OUR process group,
+ and the group signal would take the verify runner down with it."""
+
+ def test_shared_group_child_gets_terminate_only(self, monkeypatch):
+ import os as _os
+
+ from agent.verify.runner import _terminate_process_group
+
+ proc = MagicMock()
+ proc.pid = 999
+ proc.poll.return_value = None
+ monkeypatch.setattr(_os, "getpgid", lambda pid: 555) # != pid: shared group
+ killpg_calls = []
+ monkeypatch.setattr(_os, "killpg", lambda pgid, sig: killpg_calls.append((pgid, sig)))
+
+ _terminate_process_group(proc)
+
+ assert killpg_calls == []
+ proc.terminate.assert_called_once()
+
+ def test_real_shared_group_child_does_not_signal_us(self):
+ """Real child in our own group: if killpg fired, this test process would
+ be dead before the assertion. The direct child still dies."""
+ import os as _os
+
+ from agent.verify.runner import _terminate_process_group
+
+ proc = subprocess.Popen(
+ ["sleep", "60"],
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ )
+ try:
+ assert _os.getpgid(proc.pid) == _os.getpgid(0) # shared group precondition
+ _terminate_process_group(proc)
+ proc.wait(timeout=5)
+ assert proc.returncode is not None
+ finally:
+ if proc.poll() is None:
+ proc.kill()
+
+ def test_real_group_leader_child_is_group_killed(self):
+ """Control: a start_new_session child leads its own group and is killed
+ through the group signal path."""
+ import os as _os
+
+ from agent.verify.runner import _terminate_process_group
+
+ proc = subprocess.Popen(
+ ["sleep", "60"],
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ process_group=0,
+ )
+ try:
+ assert _os.getpgid(proc.pid) == proc.pid # leader precondition
+ _terminate_process_group(proc)
+ proc.wait(timeout=5)
+ assert proc.returncode is not None
+ finally:
+ if proc.poll() is None:
+ proc.kill()
diff --git a/tools/browser_tool_lifecycle.py b/tools/browser_tool_lifecycle.py
index 8258fb6ab0b..baaed46fe10 100644
--- a/tools/browser_tool_lifecycle.py
+++ b/tools/browser_tool_lifecycle.py
@@ -505,8 +505,11 @@ def _kill_process_tree(proc: "subprocess.Popen") -> None:
def _legacy_kill_process_tree(proc: "subprocess.Popen") -> None:
- """Local tree-kill (SIGTERM then SIGKILL to the process group) — fallback when
- agent.deadline is unavailable; tests pin this signal sequence."""
+ """Local tree-kill (fallback when agent.deadline is unavailable; tests pin
+ the signal sequence). A child leading its own group gets SIGTERM then
+ SIGKILL via killpg; a shared-group child can never be killpg'd (that is OUR
+ group), so it and its psutil-snapshotted descendants are killed
+ individually."""
if os.name == "nt":
try:
subprocess.run(["taskkill", "/PID", str(proc.pid), "/T", "/F"],
@@ -526,12 +529,38 @@ def _legacy_kill_process_tree(proc: "subprocess.Popen") -> None:
try:
pgid = os.getpgid(proc.pid)
except (ProcessLookupError, OSError):
- return
- for sig in (signal.SIGTERM, getattr(signal, "SIGKILL", signal.SIGTERM)):
+ pgid = None
+ # Signal the group only when the child leads it (start_new_session / process_group=0):
+ # a child spawned into our group resolves pgid to OUR process group and killpg would
+ # take the whole Hermes tree down with it, and a recycled PID can resolve to a foreign
+ # group. The direct child still gets proc.kill() either way. Same ownership check as
+ # hermes_cli/_subprocess_compat._legacy_kill_process_tree.
+ descendants = []
+ if pgid is not None and pgid == proc.pid:
+ for sig in (signal.SIGTERM, getattr(signal, "SIGKILL", signal.SIGTERM)):
+ try:
+ killpg(pgid, sig)
+ except (ProcessLookupError, PermissionError, OSError):
+ break
+ else:
+ # No group signal is safe, so descendants are killed individually;
+ # a bare proc.kill() would leave them holding the capture pipe's write
+ # end open (the #68915 communicate() hang). The snapshot must precede
+ # the parent kill: once the parent exits, children reparent and psutil
+ # can no longer find them (process_registry._terminate_host_pid).
try:
- killpg(pgid, sig)
- except (ProcessLookupError, PermissionError, OSError):
- return
+ import psutil
+
+ descendants = psutil.Process(proc.pid).children(recursive=True)
+ except Exception:
+ descendants = []
+ try:
+ proc.kill()
+ except Exception:
+ pass
+ for child in descendants:
+ with contextlib.suppress(Exception):
+ child.kill()
def _pid_exists(pid: int) -> bool:
diff --git a/tools/process_registry.py b/tools/process_registry.py
index 256279e14f8..dbb7ada1f25 100644
--- a/tools/process_registry.py
+++ b/tools/process_registry.py
@@ -1263,7 +1263,15 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin):
elif not _IS_WINDOWS:
try:
kill_signal = getattr(signal, "SIGKILL", signal.SIGTERM)
- os.killpg(os.getpgid(proc.pid), kill_signal) # windows-footgun: ok - guarded by _IS_WINDOWS above
+ pgid = os.getpgid(proc.pid)
+ if pgid == proc.pid:
+ # The child leads its own group (start_new_session): the
+ # group signal reaches any descendants with it.
+ os.killpg(pgid, kill_signal) # windows-footgun: ok - guarded by _IS_WINDOWS above
+ else:
+ # Shared our process group — killpg would take the whole
+ # tree down with it. Kill the direct child only.
+ proc.kill()
except (ProcessLookupError, PermissionError, OSError):
proc.kill()
else: