Skip to content

The agent that grows with you

fix(codex): reap app-server descendant processes

Tekniuma180274a5544
diff --git a/agent/transports/codex_app_server.py b/agent/transports/codex_app_server.py
index 54d5ec4b17a..7d7d1c38e4a 100644
--- a/agent/transports/codex_app_server.py
+++ b/agent/transports/codex_app_server.py
@@ -34,6 +34,36 @@ class CodexAppServerError(RuntimeError):
return f"codex app-server error {self.code}: {self.message}"
+def _snapshot_descendants(pid: int) -> list[Any]:
+ """psutil handles for ``pid``'s current descendants ([] when psutil is unavailable)."""
+ try:
+ import psutil
+ return psutil.Process(int(pid)).children(recursive=True)
+ except Exception:
+ return []
+
+
+def _reap_snapshotted(descendants: list[Any]) -> None:
+ """SIGTERM the snapshotted descendants (deepest first), then SIGKILL survivors after a
+ bounded wait. psutil identity checks make a recycled PID a no-op."""
+ if not descendants:
+ return
+ import psutil
+ live = []
+ for child in reversed(descendants):
+ with contextlib.suppress(Exception):
+ if child.is_running():
+ child.terminate()
+ live.append(child)
+ try:
+ _, alive = psutil.wait_procs(live, timeout=1.0)
+ except Exception:
+ alive = live
+ for child in alive:
+ with contextlib.suppress(Exception):
+ child.kill()
+
+
class CodexAppServerClient:
"""Minimal synchronous JSON-RPC 2.0 client for ``codex app-server`` over stdio.
@@ -132,10 +162,16 @@ class CodexAppServerClient:
return result
def close(self, timeout: float = 3.0) -> None:
- """Close stdin and wait for the subprocess to exit, escalating to kill."""
+ """Close stdin and wait for the subprocess TREE to exit, escalating to kill.
+
+ Codex app-server owns stdio MCP descendants that may sit in their own process
+ groups (``setsid``). Once the root exits they reparent and a parent walk can no
+ longer find them, so descendants are snapshotted BEFORE the root is retired and
+ the proven identities (PID + create time) are swept afterwards."""
if self._closed:
return
self._closed = True
+ descendants = _snapshot_descendants(self._proc.pid)
with contextlib.suppress(Exception):
if self._proc.stdin and not self._proc.stdin.closed:
self._proc.stdin.close()
@@ -144,8 +180,10 @@ class CodexAppServerClient:
self._proc.wait(timeout=timeout)
except subprocess.TimeoutExpired:
with contextlib.suppress(Exception):
- self._proc.kill()
+ kill_process_tree(self._proc.pid)
self._proc.wait(timeout=1.0)
+ finally:
+ _reap_snapshotted(descendants)
def __enter__(self) -> "CodexAppServerClient":
return self
diff --git a/tests/agent/transports/test_codex_app_server_runtime.py b/tests/agent/transports/test_codex_app_server_runtime.py
index aa3199df94b..92a675ca25f 100644
--- a/tests/agent/transports/test_codex_app_server_runtime.py
+++ b/tests/agent/transports/test_codex_app_server_runtime.py
@@ -7,6 +7,8 @@ covered by a separate live test gated on `codex --version`.
from __future__ import annotations
+import sys
+
import pytest
from hermes_cli.runtime_provider import (
@@ -111,6 +113,87 @@ class TestCodexAppServerModule:
assert "-32600" in str(err)
+class TestCodexAppServerClose:
+ """Lifecycle tests for retiring the optional Codex app-server transport."""
+
+ @pytest.mark.live_system_guard_bypass
+ @pytest.mark.skipif(sys.platform == "win32", reason="start_new_session/setsid is POSIX-only")
+ def test_close_reaps_independent_descendant_process_group(self, tmp_path):
+ """A Codex-owned MCP child that calls setsid must not survive close().
+
+ Regression ported from openclaw/openclaw#126285: killing only the
+ app-server root lets independently grouped stdio MCP descendants live
+ past client retirement. The fake codex binary below spawns a long-lived
+ child in its own session, records its PID, and exits promptly on root
+ SIGTERM; close() must still reap the child.
+ """
+ import os
+ import stat
+ import sys
+ import time
+
+ import psutil
+
+ from agent.transports.codex_app_server import CodexAppServerClient
+
+ child_pid_file = tmp_path / "child.pid"
+ fake_codex = tmp_path / "fake_codex.py"
+ fake_codex.write_text(
+ f"#!{sys.executable}\n"
+ """
+import os
+import signal
+import subprocess
+import sys
+import time
+
+child = subprocess.Popen(
+ [sys.executable, "-c", "import time; time.sleep(60)"],
+ start_new_session=True,
+)
+with open(os.environ["CHILD_PID_FILE"], "w", encoding="utf-8") as fh:
+ fh.write(str(child.pid))
+
+def _exit(_sig, _frame):
+ sys.exit(0)
+
+signal.signal(signal.SIGTERM, _exit)
+while True:
+ time.sleep(1)
+""".lstrip()
+ )
+ fake_codex.chmod(fake_codex.stat().st_mode | stat.S_IXUSR)
+
+ client = CodexAppServerClient(
+ codex_bin=str(fake_codex),
+ env={"CHILD_PID_FILE": str(child_pid_file)},
+ )
+ try:
+ deadline = time.time() + 5
+ while not child_pid_file.exists() and time.time() < deadline:
+ time.sleep(0.05)
+ assert child_pid_file.exists(), "fake codex did not report child PID"
+ child_pid = int(child_pid_file.read_text())
+ assert psutil.pid_exists(child_pid)
+
+ client.close(timeout=1.0)
+
+ deadline = time.time() + 5
+ while psutil.pid_exists(child_pid) and time.time() < deadline:
+ time.sleep(0.05)
+ assert not psutil.pid_exists(child_pid), (
+ "Codex app-server close() left an independently grouped "
+ f"descendant alive: pid={child_pid}"
+ )
+ finally:
+ client.close(timeout=0.1)
+ if child_pid_file.exists():
+ try:
+ os.kill(int(child_pid_file.read_text()), 9)
+ except ProcessLookupError:
+ pass
+
+
class TestSpawnEnvIsolation:
"""The codex spawn must NOT rewrite HOME — codex's shell tool spawns
subprocesses (gh, git, npm, aws, gcloud, ...) that need to find their