diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py index 3b7d8b0361..bc81774e4a 100644 --- a/agent/chat_completion_helpers.py +++ b/agent/chat_completion_helpers.py @@ -555,6 +555,14 @@ def should_use_direct_api_call(agent) -> bool: return getattr(agent, "platform", None) == "subagent" +# How often an in-flight direct_api_call refreshes last_activity_ts. +# Must stay well under the async-delegation idle stall threshold (450s) and +# the sync heartbeat idle window so a healthy slow model wait is never +# mistaken for a frozen child. Kept below the 30s monitor sweep interval so +# progress tokens change every sample while the request is open. +_DIRECT_API_ACTIVITY_HEARTBEAT_SECONDS = 15.0 + + def direct_api_call(agent, api_kwargs: dict): """Run a non-streaming LLM call inline on the conversation thread. @@ -565,11 +573,18 @@ def direct_api_call(agent, api_kwargs: dict): request runs in-flight normally, the per-request OpenAI client's own httpx timeout (provider ``request_timeout_seconds`` / ``HERMES_API_TIMEOUT``) bounds a genuinely hung provider — the same bound interactive calls already rely on. + + While the inline request blocks, a lightweight activity heartbeat keeps + ``last_activity_ts`` advancing. Subagents use this path (non-streaming), + and without mid-call ticks the async stall monitor / sync heartbeat treat + a slow-but-healthy local model wait as "no progress" and interrupt around + 450s — surfacing as ``Operation interrupted: waiting for model response``. """ _check_stale_giveup(agent) agent._touch_activity("waiting for non-streaming API response") request_client_holder = {"client": None} request_client_lock = threading.Lock() + activity_hb_stop = threading.Event() def _abort_active_request(reason: str) -> None: """Abort the inline request from a watchdog/interrupt thread.""" @@ -595,6 +610,23 @@ def direct_api_call(agent, api_kwargs: dict): agent._active_request_abort = _abort_active_request return client + def _activity_heartbeat() -> None: + # Do not put the API call itself on another worker thread — that is + # the nested-pool deadlock this path exists to avoid (#60203). This + # ticker only refreshes the activity clock. + while not activity_hb_stop.wait(_DIRECT_API_ACTIVITY_HEARTBEAT_SECONDS): + try: + agent._touch_activity("waiting for non-streaming API response") + except Exception: + pass + + activity_hb = threading.Thread( + target=_activity_heartbeat, + name="direct-api-activity-hb", + daemon=True, + ) + activity_hb.start() + # Only a clean return may report the reuse reason (request_complete): # after an error or interrupt the wire client is really closed so the # retry builds a fresh pool (see _REQUEST_CLIENT_REUSE_REASONS). @@ -614,6 +646,7 @@ def direct_api_call(agent, api_kwargs: dict): succeeded = True return response finally: + activity_hb_stop.set() if getattr(agent, "_active_request_abort", None) is _abort_active_request: agent._active_request_abort = None with request_client_lock: diff --git a/tests/cron/test_cron_direct_api_call_62151.py b/tests/cron/test_cron_direct_api_call_62151.py index f6c4c19d53..56bbc4db17 100644 --- a/tests/cron/test_cron_direct_api_call_62151.py +++ b/tests/cron/test_cron_direct_api_call_62151.py @@ -69,3 +69,62 @@ def test_direct_api_call_runs_two_sequential_requests_on_same_thread(): assert calls["n"] == 2 assert fake_client.chat.completions.create.call_count == 2 assert agent._close_request_openai_client.call_count == 2 + + +def test_direct_api_call_keeps_activity_alive_during_slow_wait(monkeypatch): + """Mid-wait activity heartbeats must tick while the inline request blocks. + + Subagents use direct_api_call (non-streaming). Without mid-call + ``_touch_activity`` ticks, the async stall monitor treats a slow-but- + healthy local model wait as frozen progress and interrupts around 450s + (``Operation interrupted: waiting for model response``). + """ + import threading + import time + + from agent import chat_completion_helpers as helpers + + monkeypatch.setattr(helpers, "_DIRECT_API_ACTIVITY_HEARTBEAT_SECONDS", 0.05) + + agent = _make_agent(platform="subagent") + started = threading.Event() + release = threading.Event() + fake_client = MagicMock() + + def _slow_create(**_kwargs): + started.set() + assert release.wait(timeout=2.0) + return SimpleNamespace(id="slow") + + fake_client.chat.completions.create.side_effect = _slow_create + agent._create_request_openai_client.return_value = fake_client + + result_box = {} + + def _runner(): + result_box["response"] = direct_api_call( + agent, {"model": "m", "messages": []} + ) + + worker = threading.Thread(target=_runner, daemon=True) + worker.start() + assert started.wait(timeout=2.0) + + # Allow several heartbeat intervals while the request is still blocked. + deadline = time.time() + 1.0 + while time.time() < deadline and agent._touch_activity.call_count < 3: + time.sleep(0.05) + + touches_while_blocked = agent._touch_activity.call_count + release.set() + worker.join(timeout=2.0) + + assert worker.is_alive() is False + assert result_box["response"].id == "slow" + assert touches_while_blocked >= 3, ( + f"expected mid-wait activity heartbeats, got {touches_while_blocked}" + ) + assert all( + call.args[0] == "waiting for non-streaming API response" + for call in agent._touch_activity.call_args_list + ) diff --git a/tests/tools/test_delegate.py b/tests/tools/test_delegate.py index fc97153591..615ec3d679 100644 --- a/tests/tools/test_delegate.py +++ b/tests/tools/test_delegate.py @@ -1112,6 +1112,69 @@ class TestDelegateHeartbeat(unittest.TestCase): f"got {len(touch_calls)} touches", ) + def test_heartbeat_does_not_trip_idle_stale_while_waiting_on_model(self): + """A slow in-flight model wait (api_call_count frozen, no tool) must + stay alive when last_activity_ts keeps advancing. + + Top-level delegate_task runs in the background; the async stall + monitor already treats ticking last_activity_ts as progress. The sync + heartbeat path must use the same signal so slow local / long-prefill + completions are not mistaken for a wedged idle child. + """ + from tools.delegate_tool import _run_single_child + + parent = _make_mock_parent() + touch_calls = [] + kept_going = threading.Event() + + def record(desc): + touch_calls.append(desc) + if len(touch_calls) > 2: + kept_going.set() + + parent._touch_activity = record + + child = MagicMock() + activity = {"ts": 1000.0} + + def _summary(): + # Frozen iteration / no tool — only the activity clock moves, + # matching direct_api_call's mid-wait heartbeats. + activity["ts"] += 1.0 + return { + "current_tool": None, + "api_call_count": 1, + "max_iterations": 50, + "last_activity_desc": "waiting for non-streaming API response", + "last_activity_ts": activity["ts"], + } + + child.get_activity_summary.side_effect = _summary + + def slow_run(**kwargs): + kept_going.wait(5) + return {"final_response": "done", "completed": True, "api_calls": 1} + + child.run_conversation.side_effect = slow_run + + with ( + patch("tools.delegate_tool._HEARTBEAT_INTERVAL", 0.01), + patch("tools.delegate_tool._HEARTBEAT_STALE_CYCLES_IDLE", 2), + patch("tools.delegate_tool._HEARTBEAT_STALE_CYCLES_IN_TOOL", 40), + ): + _run_single_child( + task_index=0, + goal="Test slow model wait", + child=child, + parent_agent=parent, + ) + + self.assertGreater( + len(touch_calls), 2, + f"Heartbeat stopped too early while child was waiting on the model; " + f"got {len(touch_calls)} touches", + ) + class TestDelegationReasoningEffort(unittest.TestCase): """Tests for delegation.reasoning_effort config override.""" diff --git a/tools/delegate_tool.py b/tools/delegate_tool.py index 13e2143336..eb4df253e7 100644 --- a/tools/delegate_tool.py +++ b/tools/delegate_tool.py @@ -731,14 +731,20 @@ _MIN_SUMMARY_CHARS = 2000 # in via delegation.child_timeout_seconds. DEFAULT_CHILD_TIMEOUT: Optional[float] = None _HEARTBEAT_INTERVAL = 30 # seconds between parent activity heartbeats during delegation -# Stale-heartbeat thresholds. A child with no API-call progress is either: -# - idle between turns (no current_tool) — probably stuck on a slow API call +# Stale-heartbeat thresholds. A child with no observable progress is either: +# - idle between turns (no current_tool, frozen last_activity_ts) — wedged # - inside a tool (current_tool set) — probably running a legitimately long # operation (terminal command, web fetch, large file read) -# The idle ceiling stays tight so genuinely stuck children don't mask the gateway -# timeout. The in-tool ceiling is much higher so legit long-running tools get -# time to finish; delegation.child_timeout_seconds (off by default) remains an -# optional hard cap for users who want one. +# An in-flight model wait is NOT idle: direct_api_call refreshes +# last_activity_ts while the request is open, and the monitor treats that +# timestamp advance as progress (same signal as streamed chunks / async +# stall monitor). Slow local GGUF / long-prefill models must not be killed +# for taking longer than the idle window on a single completion. +# The idle ceiling stays tight so a child that is truly between turns with +# no activity doesn't mask the gateway timeout. The in-tool ceiling is much +# higher so legit long-running tools get time to finish; +# delegation.child_timeout_seconds (off by default) remains an optional hard +# cap for users who want one. _HEARTBEAT_STALE_CYCLES_IDLE = 15 # 15 * 30s = 450s idle between turns → stale _HEARTBEAT_STALE_CYCLES_IN_TOOL = 40 # 40 * 30s = 1200s stuck on same tool → stale DEFAULT_TOOLSETS = ["terminal", "file", "web"] @@ -2003,11 +2009,14 @@ def _run_single_child( # Without this, the parent's _last_activity_ts freezes when delegate_task # starts and the gateway eventually kills the agent for "no activity". _heartbeat_stop = threading.Event() - # Stale detection: track the child's (tool, iteration) pair across - # heartbeat cycles. If neither advances, count the cycle as stale. + # Stale detection: track the child's (tool, iteration, activity_ts) across + # heartbeat cycles. If none advances, count the cycle as stale. # Different thresholds for idle vs in-tool (see _HEARTBEAT_STALE_CYCLES_*). + # last_activity_ts is the same liveness signal the async stall monitor + # already uses (streamed chunks + direct_api_call mid-wait heartbeats). _last_seen_iter = [0] _last_seen_tool = [None] # type: list + _last_seen_activity_ts = [None] # type: list _stale_count = [0] def _heartbeat_loop(): @@ -2024,18 +2033,28 @@ def _run_single_child( child_tool = child_summary.get("current_tool") child_iter = child_summary.get("api_call_count", 0) child_max = child_summary.get("max_iterations", 0) + child_activity_ts = child_summary.get("last_activity_ts") - # Stale detection: count cycles where neither the iteration - # count nor the current_tool advances. A child running a - # legitimately long-running tool (terminal command, web - # fetch) keeps current_tool set but doesn't advance - # api_call_count — we don't want that to look stale at the - # idle threshold. + # Stale detection: count cycles where iteration, current_tool, + # AND last_activity_ts are all frozen. A child running a + # legitimately long-running tool keeps current_tool set; a + # child waiting on a slow model refreshes last_activity_ts + # via direct_api_call's activity heartbeat — neither should + # look stale at the idle threshold. iter_advanced = child_iter > _last_seen_iter[0] tool_changed = child_tool != _last_seen_tool[0] - if iter_advanced or tool_changed: + activity_advanced = ( + child_activity_ts is not None + and ( + _last_seen_activity_ts[0] is None + or child_activity_ts > _last_seen_activity_ts[0] + ) + ) + if iter_advanced or tool_changed or activity_advanced: _last_seen_iter[0] = child_iter _last_seen_tool[0] = child_tool + if child_activity_ts is not None: + _last_seen_activity_ts[0] = child_activity_ts _stale_count[0] = 0 else: _stale_count[0] += 1