Skip to content

The agent that grows with you

fix(tui-gateway): exiting mid-tool no longer orphans the foreground command's process tree

teknium1537ce77f5288
diff --git a/tests/tools/test_local_interrupt_cleanup.py b/tests/tools/test_local_interrupt_cleanup.py
index 74b1d55fd33..c81aa3a6ee6 100644
--- a/tests/tools/test_local_interrupt_cleanup.py
+++ b/tests/tools/test_local_interrupt_cleanup.py
@@ -11,6 +11,7 @@ to the python process, sleep 300 survived with PPID=1 for the full 300 s
because _wait_for_process never got to call _kill_process before python
died. See commit message for full context.
"""
+import contextlib
import os
import signal
import subprocess
@@ -200,3 +201,44 @@ def test_wait_for_process_kills_subprocess_on_keyboardinterrupt():
env.cleanup()
except Exception:
pass
+
+
+def _descendant_running(marker: str):
+ import psutil
+ for p in psutil.Process(os.getpid()).children(recursive=True):
+ try:
+ if marker in " ".join(p.cmdline()):
+ return p
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
+ continue
+ return None
+
+
+def test_exit_cleanup_kills_foreground_command_still_running(monkeypatch):
+ """The host-exit funnel (CLI, one-shot, messaging gateway, serve atexit) must take an
+ in-flight foreground command's process group with it: it runs in its own session, so
+ the host exiting mid-command would otherwise orphan it to init."""
+ from tools import terminal_tool_lifecycle
+
+ monkeypatch.setattr(terminal_tool_lifecycle, "_scratch_paths", lambda: [])
+ env = LocalEnvironment(cwd="/tmp")
+ result: dict = {}
+ t = threading.Thread(target=lambda: result.update(env.execute("sleep 3517", timeout=600)), daemon=True)
+ try:
+ t.start()
+ deadline = time.monotonic() + 20.0
+ while (proc := _descendant_running("sleep 3517")) is None and time.monotonic() < deadline:
+ time.sleep(0.05)
+ assert proc is not None, "test setup: foreground sleep never started"
+ pgid = os.getpgid(proc.pid)
+
+ terminal_tool_lifecycle.cleanup_all_environments()
+
+ assert _wait_for_pgid_exit(pgid, timeout=15.0), (
+ f"foreground command survived exit cleanup:\n{_process_group_snapshot(pgid)}")
+ t.join(timeout=15.0)
+ assert not t.is_alive() and result.get("returncode") not in (None, 0), result
+ finally:
+ with contextlib.suppress(Exception):
+ os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
+ env.cleanup()
diff --git a/tests/tui_gateway/test_serve_exit_flush.py b/tests/tui_gateway/test_serve_exit_flush.py
index de69e545977..2a5e520d1e3 100644
--- a/tests/tui_gateway/test_serve_exit_flush.py
+++ b/tests/tui_gateway/test_serve_exit_flush.py
@@ -157,6 +157,65 @@ def test_shutdown_sessions_flushes_before_teardown(monkeypatch):
assert "close:sess-order" in order
+def test_shutdown_mid_tool_kills_the_command_and_keeps_its_result(monkeypatch):
+ """SIGTERM/EOF while a turn's foreground terminal command runs: the shutdown chokepoint must
+ end the command's process group (it would outlive the gateway, reparented to init) and the
+ turn's tool result must be in the transcript before per-session teardown persists it."""
+ import threading
+
+ import psutil
+
+ from tools.environments.local import LocalEnvironment
+ from tools.interrupt import set_interrupt
+
+ env = LocalEnvironment(cwd=os.getcwd())
+ messages = [{"role": "assistant", "tool_calls": [{"id": "call-1"}]}]
+
+ def turn():
+ out = env.execute("sleep 3518", timeout=600)
+ time.sleep(0.2) # the agent's post-tool bookkeeping before the result lands in history
+ messages.append({"role": "tool", "tool_call_id": "call-1", "content": out["output"]})
+
+ run_thread = threading.Thread(target=turn, daemon=True)
+
+ class _Agent:
+ _session_messages = messages
+
+ def interrupt(self, message=None): # the real agent fans this out to its tool threads
+ set_interrupt(True, thread_id=run_thread.ident)
+
+ run_thread.start()
+ deadline = time.monotonic() + 20.0
+ sleeper = None
+ while sleeper is None and time.monotonic() < deadline:
+ sleeper = next((p for p in psutil.Process().children(recursive=True)
+ if p.name() == "sleep" and "3518" in " ".join(p.cmdline())), None)
+ time.sleep(0.05)
+ assert sleeper is not None, "test setup: foreground sleep never started"
+
+ at_teardown: list = []
+ monkeypatch.setattr(server, "_release_gateway_wake_owner", lambda: None, raising=False)
+ monkeypatch.setattr(server, "_flush_sessions_before_exit", lambda budget_s=None: 0)
+ monkeypatch.setattr(server, "_close_session_by_id", lambda sid, **kw: at_teardown.append(list(messages)))
+ session = {"agent": _Agent(), "session_key": "sess-mid-tool", "running": True,
+ "_run_thread": run_thread, "history_lock": threading.RLock()}
+ with server._sessions_lock:
+ server._sessions["sess-mid-tool"] = session
+ try:
+ server._shutdown_sessions()
+ _gone, alive = psutil.wait_procs([sleeper], timeout=15.0)
+ assert not alive, "foreground command survived gateway shutdown"
+ assert at_teardown and at_teardown[0][-1].get("tool_call_id") == "call-1", (
+ f"teardown persisted a tool_call with no result: {at_teardown}")
+ finally:
+ with server._sessions_lock:
+ server._sessions.pop("sess-mid-tool", None)
+ if sleeper.is_running():
+ sleeper.kill()
+ set_interrupt(False, thread_id=run_thread.ident)
+ env.cleanup()
+
+
def test_periodic_flush_respects_interval_with_fake_clock(
registered_session, monkeypatch
):
diff --git a/tools/environments/base.py b/tools/environments/base.py
index f3e3627c6a1..c68c542b353 100644
--- a/tools/environments/base.py
+++ b/tools/environments/base.py
@@ -52,6 +52,24 @@ if _DEBUG_INTERRUPT:
# long-running _wait_for_process loops can report liveness to the gateway.
_activity_callback_local = threading.local()
+# Foreground commands in flight in THIS process, across every environment. Each runs in its
+# own session/process group, so a host that exits mid-command (TUI client gone, SIGTERM) would
+# orphan the whole tree; the process-exit funnel ``cleanup_all_environments`` kills them.
+_live_foreground: dict[int, tuple["BaseEnvironment", "ProcessHandle"]] = {}
+_live_foreground_lock = threading.Lock()
+
+
+def kill_live_foreground_processes() -> int:
+ """Kill every in-flight foreground command's process tree; returns how many were signalled."""
+ with _live_foreground_lock:
+ live = list(_live_foreground.values())
+ for env, proc in live:
+ try:
+ env._kill_process(proc)
+ except Exception:
+ logger.debug("exit-time kill of a foreground command failed", exc_info=True)
+ return len(live)
+
class FileFetchError(RuntimeError):
"""A file could not be extracted from the backend filesystem."""
@@ -542,10 +560,16 @@ class BaseEnvironment(ABC):
set_activity_callback(parent_activity_cb)
spawned = self._run_bash(wrapped, login=login, timeout=effective_timeout, stdin_data=effective_stdin)
proc_holder.append(spawned)
- return self._wait_for_process(
- spawned, timeout=effective_timeout, bounded_capture=bounded_capture,
- watch_interrupt_tid=parent_tid,
- **({"yield_handler": yield_handler} if yield_handler is not None else {}))
+ with _live_foreground_lock:
+ _live_foreground[id(spawned)] = (self, spawned)
+ try:
+ return self._wait_for_process(
+ spawned, timeout=effective_timeout, bounded_capture=bounded_capture,
+ watch_interrupt_tid=parent_tid,
+ **({"yield_handler": yield_handler} if yield_handler is not None else {}))
+ finally:
+ with _live_foreground_lock:
+ _live_foreground.pop(id(spawned), None)
def _on_timeout() -> None:
if proc_holder:
diff --git a/tools/terminal_tool_lifecycle.py b/tools/terminal_tool_lifecycle.py
index ba2c2cc9e12..74f48b73e91 100644
--- a/tools/terminal_tool_lifecycle.py
+++ b/tools/terminal_tool_lifecycle.py
@@ -263,8 +263,11 @@ def is_persistent_env(task_id: str) -> bool:
def cleanup_all_environments():
- """Clean up ALL active environments. Use with caution."""
+ """Clean up ALL active environments (process exit). Use with caution."""
+ from tools.environments.base import kill_live_foreground_processes
from tools.terminal_tool import _active_environments
+ # A command still running when the host exits would outlive it in its own process group.
+ kill_live_foreground_processes()
cleaned = 0
for task_id in list(_active_environments.keys()):
try:
diff --git a/tui_gateway/compute_host.py b/tui_gateway/compute_host.py
index 8e7c233cbe9..201fff53031 100644
--- a/tui_gateway/compute_host.py
+++ b/tui_gateway/compute_host.py
@@ -96,6 +96,11 @@ class ComputeHost:
def close(self) -> None:
self._closed.set()
self._executor.shutdown(wait=False, cancel_futures=True)
+ # Every caller hard-exits next (os._exit skips atexit): a foreground command still
+ # running in its own process group would outlive the host.
+ with contextlib.suppress(Exception):
+ from tools.environments.base import kill_live_foreground_processes
+ kill_live_foreground_processes()
def shutdown(self, *, reason: str = "shutdown", wait: float = 10.0) -> None:
"""Drain in-flight turns, then finalize every session.
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index d292c8a7d59..b232f7343fe 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -346,7 +346,7 @@ def _load_interim_assistant_messages() -> bool:
def _shutdown_sessions() -> None:
# Durable-first: flush transcripts (bounded budget) BEFORE the slow teardown so a supervisor SIGKILL can't lose them.
- for step in (_flush_sessions_before_exit, _release_gateway_wake_owner):
+ for step in (_flush_sessions_before_exit, _release_gateway_wake_owner, _stop_turns_before_exit):
with contextlib.suppress(Exception):
step()
with _sessions_lock:
diff --git a/tui_gateway/session_reaper.py b/tui_gateway/session_reaper.py
index 6c24492960a..43e7b679ef0 100644
--- a/tui_gateway/session_reaper.py
+++ b/tui_gateway/session_reaper.py
@@ -113,6 +113,29 @@ def _flush_sessions_before_exit(budget_s: float | None = None) -> int:
return result["flushed"]
+# Bounded wait for interrupted turns on the way out; the SIGTERM path hard-exits after a ~1s grace.
+_EXIT_TURN_SETTLE_S = 0.5
+
+
+def _stop_turns_before_exit(budget_s: float | None = None) -> None:
+ """Interrupt every in-flight turn and give it ``budget_s`` to settle, so a running tool call ends
+ with a result the teardown's final persist records, then kill any foreground command still alive:
+ it runs in its own process group and would otherwise outlive the gateway, reparented to init."""
+ with _sessions_lock:
+ running = [(sid, s) for sid, s in _sessions.items() if s.get("running")]
+ threads = []
+ for sid, session in running:
+ with contextlib.suppress(Exception):
+ _interrupt_session_turn(sid, session)
+ if (t := session.get("_run_thread")) is not None and t is not threading.current_thread():
+ threads.append(t)
+ deadline = time.monotonic() + (_EXIT_TURN_SETTLE_S if budget_s is None else max(0.0, budget_s))
+ for t in threads:
+ t.join(max(0.0, deadline - time.monotonic()))
+ from tools.environments.base import kill_live_foreground_processes
+ kill_live_foreground_processes()
+
+
_exit_flush_prev_handlers: dict[int, Any] = {}
_exit_flush_handlers_installed = False
@@ -122,6 +145,10 @@ def _handle_exit_flush_signal(signum, frame) -> None:
handler, or the default disposition) — this only *prepends* a bounded flush."""
with contextlib.suppress(Exception):
_flush_sessions_before_exit()
+ # The group signal that stopped us never reaches a command in its own session: reap it now,
+ # before a supervisor's SIGKILL can cut the graceful shutdown (and its atexit) short.
+ with contextlib.suppress(Exception):
+ _stop_turns_before_exit()
import signal as _signal
prev = _exit_flush_prev_handlers.get(signum)
if callable(prev):