The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(process): verify tree death before writing killed receipt
Yagna Vudathu9a46df0a21c9
diff --git a/tests/tools/test_kill_verify_tree_death.py b/tests/tools/test_kill_verify_tree_death.pynew file mode 100644index 00000000000..85cb918ffc3--- /dev/null+++ b/tests/tools/test_kill_verify_tree_death.py@@ -0,0 +1,100 @@+"""Post-kill tree-death verification (#115490).++A kill that leaves survivors must NOT write a killed receipt or prune the+session: the live tree would become unmanageable (missing from the+background list while still holding resources).+"""++import time+from unittest.mock import MagicMock, patch++from tools.process_registry import ProcessRegistry, ProcessSession+++def _live_session(sid="proc_killverify1", pid=424242, start=777001):+ s = ProcessSession(+ id=sid, command="sleep 999", task_id="t1", started_at=time.time(),+ pid=pid, pid_scope="host", host_start_time=start,+ )+ proc = MagicMock()+ proc.pid = pid+ s.process = proc+ return s+++def _paused_registry_calls():+ """Neutralize tree-kill + checkpoint side effects; return the mocks."""+ t = patch.object(ProcessRegistry, "_terminate_host_pid", return_value=None).start()+ c = patch.object(ProcessRegistry, "_write_checkpoint", return_value=None).start()+ s = patch("tools.process_registry.save_completed_result").start()+ return t, c, s+++def test_kill_with_surviving_root_keeps_session_running():+ """Root ignores the kill -> no killed receipt, session stays running."""+ reg = ProcessRegistry()+ s = _live_session()+ s.process.poll.return_value = None # Popen child still alive+ reg._running[s.id] = s+ try:+ _, _, save = _paused_registry_calls()+ with patch.object(ProcessRegistry, "_host_pid_is_ours", return_value=True), \+ patch("psutil.Process", side_effect=Exception("gone")):+ result = reg.kill_process(s.id)+ finally:+ patch.stopall()+ assert result["status"] != "killed", result+ assert result.get("process_running") is True+ assert result.get("survivors") == [424242], result+ assert s.exited is False+ assert s.completion_reason != "killed"+ assert s.id in reg._running+ assert s.id not in reg._finished+ save.assert_not_called()+++def test_kill_with_surviving_descendant_keeps_session_running():+ """Live root with a live owned descendant -> session stays running."""+ reg = ProcessRegistry()+ s = _live_session(sid="proc_killverify2")+ s.process.poll.return_value = None # root still alive+ reg._running[s.id] = s+ kid = MagicMock()+ kid.pid = 424243+ kid.is_running.return_value = True+ kid.status.return_value = "running"+ parent = MagicMock()+ parent.children.return_value = [kid]+ try:+ _, _, save = _paused_registry_calls()+ with patch.object(ProcessRegistry, "_host_pid_is_ours", return_value=True), \+ patch("psutil.Process", return_value=parent):+ result = reg.kill_process(s.id)+ finally:+ patch.stopall()+ assert result["status"] != "killed", result+ assert set(result.get("survivors", [])) == {424242, 424243}, result+ assert s.exited is False+ assert s.id in reg._running+ assert s.id not in reg._finished+ save.assert_not_called()+++def test_kill_with_dead_tree_still_reports_killed():+ """Full tree death preserves the existing killed contract."""+ reg = ProcessRegistry()+ s = _live_session(sid="proc_killverify3")+ s.process.poll.return_value = -15+ reg._running[s.id] = s+ try:+ _, _, save = _paused_registry_calls()+ with patch.object(ProcessRegistry, "_host_pid_is_ours", return_value=False), \+ patch("psutil.Process", side_effect=Exception("gone")):+ result = reg.kill_process(s.id)+ finally:+ patch.stopall()+ assert result["status"] == "killed", result+ assert s.exited is True+ assert s.completion_reason == "killed"+ assert s.id not in reg._running+ assert s.id in reg._finisheddiff --git a/tests/tools/test_process_registry.py b/tests/tools/test_process_registry.pyindex 0548586a49a..7aae151fbfa 100644--- a/tests/tools/test_process_registry.py+++ b/tests/tools/test_process_registry.py@@ -1416,6 +1416,10 @@ class TestKillProcess:registry._running[s.id] = sterminate_calls = []+ # Post-#115490 kill_process verifies tree death after signalling: the+ # fake terminate must actually kill, or the live fake reads as a+ # survivor and the kill correctly reports incomplete.+ kill_state = {"alive": True}class FakeProcess:def __init__(self, pid):@@ -1424,6 +1428,7 @@ class TestKillProcess:return []def terminate(self):terminate_calls.append(("terminate", self.pid))+ kill_state["alive"] = Falseimport psutil as _psutil@@ -1435,7 +1440,7 @@ class TestKillProcess:# touches ``os.kill`` directly. Mock both seams. Disable the# SIGKILL-escalation step (grace=0) so it doesn't call# ``psutil.wait_procs`` on the FakeProcess.- with patch("gateway.status._pid_exists", return_value=True), \+ with patch("gateway.status._pid_exists", side_effect=lambda pid: kill_state["alive"]), \patch.object(ProcessRegistry, "_daemon_term_grace_seconds",staticmethod(lambda: 0.0)), \patch.object(_psutil, "Process", side_effect=lambda pid: FakeProcess(pid)):diff --git a/tools/process_registry.py b/tools/process_registry.pyindex 8706f5a63d4..8c97e4a81b0 100644--- a/tools/process_registry.py+++ b/tools/process_registry.py@@ -947,6 +947,52 @@ class ProcessRegistry(ProcessCheckpointMixin):proc.kill() # SIGKILL on POSIXlogger.info("Escalated to SIGKILL for pid %d (ignored SIGTERM within %.1fs grace)", proc.pid, grace)+ @staticmethod+ def _live_descendants(pid: int) -> List[int]:+ """PIDs of living non-zombie descendants of host PID ``pid`` (best-effort)."""+ try:+ import psutil+ children = psutil.Process(pid).children(recursive=True)+ except Exception:+ return []+ return [c.pid for c in children if ProcessRegistry._proc_alive(c)]++ def _post_kill_survivors(self, session: "ProcessSession") -> List[int]:+ """Host PIDs still alive after the kill signals were delivered (#115490).++ Fail-closed: anything unverifiable counts as a survivor, so a kill+ that leaves a live tree can never write a killed receipt. Sandbox+ (env) sessions have no host-visible tree and are unverifiable by+ design — they return no survivors, preserving existing behavior."""+ survivors: List[int] = []+ proc = getattr(session, "process", None)+ if proc is not None:+ try:+ root_alive = proc.poll() is None+ except Exception:+ root_alive = True+ if root_alive:+ survivors.append(getattr(proc, "pid", None) or session.pid)+ pty = getattr(session, "_pty", None)+ if pty is not None:+ try:+ pty_alive = bool(pty.isalive())+ except Exception:+ pty_alive = self._is_host_pid_alive(session.pid)+ if pty_alive:+ survivors.append(session.pid)+ if session.pid_scope == "host" and session.pid:+ if self._host_pid_is_ours(session.pid, session.host_start_time):+ if session.pid not in survivors:+ survivors.append(session.pid)+ survivors.extend(+ pid for pid in self._live_descendants(session.pid)+ if pid not in survivors)+ # A dead/recycled root has no PID-scope descendants left to find:+ # reparented orphans are outside PID scope (systemd scope stop,+ # issued before this check, covers the cgroup case).+ return [pid for pid in survivors if pid]+# ----- Spawn -----@staticmethod@@ -1954,6 +2000,28 @@ class ProcessRegistry(ProcessCheckpointMixin):# descendants reparented inside the cgroup.if session.systemd_unit:_stop_systemd_unit(session.systemd_unit)+ # Post-kill verification (#115490): the signals above can leave+ # survivors (SIGTERM-ignoring daemons, scope escapees). A kill that+ # leaves a live tree must not write a killed receipt or prune the+ # session — the survivors would become unmanageable. Keep the+ # session running so it stays listed and killable.+ with session._lock:+ signal_race_exited = session.exited+ # A reader that finalised the session mid-signal already proved+ # real exit; only a still-running session needs tree-death proof.+ survivors = [] if signal_race_exited else self._post_kill_survivors(session)+ if survivors:+ alive = ", ".join(map(str, survivors))+ logger.warning(+ "Kill incomplete for %s: %d process(es) still alive (%s) — session kept running",+ session.id, len(survivors), alive)+ return {+ "status": "error",+ "error": (+ f"Kill incomplete: {len(survivors)} process(es) still alive "+ f"({alive}); session running"),+ "session_id": session.id, "survivors": survivors,+ "process_running": True}# Capture output, mark consumed, THEN expose ``exited`` to watcher tasks —# closes the delayed-notification race without losing the transcript.with session._lock: