The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(delegation): a stale subagent ends the sync delegation wait instead of holding the turn forever
teknium190663bff3031
diff --git a/tests/tools/test_delegate_stale_wait_release.py b/tests/tools/test_delegate_stale_wait_release.pynew file mode 100644index 00000000000..1c94c216e98--- /dev/null+++ b/tests/tools/test_delegate_stale_wait_release.py@@ -0,0 +1,62 @@+"""A child whose worker never returns after the heartbeat declares it stale must not hold+the parent forever (#109749: sync delegation in a -Q one-shot kept the Bot Chat lease)."""++from __future__ import annotations++import threading+from types import SimpleNamespace++from tools import delegate_tool+++class _WedgedAfterFinalAnswer:+ """Frozen activity (final answer already written); the worker only unwinds when released."""++ def __init__(self) -> None:+ self.tool_progress_callback = None+ self._credential_pool = None+ self._delegate_saved_tool_names = []+ self._delegate_role = "leaf"+ self._delegate_depth = 1+ self._subagent_id = None+ self.session_id = "wedged-child"+ self.release = threading.Event()+ self.interrupted = threading.Event()++ def run_conversation(self, **_kwargs):+ self.release.wait()+ return {"final_response": "VERDICT", "completed": True, "api_calls": 28, "messages": []}++ def get_activity_summary(self):+ return {"api_call_count": 28, "current_tool": None, "last_activity_ts": 1000.0, "max_iterations": 50}++ def hard_interrupt(self, *_args, **_kwargs):+ self.interrupted.set()++ def close(self):+ self.release.set()+++def test_stale_heartbeat_ends_the_wait_without_a_configured_timeout(monkeypatch):+ child = _WedgedAfterFinalAnswer()+ parent = SimpleNamespace(+ session_id="parent", _current_task_id=None, _active_children=[child],+ _active_children_lock=threading.Lock(), _touch_activity=lambda _d: None, _interrupt_requested=False,+ )+ monkeypatch.setattr(delegate_tool, "_HEARTBEAT_INTERVAL", 0.01)+ monkeypatch.setattr(delegate_tool, "_HEARTBEAT_STALE_CYCLES_IDLE", 2)+ monkeypatch.setattr(delegate_tool, "_get_child_timeout", lambda: None)+ monkeypatch.setattr(delegate_tool, "_get_worktree_isolation", lambda: False)+ # Safety valve so an unfixed tree fails (status "completed") instead of hanging the suite.+ valve = threading.Timer(30.0, child.release.set)+ valve.daemon = True+ valve.start()+ try:+ entry = delegate_tool._run_single_child(0, "review", child=child, parent_agent=parent)+ finally:+ valve.cancel()+ child.release.set()++ assert entry["status"] == "timeout", entry+ assert "stopped making progress" in entry["error"]+ assert child.interrupted.is_set()diff --git a/tools/delegate_tool.py b/tools/delegate_tool.pyindex 3d5b11019fe..eaf0261f2a7 100644--- a/tools/delegate_tool.py+++ b/tools/delegate_tool.py@@ -313,7 +313,7 @@ def _run_single_child(child_progress_cb = getattr(child, "tool_progress_callback", None)child_pool, leased_cred_id = _lease_child_credential(child)# Heartbeat keeps the parent's _last_activity_ts moving so the gateway inactivity timeout doesn't fire while the- # child works; it stops itself once the child looks stale (see _HEARTBEAT_STALE_CYCLES_*).+ # child works; once the child looks stale (see _HEARTBEAT_STALE_CYCLES_*) it also ends await_child's wait.heartbeat = _start_heartbeat(child, parent_agent, task_index)# TUI/RPC registry entry (kill/pause/status by subagent_id); None for test# doubles without a stable id. Unregistered in the finally block.@@ -321,7 +321,7 @@ def _run_single_child(child, parent_agent, goal, owner_session_id=owner_session_id, owner_transport=owner_transport,owner_session_record=owner_session_record,)- run = _ChildRun(child, parent_agent, task_index, goal, _subagent_id, child_progress_cb)+ run = _ChildRun(child, parent_agent, task_index, goal, _subagent_id, child_progress_cb, heartbeat=heartbeat)# Set when a timed-out Future still owns the child: closing it from this# thread before the worker settles races the conversation's finally path._child_close_deferred = Falsediff --git a/tools/delegate_tool_child_run.py b/tools/delegate_tool_child_run.pyindex 0d8a39e1a94..388bfccb3a9 100644--- a/tools/delegate_tool_child_run.py+++ b/tools/delegate_tool_child_run.py@@ -233,6 +233,9 @@ class _Heartbeat:# activity_ts) all froze; thresholds differ idle vs in-tool.self.last_seen = {"iter": 0, "tool": None, "ts": None, "stale": 0}self.handle = None+ # Set on the stale verdict; ``await_child`` waits on it (its worker's done-callback+ # sets it too) so a wedged child ends the wait instead of only ending the heartbeat.+ self.settled = threading.Event()def start(self) -> None:from agent.periodic_scheduler import schedule@@ -271,10 +274,12 @@ class _Heartbeat:last_seen["stale"] += 1if last_seen["stale"] >= (_HEARTBEAT_STALE_CYCLES_IN_TOOL if child_tool else _HEARTBEAT_STALE_CYCLES_IDLE):logger.warning(- "Subagent %d appears stale (no progress for %d heartbeat cycles, tool=%s) — stopping heartbeat",+ "Subagent %d appears stale (no progress for %d heartbeat cycles, tool=%s) — abandoning its wait",task_index, last_seen["stale"], child_tool or "<none>",)- return False # stop touching parent, let gateway timeout fire+ # A finite/-Q turn has no gateway watchdog behind this; the wait itself must end (#109749).+ self.settled.set()+ return Falseif child_tool:desc = f"delegate_task: subagent running {child_tool} (iteration {child_iter}/{child_max})"elif child_summary.get("last_activity_desc", ""):@@ -634,6 +639,7 @@ class _ChildRun:goal: strsubagent_id: Optional[str]child_progress_cb: Any+ heartbeat: Any = Nonechild_start: float = field(default_factory=time.monotonic)worktree_info: Optional[Dict[str, str]] = Nonechild_task_id: str = ""@@ -742,8 +748,17 @@ class _ChildRun:)future = executor.submit(contextvars.copy_context().run, _run_with_thread_capture)+ # One wait covers both ways out: the worker finishing, or the heartbeat's stale verdict.+ # Without the second, a worker wedged after its final answer holds a finite (-Q / Bot Chat+ # one-shot) turn — and its session lease — forever, since that runtime has no gateway+ # inactivity watchdog (#109749).+ settled = self.heartbeat.settled if self.heartbeat is not None else threading.Event()+ future.add_done_callback(lambda _f: settled.set())try:- return future.result(timeout=child_timeout), None, False+ settled.wait(timeout=child_timeout)+ if not future.done():+ raise FuturesTimeoutError()+ return future.result(), None, Falseexcept Exception as wait_exc:exc: BaseException = wait_exc # ``as`` targets are unbound after the except blockfinally:@@ -773,6 +788,11 @@ class _ChildRun:logger.warning("Subagent %d 0-API-call timeout — diagnostic written to %s", task_index, diagnostic_path)if not is_timeout:_err = str(exc)+ elif child_timeout is None:+ _err = (+ f"Subagent stopped making progress after {child_api_calls} API call(s) (heartbeat stale "+ f"threshold) — the pending worker was abandoned."+ )elif before_first_call:_err = (f"Subagent timed out after {child_timeout}s without making any API call — the child never reached its "