Skip to content

The agent that grows with you

fix(hooks): kill the whole process tree when a shell hook times out

Teknium3b9d1b3cde8f
diff --git a/agent/shell_hooks.py b/agent/shell_hooks.py
index c2aa916d28e..868b58db14b 100644
--- a/agent/shell_hooks.py
+++ b/agent/shell_hooks.py
@@ -145,7 +145,7 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable, Dict, Iterator, List, Optional, Set, Tuple
-from hermes_cli._subprocess_compat import IS_WINDOWS, windows_hide_flags
+from hermes_cli._subprocess_compat import IS_WINDOWS, kill_process_tree, windows_hide_flags
try:
import fcntl # POSIX only; Windows falls back to best-effort without flock.
@@ -544,21 +544,26 @@ def _spawn(spec: ShellHookSpec, stdin_json: str) -> Dict[str, Any]:
return result
t0 = time.monotonic()
- _popen_kwargs = {"creationflags": windows_hide_flags()} if IS_WINDOWS else {}
+ # Spawn the hook in its own process group on POSIX (``process_group=0``,
+ # Python ≥3.11) so a timed-out hook's descendants can be reaped with the
+ # hook itself. Windows keeps the hidden-window flags; tree cleanup there
+ # goes through ``taskkill /T`` in ``kill_process_tree``. Hooks that
+ # complete in time keep their descendants — an intentionally detached
+ # helper (``some-daemon &``) survives a successful run. Ported from
+ # openai/codex#37527 ("Terminate timed-out hook process trees").
+ _popen_kwargs: Dict[str, Any] = (
+ {"creationflags": windows_hide_flags()} if IS_WINDOWS else {"process_group": 0}
+ )
try:
- proc = subprocess.run(
+ proc = subprocess.Popen(
argv,
- input=stdin_json,
- capture_output=True,
- timeout=spec.timeout,
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
text=True, encoding='utf-8', errors='replace',
shell=False,
**_popen_kwargs,
)
- except subprocess.TimeoutExpired:
- result["timed_out"] = True
- result["elapsed_seconds"] = round(time.monotonic() - t0, 3)
- return result
except FileNotFoundError:
result["error"] = "command not found"
return result
@@ -569,9 +574,32 @@ def _spawn(spec: ShellHookSpec, stdin_json: str) -> Dict[str, Any]:
result["error"] = str(exc)
return result
+ try:
+ stdout, stderr = proc.communicate(input=stdin_json, timeout=spec.timeout)
+ except subprocess.TimeoutExpired:
+ # Take down the whole process tree, not just the direct child —
+ # otherwise a hook that forked helpers leaves them running (and,
+ # holding the pipe write ends, they'd stall the drain below).
+ kill_process_tree(proc)
+ try:
+ proc.communicate(timeout=1)
+ except Exception:
+ pass
+ result["timed_out"] = True
+ result["elapsed_seconds"] = round(time.monotonic() - t0, 3)
+ return result
+ except Exception as exc: # pragma: no cover — defensive
+ kill_process_tree(proc)
+ try:
+ proc.communicate(timeout=1)
+ except Exception:
+ pass
+ result["error"] = str(exc)
+ return result
+
result["returncode"] = proc.returncode
- result["stdout"] = proc.stdout or ""
- result["stderr"] = proc.stderr or ""
+ result["stdout"] = stdout or ""
+ result["stderr"] = stderr or ""
result["elapsed_seconds"] = round(time.monotonic() - t0, 3)
return result
diff --git a/hermes_cli/_subprocess_compat.py b/hermes_cli/_subprocess_compat.py
index 10076731fa9..3813bfaab82 100644
--- a/hermes_cli/_subprocess_compat.py
+++ b/hermes_cli/_subprocess_compat.py
@@ -383,22 +383,24 @@ def noninteractive_git_env(
# -----------------------------------------------------------------------------
-def _kill_git_process_tree(proc: "subprocess.Popen") -> None:
+def kill_process_tree(proc: "subprocess.Popen") -> None:
"""Best-effort terminate *proc* and its descendants on both platforms.
``proc.kill()`` alone only terminates the direct child. On Windows a
- suspended descendant ``git.exe`` can survive holding duplicates of the
+ suspended descendant (e.g. ``git.exe``) can survive holding duplicates of the
captured pipe handles, which keeps the pipes from reaching EOF and leaks two
reader threads + the process per fired timeout — ``taskkill /T /F`` takes the
whole tree down so the bounded drain that follows can actually reach EOF.
On POSIX the same class exists: killing the launcher leaves descendants
(credential helpers, ``git-remote-https``, hook children) running and
- holding the pipe write ends. The probe is spawned in its own process group
- (``process_group=0`` in :func:`bounded_git_probe`), so when — and only
+ holding the pipe write ends. Callers spawn the child in its own process
+ group (``process_group=0``, Python ≥3.11), so when — and only
when — the child leads its own group (``pgid == pid``), the entire group is
signalled with ``os.killpg``. The ownership check means a fallback spawn
that shares our group can never cause us to kill unrelated processes.
- Ported from openai/codex#36793 ("Terminate timed-out Git process trees").
+ Ported from openai/codex#36793 ("Terminate timed-out Git process trees");
+ generalized for the shell-hook runner via openai/codex#37527
+ ("Terminate timed-out hook process trees").
All failures are swallowed — this is cleanup on an already-failing path, and
the caller's contract is to fail open. ``kill()`` can raise (access denied,
@@ -489,10 +491,14 @@ def bounded_git_probe(argv: Sequence[str], *, timeout: float) -> str:
# Timeout OR any other communicate() failure (torn-down pipe, decode
# error): terminate the child + descendants and drain bounded. Leaving
# it running would leak the same suspended-descendant class this guards.
- _kill_git_process_tree(proc)
+ kill_process_tree(proc)
try:
proc.communicate(timeout=1)
except Exception:
pass
return ""
return stdout.strip() if proc.returncode == 0 else ""
+
+
+# Backward-compat alias — existing call sites/tests import the historical name.
+_kill_git_process_tree = kill_process_tree
diff --git a/tests/agent/test_shell_hooks_tree_kill.py b/tests/agent/test_shell_hooks_tree_kill.py
new file mode 100644
index 00000000000..942f51e9203
--- /dev/null
+++ b/tests/agent/test_shell_hooks_tree_kill.py
@@ -0,0 +1,160 @@
+"""Process-tree cleanup for timed-out shell hooks (port of openai/codex#37527).
+
+Timing out a shell hook must not leave descendant processes running after the
+hook itself is stopped. ``_spawn`` places the hook in its own process group on
+POSIX (``process_group=0``) and, on timeout, ``kill_process_tree`` signals the
+whole group — gated on the child actually leading its own group so a
+shared-group spawn can never take down unrelated processes. Hooks that
+complete within their timeout keep their descendants (intentionally detached
+helpers survive a successful run).
+
+These tests use REAL subprocesses (no mocks): group membership and survival
+semantics cannot be mocked.
+"""
+
+import os
+import sys
+import textwrap
+import time
+
+import pytest
+
+from agent.shell_hooks import ShellHookSpec, _spawn
+
+pytestmark = pytest.mark.skipif(
+ sys.platform == "win32", reason="POSIX process-group semantics"
+)
+
+
+def _spec(command: str, timeout: int = 2) -> ShellHookSpec:
+ return ShellHookSpec(
+ event="post_tool_call",
+ command=command,
+ matcher=None,
+ timeout=timeout,
+ fail_closed=False,
+ )
+
+
+def _write_forking_script(tmp_path, stall_after: bool):
+ """A hook that forks a long-lived descendant, then stalls or exits."""
+ marker = tmp_path / "child.pid"
+ script = tmp_path / "hook.sh"
+ tail = "sleep 300" if stall_after else "exit 0"
+ script.write_text(
+ textwrap.dedent(
+ f"""\
+ #!/bin/bash
+ sleep 300 &
+ echo $! > {marker}
+ {tail}
+ """
+ )
+ )
+ script.chmod(0o755)
+ return script, marker
+
+
+def _pid_alive(pid: int) -> bool:
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ return False
+ return True
+
+
+def _read_marker(marker, timeout=5.0) -> int:
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if marker.exists() and marker.read_text().strip():
+ return int(marker.read_text().strip())
+ time.sleep(0.05)
+ raise AssertionError("hook script never wrote its descendant pid")
+
+
+def test_timeout_kills_descendants(tmp_path):
+ """A hook timeout must take the forked descendant down with the hook."""
+ script, marker = _write_forking_script(tmp_path, stall_after=True)
+
+ t0 = time.monotonic()
+ r = _spawn(_spec(str(script), timeout=1), "{}")
+ elapsed = time.monotonic() - t0
+
+ assert r["timed_out"] is True
+ assert elapsed < 30, "timeout cleanup must not hang on held pipes"
+
+ child_pid = _read_marker(marker)
+ deadline = time.monotonic() + 3.0
+ while time.monotonic() < deadline and _pid_alive(child_pid):
+ time.sleep(0.05)
+ alive = _pid_alive(child_pid)
+ if alive: # cleanup so a failure doesn't leak a 300s sleeper
+ os.kill(child_pid, 9)
+ assert not alive, f"descendant {child_pid} survived hook timeout"
+
+
[email protected]_system_guard_bypass # cleanup-kills a helper reparented to init
+def test_successful_hook_preserves_detached_helpers(tmp_path):
+ """A hook that completes in time keeps its intentionally detached helpers.
+
+ Mirrors codex#37527's "preserve descendants on success" semantics: tree
+ cleanup fires only on the timeout/error path.
+ """
+ script, marker = _write_forking_script(tmp_path, stall_after=False)
+ # Detach the helper's stdio so the pipes reach EOF despite the survivor.
+ script.write_text(
+ textwrap.dedent(
+ f"""\
+ #!/bin/bash
+ sleep 300 > /dev/null 2>&1 < /dev/null &
+ echo $! > {marker}
+ exit 0
+ """
+ )
+ )
+
+ r = _spawn(_spec(str(script), timeout=10), "{}")
+ assert r["timed_out"] is False
+ assert r["returncode"] == 0
+
+ child_pid = _read_marker(marker)
+ time.sleep(0.3)
+ alive = _pid_alive(child_pid)
+ if alive:
+ os.kill(child_pid, 9)
+ assert alive, "successful hook's detached helper must survive"
+
+
+def test_hook_child_leads_own_process_group(tmp_path):
+ """The hook child must lead its own group (killpg ownership precondition)."""
+ script = tmp_path / "pgid.sh"
+ script.write_text("#!/bin/bash\necho \"$$ $(ps -o pgid= -p $$ | tr -d ' ')\"\n")
+ script.chmod(0o755)
+
+ r = _spawn(_spec(str(script), timeout=10), "{}")
+ assert r["returncode"] == 0
+ pid, pgid = r["stdout"].split()
+ assert pid == pgid, f"hook child pid={pid} does not lead its group pgid={pgid}"
+ assert int(pgid) != os.getpgid(0), "hook child must not share our group"
+
+
+def test_fast_path_contract_unchanged(tmp_path):
+ """stdin JSON delivery, stdout/stderr capture, and exit codes still work."""
+ script = tmp_path / "echoer.sh"
+ script.write_text(
+ "#!/bin/bash\ncat\necho errline >&2\nexit 3\n"
+ )
+ script.chmod(0o755)
+
+ r = _spawn(_spec(str(script), timeout=10), '{"tool_name": "terminal"}')
+ assert r["returncode"] == 3
+ assert r["stdout"] == '{"tool_name": "terminal"}'
+ assert "errline" in r["stderr"]
+ assert r["error"] is None
+ assert r["timed_out"] is False
+
+
+def test_missing_command_still_fails_open():
+ r = _spawn(_spec("/nonexistent/hook-command-xyz", timeout=2), "{}")
+ assert r["error"] == "command not found"
+ assert r["returncode"] is None