Skip to content

The agent that grows with you

fix(gateway): exec quick commands stop their whole process tree on timeout or cancel

unsupportedpastels49df49a5e122
diff --git a/gateway/run_inbound_hooks.py b/gateway/run_inbound_hooks.py
index 553ab83cec1..a3f69aeacec 100644
--- a/gateway/run_inbound_hooks.py
+++ b/gateway/run_inbound_hooks.py
@@ -11,6 +11,9 @@ import asyncio
import contextlib
import dataclasses
import logging
+import os
+import signal
+import sys
from typing import Optional, Tuple
from agent.i18n import t
@@ -20,6 +23,25 @@ from gateway.session import SessionSource, build_session_context
# Log-record parity with the origin module.
logger = logging.getLogger("gateway.run")
+# Seconds a ``type: exec`` quick command may run before its whole process tree is killed.
+_EXEC_QUICK_COMMAND_TIMEOUT = 30
+
+
+async def _stop_exec_tree(proc) -> None:
+ """Kill an exec quick command's shell and everything it started, then reap the shell (bounded).
+
+ Killing only the shell leaves ``sleep 120 & wait``'s sleep running. ``kill_process_tree`` reaches
+ descendants (``taskkill /T`` on Windows); on POSIX the group the shell led also catches members
+ that already outlived it."""
+ if proc.returncode is None:
+ from agent.deadline import kill_process_tree
+ await asyncio.to_thread(kill_process_tree, proc.pid)
+ if sys.platform != "win32":
+ with contextlib.suppress(ProcessLookupError, PermissionError):
+ os.killpg(proc.pid, signal.SIGKILL) # windows-footgun: ok — POSIX-only branch; start_new_session made pid the pgid
+ with contextlib.suppress(TimeoutError):
+ await asyncio.wait_for(proc.wait(), timeout=5)
+
class GatewayInboundHooksMixin:
"""Hook, quick-command and plugin-command dispatch for ``GatewayInboundMixin``."""
@@ -141,7 +163,8 @@ class GatewayInboundHooksMixin:
async def _hm_run_exec_quick_command(self, command: str, exec_cmd: str, cwd: Optional[str] = None) -> str:
"""Run a ``type: exec`` quick command as a host shell of the gateway process: sanitized env
- (the gateway process has every API key in os.environ), redacted output, killed after 30 s.
+ (the gateway process has every API key in os.environ), redacted output, its process tree
+ killed after 30 s or when the awaiting task is cancelled (gateway shutdown).
``cwd`` is a local session's folder; None keeps the gateway's own (messaging)."""
proc = None
try:
@@ -149,19 +172,22 @@ class GatewayInboundHooksMixin:
proc = await asyncio.create_subprocess_shell(
exec_cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
env=build_subprocess_env(), cwd=cwd,
+ # Its own process group, so cleanup can reach what the shell started (POSIX;
+ # Windows ignores it and _stop_exec_tree walks the tree with taskkill /T).
+ start_new_session=True,
)
- stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=30)
+ stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=_EXEC_QUICK_COMMAND_TIMEOUT)
output = (stdout or stderr).decode().strip()
if output:
from agent.redact import redact_sensitive_text
output = redact_sensitive_text(output)
return output or t("gateway.quick_command.no_output")
- except TimeoutError:
- if proc is not None and proc.returncode is None:
- with contextlib.suppress(ProcessLookupError):
- proc.kill()
- with contextlib.suppress(TimeoutError):
- await asyncio.wait_for(proc.wait(), timeout=5)
+ except (TimeoutError, asyncio.CancelledError) as stopped:
+ # One cleanup for both: a cancelled await must not leave the command running either.
+ if proc is not None:
+ await asyncio.shield(_stop_exec_tree(proc))
+ if isinstance(stopped, asyncio.CancelledError):
+ raise
return t("gateway.quick_command.timed_out")
except Exception as e: # health: allow BLE001 -- moved unchanged from run_inbound.py (main has the same handler): an operator quick command's failure is its reply
return t("gateway.quick_command.error", error=e)
diff --git a/tests/gateway/test_exec_quick_command_tree.py b/tests/gateway/test_exec_quick_command_tree.py
new file mode 100644
index 00000000000..fc3e0907e6a
--- /dev/null
+++ b/tests/gateway/test_exec_quick_command_tree.py
@@ -0,0 +1,53 @@
+"""A ``type: exec`` quick command that times out or is cancelled leaves nothing running.
+
+Killing only the shell left ``sleep 120 & wait``'s sleep alive, and a cancelled await (gateway
+shutdown on the WebSocket path) skipped cleanup entirely.
+"""
+import asyncio
+from pathlib import Path
+
+import psutil
+import pytest
+
+from gateway import run_inbound_hooks
+from gateway.run_inbound_hooks import GatewayInboundHooksMixin
+from tests.waiting import async_wait_until
+
+_TREE = 'echo $$ > shell.pid; sleep 120 & echo $! > child.pid; wait'
+
+
+def _alive(pid):
+ try:
+ return psutil.Process(pid).status() != psutil.STATUS_ZOMBIE
+ except psutil.NoSuchProcess:
+ return False
+
+
+def _pid(path: Path):
+ text = path.read_text().strip() if path.exists() else ''
+ return int(text) if text else None
+
+
+async def test_timed_out_exec_command_kills_its_background_child(tmp_path, monkeypatch):
+ monkeypatch.setattr(run_inbound_hooks, '_EXEC_QUICK_COMMAND_TIMEOUT', 2)
+ reply = await GatewayInboundHooksMixin()._hm_run_exec_quick_command('probe', _TREE, cwd=str(tmp_path))
+ assert reply == run_inbound_hooks.t('gateway.quick_command.timed_out')
+ child = _pid(tmp_path / 'child.pid')
+ assert child is not None
+ await async_wait_until(lambda: not _alive(child), timeout=10, what='the backgrounded sleep to stop')
+
+
+async def test_cancelled_exec_command_kills_shell_and_child(tmp_path):
+ task = asyncio.create_task(
+ GatewayInboundHooksMixin()._hm_run_exec_quick_command('probe', _TREE, cwd=str(tmp_path)))
+ child = await async_wait_until(lambda: _pid(tmp_path / 'child.pid'), timeout=10, what='the child pid')
+ shell = _pid(tmp_path / 'shell.pid')
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ await async_wait_until(lambda: not _alive(shell) and not _alive(child), timeout=10,
+ what='the shell and its child to stop')