Skip to content

The agent that grows with you

fix(delegate): defer timed-out child teardown

Leandro Piccioneaa1d22670e38
diff --git a/tests/tools/test_delegate_timeout_cleanup.py b/tests/tools/test_delegate_timeout_cleanup.py
new file mode 100644
index 00000000000..2c16d91e730
--- /dev/null
+++ b/tests/tools/test_delegate_timeout_cleanup.py
@@ -0,0 +1,90 @@
+"""Regression coverage for timed-out delegation teardown."""
+
+from __future__ import annotations
+
+import threading
+from types import SimpleNamespace
+
+from tools import delegate_tool
+
+
+class _SlowUnwindingChild:
+ 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.model = "test-model"
+ self.session_prompt_tokens = 0
+ self.session_completion_tokens = 0
+ self.session_estimated_cost_usd = 0.0
+ self.session_cost_status = "unknown"
+ self.started = threading.Event()
+ self.interrupted = threading.Event()
+ self.unwinding = threading.Event()
+ self.allow_finish = threading.Event()
+ self.finished = threading.Event()
+ self.closed = threading.Event()
+ self.close_while_running = False
+
+ def run_conversation(self, **_kwargs):
+ self.started.set()
+ assert self.interrupted.wait(timeout=1)
+ # Model the real child turn's finally path: it still performs session
+ # activity/SQLite cleanup after the parent requests interruption.
+ self.unwinding.set()
+ assert self.allow_finish.wait(timeout=2)
+ self.finished.set()
+ return {
+ "final_response": "",
+ "completed": False,
+ "interrupted": True,
+ "api_calls": 1,
+ "messages": [],
+ }
+
+ def hard_interrupt(self, _reason=None):
+ self.interrupted.set()
+
+ def get_activity_summary(self):
+ return {"api_call_count": 1}
+
+ def close(self):
+ if not self.finished.is_set():
+ self.close_while_running = True
+ self.closed.set()
+
+
+def test_timeout_does_not_close_child_while_worker_is_unwinding(monkeypatch):
+ child = _SlowUnwindingChild()
+ parent = SimpleNamespace(
+ session_id="parent-timeout-test",
+ _current_task_id=None,
+ _active_children=[child],
+ _active_children_lock=threading.Lock(),
+ )
+ monkeypatch.setattr(delegate_tool, "_get_child_timeout", lambda: 0.5)
+ monkeypatch.setattr(delegate_tool, "_get_worktree_isolation", lambda: False)
+
+ result = delegate_tool._run_single_child(
+ task_index=0,
+ goal="exercise timeout teardown",
+ child=child,
+ parent_agent=parent,
+ )
+
+ assert result["status"] == "timeout"
+ assert child.unwinding.wait(timeout=1)
+ try:
+ assert not child.closed.is_set(), (
+ "timed-out child.close() ran before its conversation thread unwound"
+ )
+ finally:
+ child.allow_finish.set()
+ assert child.finished.wait(timeout=1)
+ assert child.closed.wait(timeout=1)
+ assert not child.close_while_running, (
+ "timed-out child.close() raced its still-running conversation thread"
+ )
diff --git a/tools/delegate_tool.py b/tools/delegate_tool.py
index 5b8f645fda9..770220e9051 100644
--- a/tools/delegate_tool.py
+++ b/tools/delegate_tool.py
@@ -2603,6 +2603,12 @@ def _run_single_child(
parent-visible truncation flag stays truthful for all of the above.
"""
child_start = time.monotonic()
+ # A timed-out Future may still be unwinding on its daemon worker. Closing
+ # the child from this owner thread before that Future settles races every
+ # resource the conversation's finally path still touches (notably its
+ # owned SessionDB). The timeout branch flips this when close ownership is
+ # handed to a Future done-callback instead.
+ _child_close_deferred = False
# Get the progress callback from the child agent
child_progress_cb = getattr(child, "tool_progress_callback", None)
@@ -3080,6 +3086,28 @@ def _run_single_child(
f"{_late_pending_steer}]"
)
_attach_worktree(_error_entry)
+ if is_timeout and not _child_future.done():
+ # request_hard_interrupt() is cooperative: the worker still
+ # executes run_conversation's finally path before its Future
+ # becomes done. child.close() tears down that same agent's
+ # clients, messages, and owned SQLite handle, so calling it in
+ # our outer finally while the worker is alive can close SQLite
+ # underneath its final activity write. Future callbacks run
+ # only after the worker has fully returned (or raised), which
+ # is the first safe close boundary.
+ def _close_after_timed_out_worker(_done_future) -> None:
+ try:
+ close = getattr(child, "close", None)
+ if callable(close):
+ close()
+ except Exception:
+ logger.debug(
+ "Failed to close timed-out child after worker exit",
+ exc_info=True,
+ )
+
+ _child_future.add_done_callback(_close_after_timed_out_worker)
+ _child_close_deferred = True
return _error_entry
finally:
# Shut down executor without waiting — if the child thread
@@ -3554,11 +3582,13 @@ def _run_single_child(
# Close tool resources (terminal sandboxes, browser daemons,
# background processes, httpx clients) so subagent subprocesses
# don't outlive the delegation.
- try:
- if hasattr(child, "close"):
- child.close()
- except Exception:
- logger.debug("Failed to close child agent after delegation")
+ if not _child_close_deferred:
+ try:
+ close = getattr(child, "close", None)
+ if callable(close):
+ close()
+ except Exception:
+ logger.debug("Failed to close child agent after delegation")
# The AIAgent turn boundary normally closes the child scope itself. This
# fallback covers failures before that boundary starts, but must not pop