The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): reap an abandoned turn's background jobs by owner, not container key
John Paul Solivafc3533d1237c
diff --git a/tests/gateway/test_abandoned_turn_process_cleanup.py b/tests/gateway/test_abandoned_turn_process_cleanup.pyindex c0a62014863..6eebd8d9e5e 100644--- a/tests/gateway/test_abandoned_turn_process_cleanup.py+++ b/tests/gateway/test_abandoned_turn_process_cleanup.py@@ -1,12 +1,21 @@"""Regression coverage for abandoned gateway-turn subprocess cleanup (#76115)."""+import jsonimport threading+from contextvars import copy_context++import pytestfrom gateway.run import (+ GatewayRunner,_abandon_timed_out_gateway_turn,_reap_gateway_turn_processes,_watch_gateway_turn_inactivity,)+from gateway.session_context import set_session_vars+from gateway.session_state import SessionState+from model_tools import handle_function_call+from tools.approval_context import set_current_session_keyfrom tools.process_registry import process_registry@@ -412,3 +421,103 @@ def test_dump_wedged_turn_stacks_never_raises(monkeypatch):from gateway.run import _dump_wedged_turn_stacks_dump_wedged_turn_stacks("t-no-raise") # must not raise+++# ---------------------------------------------------------------------------+# Real spawns: the terminal tool stores the CONTAINER key in ``task_id``+# (``session:<key>``, ``default``) and the turn's own id in ``owner_task_id``;+# the reap is keyed by the turn's id, so it must match on the owner.+# ---------------------------------------------------------------------------+++def _plain_spawn(monkeypatch):+ """The systemd-run --user --scope wrapper is irrelevant here and stalls under pytest."""+ import tools.process_registry as _pr+ monkeypatch.setattr(_pr, "_SYSTEMD_SCOPE_AVAILABLE", False)+++def _bind_session(session_key, session_id, platform="telegram"):+ set_session_vars(platform=platform, chat_id=session_id, user_id=session_id,+ session_key=session_key, session_id=session_id)+ set_current_session_key(session_key)+++def _spawn_background(turn_task_id, spawned):+ out = json.loads(handle_function_call(+ "terminal", {"command": "sleep 300", "background": True}, task_id=turn_task_id))+ spawned.append(process_registry.get(out["session_id"]))+ return spawned[-1]+++def _kill_own(spawned):+ for session in spawned:+ if session is not None:+ process_registry.kill_process(session.id)+++def test_stop_reaps_the_background_job_the_stopped_turn_started(_plain_spawn):+ """/stop (shared with /new and eviction) reaps the job the stopped turn started and keeps+ the session's older job, on the local backend's ``session:<key>`` container key."""+ session_key, session_id = "agent:main:telegram:dm:76115", "20260924_stop_76115"+ spawned = []++ def scenario():+ _bind_session(session_key, session_id)+ older = _spawn_background(session_id, spawned)+ # Turn start, as the gateway turn does it: baseline keyed by the turn's session id.+ agent = _IdleAgent()+ agent._gateway_turn_process_task_id = session_id+ agent._gateway_turn_process_baseline = process_registry.snapshot_running_ids(session_id)+ job = _spawn_background(session_id, spawned)+ assert job.task_id != job.owner_task_id == session_id++ runner = object.__new__(GatewayRunner)+ runner._sessions = {session_key: SessionState()}+ runner._sessions[session_key].turn.agent = agent+ runner._interrupt_running_turn(+ session_key, interrupt_reason="Stop requested", invalidation_reason="stop_command_handler")++ assert agent.interrupts == ["Stop requested"]+ assert process_registry.wait(job.id, timeout=30)["status"] == "exited"+ assert process_registry.poll(older.id)["status"] == "running"++ try:+ copy_context().run(scenario)+ finally:+ _kill_own(spawned)+++def test_timed_out_turn_reaps_only_its_own_job_on_a_shared_container_key(_plain_spawn):+ """Two sessions on ONE container key (``default``: keyless API sessions here, every+ default-profile session under persistent Docker). The timed-out turn lists and loses only+ the job it started; the sibling session's job, started after the baseline, survives."""+ turn_a, turn_b = "api-session-a-76115", "api-session-b-76115"+ spawned = []++ def scenario():+ _bind_session("", turn_a, platform="api_server")+ baseline = process_registry.snapshot_running_ids(turn_a)+ mine = _spawn_background(turn_a, spawned)+ _bind_session("", turn_b, platform="api_server")+ sibling = _spawn_background(turn_b, spawned)+ assert mine.task_id == sibling.task_id and mine.owner_task_id != sibling.owner_task_id++ _bind_session("", turn_a, platform="api_server")+ listed = json.loads(handle_function_call("process_manage", {"action": "list"}, task_id=turn_a))+ assert [p["session_id"] for p in listed["processes"]] == [mine.id]++ agent, worker_done, timeout_fired, cleanup_lock = _IdleAgent(), *_state()+ _watch_gateway_turn_inactivity(+ agent_holder=[agent], task_id=turn_a, process_baseline=baseline, timeout=0.05,+ worker_done=worker_done, timeout_fired=timeout_fired, cleanup_lock=cleanup_lock,+ poll_interval=0.01)++ assert timeout_fired.is_set()+ assert process_registry.wait(mine.id, timeout=30)["status"] == "exited"+ assert process_registry.poll(sibling.id)["status"] == "running"++ try:+ copy_context().run(scenario)+ finally:+ _kill_own(spawned)diff --git a/tools/process_registry.py b/tools/process_registry.pyindex 1aeb66f88d9..7774914c6b4 100644--- a/tools/process_registry.py+++ b/tools/process_registry.py@@ -2275,10 +2275,10 @@ class ProcessRegistry(ProcessCheckpointMixin):cross-task entries sharing the gateway session (a forgotten preview serverblocking session reset) are flagged ``"session_scoped": true``.- When ``task_id`` is given, processes for that task are included. When ``session_key`` is also given,- session-scoped background processes (``background: true``) registered under that gateway session are- surfaced too, even if they belong to a different task — so the agent can discover a forgotten- preview server that is blocking session reset (#29177).+ When ``task_id`` is given, processes that task spawned (its ``owner_task_id``) are included. When+ ``session_key`` is also given, session-scoped background processes (``background: true``) registered+ under that gateway session are surfaced too, even if they belong to a different task — so the agent+ can discover a forgotten preview server that is blocking session reset (#29177)."""# Only an explicit tool query reads historical receipts. Status bars and# gateway liveness scans call this frequently and need the live registry.@@ -2290,7 +2290,8 @@ class ProcessRegistry(ProcessCheckpointMixin):if task_id or session_key:all_sessions = [s for s in all_sessions- if (task_id and s.task_id == task_id) or (session_key and s.session_key == session_key)+ if (task_id and (s.owner_task_id or s.task_id) == task_id)+ or (session_key and s.session_key == session_key)]result = []for s in all_sessions:@@ -2310,7 +2311,7 @@ class ProcessRegistry(ProcessCheckpointMixin):}# Flag processes surfaced only because they share the gateway session (not the current task) —# these are the long-lived background processes a user may have forgotten about (#29177).- if task_id and session_key and s.task_id != task_id and s.session_key == session_key:+ if task_id and session_key and (s.owner_task_id or s.task_id) != task_id and s.session_key == session_key:entry["session_scoped"] = True# Trigger metadata for goal-loop judges (a watcher may never exit).if s.watch_patterns and not s._watch_disabled:@@ -2389,9 +2390,12 @@ class ProcessRegistry(ProcessCheckpointMixin):def snapshot_running_ids(self, task_id: str) -> frozenset[str]:"""Running IDs owned by ``task_id`` — a turn-boundary marker: on timeoutonly processes absent from the starting snapshot belong to the abandoned- turn; older ones intentionally span turns and must survive."""+ turn; older ones intentionally span turns and must survive. Ownership is+ ``owner_task_id``: ``task_id`` is the container key (``session:<key>``,+ ``default``), shared across turns and sessions, not the turn's id."""with self._lock:- return frozenset(s.id for s in self._running.values() if s.task_id == task_id and not s.exited)+ return frozenset(+ s.id for s in self._running.values() if (s.owner_task_id or s.task_id) == task_id and not s.exited)def kill_started_since(self, task_id: str, baseline_ids, *, source: str) -> int:"""Kill ``task_id`` processes created after ``baseline_ids``. Output is@@ -2402,11 +2406,13 @@ class ProcessRegistry(ProcessCheckpointMixin):def kill_all(self, task_id: Optional[str] = None, *, exclude_ids: frozenset = frozenset(),source: str = "kill_all", consume_output: bool = False) -> int:- """Kill all running processes, optionally filtered by task_id. Returns count killed."""+ """Kill all running processes, optionally only those ``task_id`` spawned (its ``owner_task_id``).+ Returns count killed."""with self._lock:targets = [s for s in self._running.values()- if (task_id is None or s.task_id == task_id) and s.id not in exclude_ids and not s.exited+ if (task_id is None or (s.owner_task_id or s.task_id) == task_id)+ and s.id not in exclude_ids and not s.exited]return sum(self.kill_process(s.id, source=source, consume_output=consume_output).get("status")