The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(mcp): re-validate PGID ownership before killing orphaned process groups
valentt3050629bb37f
diff --git a/tests/tools/test_mcp_stability.py b/tests/tools/test_mcp_stability.pyindex 4cbc3f22f21..a7bbaae5cc3 100644--- a/tests/tools/test_mcp_stability.py+++ b/tests/tools/test_mcp_stability.py@@ -212,13 +212,87 @@ class TestStdioPgroupReaping:"""_kill_orphaned_mcp_children reaps via killpg when a pgid is tracked."""def _reset_state(self):- from tools.mcp_tool_lifecycle import _orphan_stdio_pid_servers, _orphan_stdio_pids, _stdio_pgids, _stdio_pids+ from tools.mcp_tool_lifecycle import (+ _orphan_stdio_pid_servers, _orphan_stdio_pids, _stdio_pgids, _stdio_pids, _stdio_starttimes)from tools.mcp_tool import _lockwith _lock:_stdio_pids.clear()_orphan_stdio_pids.clear()_orphan_stdio_pid_servers.clear()_stdio_pgids.clear()+ _stdio_starttimes.clear()++ def test_kill_orphaned_skips_recycled_pid(self):+ """PID-reuse guard (#43044): a recycled PID (start-time changed) is NOT signalled.++ Regression test: once an MCP child exits and is reaped, the kernel can+ recycle its PID/PGID onto an unrelated process group. The sweep must+ not signal the stale number, or it kills a stranger (observed: a desktop+ browser whose session leader reused a dead MCP child's PID).+ """+ from tools.mcp_tool_lifecycle import (+ _kill_orphaned_mcp_children, _orphan_stdio_pids, _stdio_pgids, _stdio_starttimes)+ from tools.mcp_tool import _lock++ self._reset_state()+ fake_pid = 454545+ with _lock:+ _orphan_stdio_pids.add(fake_pid)+ _stdio_pgids[fake_pid] = fake_pid+ _stdio_starttimes[fake_pid] = 111111 # recorded at spawn++ # Current start time differs -> PID was recycled -> guard must skip.+ with patch("tools.mcp_tool_lifecycle._leader_start_time", return_value=222222), \+ patch("tools.mcp_tool.os.killpg") as mock_killpg, \+ patch("tools.mcp_tool.os.kill") as mock_kill, \+ patch("gateway.status._pid_exists", return_value=True), \+ patch("tools.mcp_tool.time.sleep"):+ _kill_orphaned_mcp_children()++ mock_killpg.assert_not_called()+ mock_kill.assert_not_called()++ def test_kill_orphaned_signals_when_start_time_matches(self):+ """The orphan IS signalled when its leader start-time still matches."""+ from tools.mcp_tool_lifecycle import (+ _kill_orphaned_mcp_children, _orphan_stdio_pids, _stdio_pgids, _stdio_starttimes)+ from tools.mcp_tool import _lock++ self._reset_state()+ fake_pid = 464646+ with _lock:+ _orphan_stdio_pids.add(fake_pid)+ _stdio_pgids[fake_pid] = fake_pid+ _stdio_starttimes[fake_pid] = 333333++ with patch("tools.mcp_tool_lifecycle._leader_start_time", return_value=333333), \+ patch("tools.mcp_tool.os.killpg") as mock_killpg, \+ patch("gateway.status._pid_exists", return_value=False), \+ patch("tools.mcp_tool.time.sleep"):+ _kill_orphaned_mcp_children()++ mock_killpg.assert_any_call(fake_pid, signal.SIGTERM)++ def test_kill_orphaned_without_baseline_keeps_legacy_behaviour(self):+ """No recorded start time (macOS / capture raced exit) -> best-effort killpg."""+ from tools.mcp_tool_lifecycle import (+ _kill_orphaned_mcp_children, _orphan_stdio_pids, _stdio_pgids, _stdio_starttimes)+ from tools.mcp_tool import _lock++ self._reset_state()+ fake_pid = 474747+ with _lock:+ _orphan_stdio_pids.add(fake_pid)+ _stdio_pgids[fake_pid] = fake_pid+ # No _stdio_starttimes entry.++ with patch("tools.mcp_tool.os.killpg") as mock_killpg, \+ patch("gateway.status._pid_exists", return_value=False), \+ patch("tools.mcp_tool.time.sleep"):+ _kill_orphaned_mcp_children()++ mock_killpg.assert_any_call(fake_pid, signal.SIGTERM)+def test_killpg_used_when_pgid_tracked(self, monkeypatch):"""SIGTERM and SIGKILL route through killpg when pgid is known."""diff --git a/tools/environments/local.py b/tools/environments/local.pyindex 792a8358b9c..00e38941a3e 100644--- a/tools/environments/local.py+++ b/tools/environments/local.py@@ -840,16 +840,50 @@ def _sweep_escaped_descendants(descendants: list, pgid: int) -> None:continue+def _leader_is_ours(pgid, expected_start) -> bool:+ """The setsid group leader's PID == its PGID. Confirm it is still the process we+ spawned before signalling the whole group, so a recycled PID/PGID can never take+ down an unrelated process group (#43044). When no start-time baseline was captured+ (e.g. macOS, which has no /proc), fall back to the legacy best-effort behaviour+ rather than refusing to kill."""+ if pgid is None:+ return False+ if expected_start is None:+ return True+ from gateway.status import get_process_start_time+ try:+ return get_process_start_time(pgid) == expected_start+ except Exception: # noqa: BLE001 — the guard must never break signalling+ return True++def _kill_process_group_posix(proc) -> None:"""TERM the group, wait, KILL, then sweep setsid escapees. Descendants aresnapshotted BEFORE the first signal — once the wrapper dies they reparent toinit — and we wait on the group, not the wrapper, which can exit before- grandchildren under load. POSIX-only (_IS_WINDOWS handled by the caller)."""+ grandchildren under load. POSIX-only (_IS_WINDOWS handled by the caller).+ PID-reuse guard (#43044): the group is only signalled while its leader's start+ time still matches the spawn-time baseline — a recycled PGID is never killed."""+ expected_start = getattr(proc, "_hermes_pgid_start", None)try:pgid = os.getpgid(proc.pid)except ProcessLookupError:if (pgid := getattr(proc, "_hermes_pgid", None)) is None:raise+ if not _leader_is_ours(pgid, expected_start):+ # Leader exited and its PID/PGID may have been recycled onto an unrelated+ # process group; signalling the stale number is unsafe. Bail out — a rare+ # orphaned grandchild may leak, which is strictly preferable to killing a+ # stranger. Sweep the snapshotted descendants by PID (identity-checked)+ # so we still reach escapees that are verifiably ours.+ descendants = []+ try:+ import psutil+ descendants = psutil.Process(proc.pid).children(recursive=True)+ except Exception:+ pass+ _sweep_escaped_descendants(descendants, pgid)+ returntry: # psutil children snapshot; empty on any failure (must never break the kill)import psutildescendants = psutil.Process(proc.pid).children(recursive=True)@@ -863,6 +897,10 @@ def _kill_process_group_posix(proc) -> None:try:os.killpg(pgid, signal.SIGTERM) # windows-footgun: ok — POSIX only (see _IS_WINDOWS gate in caller)if not _wait_for_group_exit(proc, pgid, 1.0):+ if not _leader_is_ours(pgid, expected_start):+ # Leader exited during the grace window; do not escalate to+ # SIGKILL on a possibly-recycled PGID.+ returnos.killpg(pgid, signal.SIGKILL) # windows-footgun: ok — POSIX only (see _IS_WINDOWS gate in caller)_wait_for_group_exit(proc, pgid, 2.0)with contextlib.suppress(subprocess.TimeoutExpired, OSError):@@ -1007,6 +1045,10 @@ class LocalEnvironment(BaseEnvironment):if not _IS_WINDOWS:with contextlib.suppress(ProcessLookupError):proc._hermes_pgid = os.getpgid(proc.pid)+ # Record the group leader's start time so _kill_process can+ # detect PID/PGID recycling before signalling the group (#43044).+ from gateway.status import get_process_start_time+ proc._hermes_pgid_start = get_process_start_time(proc.pid)if stdin_data is not None:_pipe_stdin(proc, stdin_data)return proc@@ -1025,7 +1067,11 @@ class LocalEnvironment(BaseEnvironment):return self._kill_process(proc)with contextlib.suppress(OSError):pgid = getattr(proc, "_hermes_pgid", None) or os.getpgid(proc.pid)- if pgid != os.getpgrp(): # never our own group (see _kill_process_group_posix)+ # PID-reuse guard (#43044): never SIGKILL a group whose leader's start time+ # no longer matches the spawn-time baseline — the PGID may have been recycled+ # onto an unrelated process group. Without a baseline (macOS, no /proc) keep+ # the legacy best-effort behaviour.+ if pgid != os.getpgrp() and _leader_is_ours(pgid, getattr(proc, "_hermes_pgid_start", None)):os.killpg(pgid, signal.SIGKILL) # windows-footgun: ok — POSIX only (_IS_WINDOWS returned above)with contextlib.suppress(OSError):proc.kill()diff --git a/tools/mcp_tool_lifecycle.py b/tools/mcp_tool_lifecycle.pyindex a755658ff53..219033172aa 100644--- a/tools/mcp_tool_lifecycle.py+++ b/tools/mcp_tool_lifecycle.py@@ -22,6 +22,25 @@ _orphan_stdio_pid_servers: Dict[int, str] = {}# grandchildren keep that PGID after the direct child exits, so killpg still reaches them.# Separate from _stdio_pids so the PGID survives the child's removal. Empty on Windows._stdio_pgids: Dict[int, int] = {}+# Spawn-time start ticks (/proc/<pid>/stat field 22) of each stdio child's pgroup leader,+# captured alongside the PGID. PIDs/PGIDs are recycled by the kernel once the original+# process exits and is reaped, so a long-lived tracker holding a bare PGID is unsafe: by+# the time a sweep runs, that number may name an unrelated process group (observed in the+# wild: a desktop browser whose session leader happened to reuse a dead MCP child's PID —+# #43044). We re-check the leader's start time before signalling so a recycled PGID is+# never killed. None entries are dropped: platforms without /proc (macOS) have no baseline+# and keep the legacy best-effort behaviour.+_stdio_starttimes: Dict[int, int] = {} # pid -> leader start ticks+++def _leader_start_time(pid: int) -> Optional[int]:+ """``/proc``-backed start time of the pgroup leader (PGID == leader PID on setsid spawn);+ ``None`` on platforms without /proc (macOS/Windows) or for an already-reaped PID."""+ from gateway.status import get_process_start_time+ try:+ return get_process_start_time(pid)+ except Exception: # noqa: BLE001 — the guard must never break signalling+ return Nonedef _snapshot_child_pids() -> set:@@ -219,7 +238,7 @@ def shutdown_mcp_servers(*, scope: Optional[str] = None, names: Optional[set] =_close_mcp_stderr_logs(scope=scope)-def _take_reapable_pids(include_active: bool, server_name: Optional[str]) -> tuple[Dict[int, str], Dict[int, int]]:+def _take_reapable_pids(include_active: bool, server_name: Optional[str]) -> tuple[Dict[int, str], Dict[int, int], Dict[int, int]]:"""Pop the PIDs to reap (and their spawn-time pgids) out of the ledgers under the lock, soa future spawn can't collide with stale state. Returns ``(pid -> owner, pid -> pgid)``."""def _owned(entries: Dict[int, str]) -> Dict[int, str]:@@ -236,12 +255,26 @@ def _take_reapable_pids(include_active: bool, server_name: Optional[str]) -> tupfor pid in active:_stdio_pids.pop(pid, None)pgids = {pid: _stdio_pgids.pop(pid) for pid in pids if pid in _stdio_pgids}- return pids, pgids+ starts = {pid: _stdio_starttimes.pop(pid) for pid in pids if pid in _stdio_starttimes}+ return pids, pgids, starts-def _signal_mcp_process(pid: int, sig: int, server_name: str, pgid: Optional[int], my_pgid: Optional[int]) -> None:+def _signal_mcp_process(pid: int, sig: int, server_name: str, pgid: Optional[int], my_pgid: Optional[int],+ expected_start: Optional[int] = None) -> None:"""SIGTERM/SIGKILL via the spawn-time pgroup on POSIX (reaches reparented grandchildren),- falling back to a per-pid signal."""+ falling back to a per-pid signal.++ PID-reuse guard (#43044): only signal if ``pid`` still names the process we spawned. Once+ an MCP child exits and is reaped the kernel may recycle its PID/PGID onto an unrelated+ process group; signalling the stale number would kill a stranger (observed: a recycled+ PGID landing on a desktop browser's session leader). When ``expected_start`` was captured+ at spawn and no longer matches, skip entirely. Without a baseline (no /proc — macOS — or+ the capture raced the child's exit) fall through to the legacy best-effort path."""+ if expected_start is not None and _leader_start_time(pid) != expected_start:+ logger.debug(+ "Skip signalling MCP pid %d (%s): start-time mismatch — PID was recycled; "+ "refusing to kill an unrelated process group.", pid, server_name)+ returnkillpg = getattr(os, "killpg", None)if pgid is not None and killpg is not None:if my_pgid is not None and pgid == my_pgid:@@ -305,7 +338,7 @@ def _kill_orphaned_mcp_children(include_active: bool = False, server_name: Optiofinal shutdown after the MCP loop has stopped. ``server_name`` limits the sweep to oneserver (stdio reconnects cleaning up their old transport)."""import signal as _signal- pids, pgids = _take_reapable_pids(include_active, server_name)+ pids, pgids, starts = _take_reapable_pids(include_active, server_name)if not pids: # skip the 2s sleep every MCP-free shutdown would otherwise payreturn@@ -315,14 +348,14 @@ def _kill_orphaned_mcp_children(include_active: bool = False, server_name: Optiomy_pgid = None # Windows or restricted environmentfor pid, owner in pids.items():- _signal_mcp_process(pid, _signal.SIGTERM, owner, pgids.get(pid), my_pgid)+ _signal_mcp_process(pid, _signal.SIGTERM, owner, pgids.get(pid), my_pgid, starts.get(pid))logger.debug("Sent SIGTERM to orphaned MCP process %d (%s)", pid, owner)time.sleep(2)sigkill = getattr(_signal, "SIGKILL", _signal.SIGTERM)from gateway.status import _pid_exists # ``os.kill(pid, 0)`` is NOT a no-op on Windowsfor pid, owner in pids.items():if _pid_exists(pid): # survived SIGTERM- _signal_mcp_process(pid, sigkill, owner, pgids.get(pid), my_pgid)+ _signal_mcp_process(pid, sigkill, owner, pgids.get(pid), my_pgid, starts.get(pid))logger.warning("Force-killed MCP process %d (%s) after SIGTERM timeout", pid, owner)# These groups are reaped. Release them last, so a crash partway through the SIGTERM/SIGKILL# dance still leaves the supervisor holding them.diff --git a/tools/mcp_tool_transport.py b/tools/mcp_tool_transport.pyindex cd69f548a6a..47ac05b23c2 100644--- a/tools/mcp_tool_transport.py+++ b/tools/mcp_tool_transport.py@@ -13,7 +13,7 @@ from utils import normalize_proxy_urlfrom agent.proxy_bypass import is_loopback_host, should_bypass_proxyfrom agent import runtime_cwd as _runtime_cwdfrom tools.mcp_tool_errors import NonMcpEndpointError, _apply_identity_header, _describe_http_failure, _handshake_answered_with_unsupported_version, _handshake_rejected_as_modern, _is_streamable_http_rejection, _make_http_rejection_recorder, _make_mcp_body_cap_transport, _make_redirect_header_stripper, _resolve_client_cert, _unwrap_exception_group-from tools.mcp_tool_lifecycle import _filter_mcp_children, _orphan_stdio_pid_servers, _orphan_stdio_pids, _stdio_pgids, _stdio_pids+from tools.mcp_tool_lifecycle import _filter_mcp_children, _leader_start_time, _orphan_stdio_pid_servers, _orphan_stdio_pids, _stdio_pgids, _stdio_pids, _stdio_starttimesfrom tools.mcp_tool_common import _corefrom tools.mcp_tool_node_abi import node_abi_errorfrom tools import mcp_tool_config as _config@@ -295,6 +295,7 @@ class MCPServerTransportMixin:"""Ledger the freshly spawned stdio children (pids, pgids, machine spawn ledger). pgids arecaptured while alive (getpgid fails after exit; the sweep needs them for reparented descendants)."""new_pgids: Dict[int, int] = {}+ new_starts: Dict[int, int] = {}for pid in new_pids:try:new_pgids[pid] = os.getpgid(pid)@@ -306,9 +307,15 @@ class MCPServerTransportMixin:new_pgids[pid] = pidexcept (AttributeError, OSError): # Windows (os.getpgid is POSIX-only)pass+ # Record the leader's start time so a later sweep can detect PID/PGID+ # recycling before signalling (see _stdio_starttimes, #43044).+ start = _leader_start_time(pid)+ if start is not None:+ new_starts[pid] = startwith _core._lock:_stdio_pids.update(dict.fromkeys(new_pids, self.name))_stdio_pgids.update(new_pgids)+ _stdio_starttimes.update(new_starts)# Machine spawn ledger (startup sweeps reap orphans after an unclean exit); best-effort.for _pid in new_pids:try:@@ -341,6 +348,7 @@ class MCPServerTransportMixin:dropped = _stdio_pgids.pop(pid, None)if dropped is not None:released_pgids.append(dropped)+ _stdio_starttimes.pop(pid, None)_core._update_death_supervisor("unregister", released_pgids)async def _run_stdio(self, config: dict):