fix: stream internal model calls with idle timeouts (#5730)

* fix: stream internal model calls with idle timeouts

* fix(providers): reject streams without terminal events
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-11 13:06:43 +08:00
1 parent aeb7b207d7
commit 73410e0217
60 files changed
+815 -795

No files matched your search

+46 -219
View File
@@ -1,11 +1,9 @@
"""Tests for core AgentRunner behavior: message passing, iteration limits,
timeouts, empty-response handling, usage accumulation, and config passthrough."""
empty-response handling, usage accumulation, and config passthrough."""
from __future__ import annotations
import asyncio
import time
from unittest.mock import AsyncMock, MagicMock, patch
from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -226,7 +224,7 @@ async def test_runner_preserves_reasoning_fields_and_tool_results():
captured_second_call: list[dict] = []
call_count = {"n": 0}
async def chat_with_retry(*, messages, **kwargs):
async def chat_stream_with_retry(*, messages, **kwargs):
call_count["n"] += 1
if call_count["n"] == 1:
return LLMResponse(
@@ -239,7 +237,7 @@ async def test_runner_preserves_reasoning_fields_and_tool_results():
captured_second_call[:] = messages
return LLMResponse(content="done", tool_calls=[], usage=None)
provider.chat_with_retry = chat_with_retry
provider.chat_stream_with_retry = chat_stream_with_retry
tools = MagicMock()
tools.get_definitions.return_value = []
tools.execute = AsyncMock(return_value="tool result")
@@ -304,7 +302,7 @@ async def test_runner_replays_provider_state_without_chat_projection_duplicates(
payload={"items": [{"type": "message", "role": "assistant"}]},
)
async def chat_with_retry(**kwargs):
async def chat_stream_with_retry(**kwargs):
nonlocal calls
calls += 1
if calls == 1:
@@ -325,7 +323,7 @@ async def test_runner_replays_provider_state_without_chat_projection_duplicates(
captured_second_kwargs.update(kwargs)
return LLMResponse(content="done", provider_state=second_state)
provider.chat_with_retry = chat_with_retry
provider.chat_stream_with_retry = chat_stream_with_retry
tools = MagicMock()
tools.get_definitions.return_value = []
tools.execute = AsyncMock(return_value="tool result")
@@ -389,7 +387,7 @@ async def test_runner_preserves_tool_result_before_rejecting_unfit_followup():
payload={"items": [{"type": "reasoning", "encrypted_content": "opaque"}]},
)
async def chat_with_retry(**kwargs):
async def chat_stream_with_retry(**kwargs):
nonlocal calls
calls += 1
if calls == 1:
@@ -406,7 +404,7 @@ async def test_runner_preserves_tool_result_before_rejecting_unfit_followup():
)
return LLMResponse(content="done")
provider.chat_with_retry = chat_with_retry
provider.chat_stream_with_retry = chat_stream_with_retry
tools = MagicMock()
tools.get_definitions.return_value = []
tools.execute = AsyncMock(return_value="x" * 5_000)
@@ -466,7 +464,7 @@ async def test_injected_final_response_checkpoint_includes_provider_state():
version=1,
payload={"items": [{"type": "message", "content": "second answer"}]},
)
provider.chat_with_retry = AsyncMock(side_effect=[
provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content="first answer", provider_state=first_state),
LLMResponse(content="second answer", provider_state=second_state),
])
@@ -502,7 +500,7 @@ async def test_runner_preserves_last_completed_provider_state_on_model_error():
provider = MagicMock(spec=LLMProvider)
provider.can_resume_conversation_state.return_value = True
provider.chat_with_retry = AsyncMock(return_value=LLMResponse(
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
content="temporary upstream failure",
finish_reason="error",
error_kind="timeout",
@@ -545,7 +543,7 @@ async def test_runner_discards_provider_state_on_non_retryable_model_error():
provider = MagicMock(spec=LLMProvider)
provider.can_resume_conversation_state.return_value = True
provider.chat_with_retry = AsyncMock(return_value=LLMResponse(
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
content="context length exceeded",
finish_reason="error",
error_status_code=400,
@@ -580,7 +578,7 @@ async def test_runner_returns_max_iterations_fallback():
from nanobot.agent.runner import AgentRunner
provider = MagicMock(spec=LLMProvider)
provider.chat_with_retry = AsyncMock(return_value=LLMResponse(
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
content="still working",
tool_calls=[ToolCallRequest(id="call_1", name="list_dir", arguments={"path": "."})],
))
@@ -604,8 +602,8 @@ async def test_runner_returns_max_iterations_fallback():
)
assert result.messages[-1]["role"] == "assistant"
assert result.messages[-1]["content"] == result.final_content
assert provider.chat_with_retry.await_count == 3
assert provider.chat_with_retry.await_args_list[-1].kwargs["tools"] is None
assert provider.chat_stream_with_retry.await_count == 3
assert provider.chat_stream_with_retry.await_args_list[-1].kwargs["tools"] is None
assert tools.execute.await_count == 2
@@ -616,7 +614,7 @@ async def test_runner_uses_no_tools_finalization_after_max_iterations():
provider = MagicMock(spec=LLMProvider)
calls: list[dict] = []
async def chat_with_retry(*, messages, tools=None, **kwargs):
async def chat_stream_with_retry(*, messages, tools=None, **kwargs):
calls.append({"messages": messages, "tools": tools})
if len(calls) <= 2:
return LLMResponse(
@@ -636,7 +634,7 @@ async def test_runner_uses_no_tools_finalization_after_max_iterations():
usage=LLMUsage.reported(input_tokens=10, output_tokens=7),
)
provider.chat_with_retry = chat_with_retry
provider.chat_stream_with_retry = chat_stream_with_retry
tools = MagicMock()
tools.get_definitions.return_value = []
tools.execute = AsyncMock(return_value="tool result")
@@ -670,176 +668,6 @@ async def test_runner_uses_no_tools_finalization_after_max_iterations():
]
@pytest.mark.asyncio
async def test_runner_times_out_hung_llm_request():
from nanobot.agent.runner import AgentRunner
provider = MagicMock(spec=LLMProvider)
async def chat_with_retry(**kwargs):
await asyncio.sleep(3600)
provider.chat_with_retry = chat_with_retry
tools = MagicMock()
tools.get_definitions.return_value = []
runner = AgentRunner()
started = time.monotonic()
result = await runner.run(make_run_spec(provider,
initial_messages=[{"role": "user", "content": "hello"}],
tools=tools,
model="test-model",
max_iterations=1,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
llm_timeout_s=0.05,
))
assert (time.monotonic() - started) < 1.0
assert result.stop_reason == "error"
assert "timed out" in (result.final_content or "").lower()
@pytest.mark.asyncio
async def test_runner_times_out_hung_max_iteration_finalization():
from nanobot.agent.runner import AgentRunner
provider = MagicMock()
calls = 0
async def chat_with_retry(**kwargs):
nonlocal calls
calls += 1
if calls == 1:
return LLMResponse(
content="",
tool_calls=[
ToolCallRequest(
id="call_1",
name="probe",
arguments={},
)
],
finish_reason="tool_calls",
)
await asyncio.Event().wait()
provider.chat_with_retry = chat_with_retry
tools = MagicMock()
tools.get_definitions.return_value = []
tools.execute = AsyncMock(return_value="ok")
result = await asyncio.wait_for(
AgentRunner().run(make_run_spec(
provider,
initial_messages=[{"role": "user", "content": "run the probe"}],
tools=tools,
model="test-model",
max_iterations=1,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
max_iterations_message="fallback after {max_iterations} iteration",
llm_timeout_s=0.01,
)),
timeout=1.0,
)
assert calls == 2
assert result.stop_reason == "max_iterations"
assert result.error is None
assert result.final_content == "fallback after 1 iteration"
@pytest.mark.asyncio
async def test_runner_applies_outer_wall_timeout_to_streaming_requests():
from nanobot.agent.hook import AgentHook, AgentHookContext
from nanobot.agent.runner import AgentRunner
provider = MagicMock(spec=LLMProvider)
streamed: list[str] = []
async def chat_stream_with_retry(*, on_content_delta, **kwargs):
await asyncio.sleep(0)
await on_content_delta("still ")
await asyncio.sleep(0)
await on_content_delta("alive")
return LLMResponse(content="still alive", tool_calls=[])
provider.chat_stream_with_retry = chat_stream_with_retry
provider.chat_with_retry = AsyncMock()
tools = MagicMock()
tools.get_definitions.return_value = []
class StreamingHook(AgentHook):
def wants_streaming(self) -> bool:
return True
async def on_stream(self, context: AgentHookContext, delta: str) -> None:
streamed.append(delta)
runner = AgentRunner()
wait_for_calls: list[float] = []
async def fake_wait_for(coro, *, timeout):
wait_for_calls.append(timeout)
return await coro
with patch("nanobot.agent.runner.asyncio.wait_for", fake_wait_for):
result = await runner.run(make_run_spec(provider,
initial_messages=[{"role": "user", "content": "think for a while"}],
tools=tools,
model="test-model",
max_iterations=1,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
hook=StreamingHook(),
llm_timeout_s=0.01,
))
assert result.stop_reason == "completed"
assert result.final_content == "still alive"
assert streamed == ["still ", "alive"]
provider.chat_with_retry.assert_not_awaited()
assert wait_for_calls == [300.0]
@pytest.mark.asyncio
async def test_runner_times_out_never_ending_streaming_request():
from nanobot.agent.hook import AgentHook
from nanobot.agent.runner import AgentRunner
provider = MagicMock(spec=LLMProvider)
async def chat_stream_with_retry(*, on_content_delta, **kwargs):
await asyncio.sleep(3600)
provider.chat_stream_with_retry = chat_stream_with_retry
provider.chat_with_retry = AsyncMock()
tools = MagicMock()
tools.get_definitions.return_value = []
class StreamingHook(AgentHook):
def wants_streaming(self) -> bool:
return True
async def fake_wait_for(coro, *, timeout):
coro.close()
raise asyncio.TimeoutError
runner = AgentRunner()
with patch("nanobot.agent.runner.asyncio.wait_for", fake_wait_for):
result = await runner.run(make_run_spec(provider,
initial_messages=[{"role": "user", "content": "think forever"}],
tools=tools,
model="test-model",
max_iterations=1,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
hook=StreamingHook(),
llm_timeout_s=200,
))
assert result.stop_reason == "error"
assert result.final_content == "Error calling LLM: timed out after 400s"
provider.chat_with_retry.assert_not_awaited()
@pytest.mark.asyncio
async def test_runner_replaces_empty_tool_result_with_marker():
from nanobot.agent.runner import AgentRunner
@@ -848,7 +676,7 @@ async def test_runner_replaces_empty_tool_result_with_marker():
captured_second_call: list[dict] = []
call_count = {"n": 0}
async def chat_with_retry(*, messages, **kwargs):
async def chat_stream_with_retry(*, messages, **kwargs):
call_count["n"] += 1
if call_count["n"] == 1:
return LLMResponse(
@@ -859,7 +687,7 @@ async def test_runner_replaces_empty_tool_result_with_marker():
captured_second_call[:] = messages
return LLMResponse(content="done", tool_calls=[], usage=None)
provider.chat_with_retry = chat_with_retry
provider.chat_stream_with_retry = chat_stream_with_retry
tools = MagicMock()
tools.get_definitions.return_value = []
tools.execute = AsyncMock(return_value="")
@@ -886,7 +714,7 @@ async def test_runner_retries_empty_final_response_with_summary_prompt():
provider = MagicMock(spec=LLMProvider)
calls: list[dict] = []
async def chat_with_retry(*, messages, tools=None, **kwargs):
async def chat_stream_with_retry(*, messages, tools=None, **kwargs):
calls.append({"messages": messages, "tools": tools})
if len(calls) <= 2:
return LLMResponse(
@@ -900,7 +728,7 @@ async def test_runner_retries_empty_final_response_with_summary_prompt():
usage=LLMUsage.reported(input_tokens=3, output_tokens=7),
)
provider.chat_with_retry = chat_with_retry
provider.chat_stream_with_retry = chat_stream_with_retry
tools = MagicMock()
tools.get_definitions.return_value = []
@@ -938,7 +766,7 @@ async def test_runner_does_not_retry_blank_policy_terminal(
from nanobot.utils.runtime import EMPTY_FINAL_RESPONSE_MESSAGE
provider = MagicMock(spec=LLMProvider)
provider.chat_with_retry = AsyncMock(return_value=LLMResponse(
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
content=None,
finish_reason=finish_reason,
))
@@ -954,7 +782,7 @@ async def test_runner_does_not_retry_blank_policy_terminal(
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
))
assert provider.chat_with_retry.await_count == 1
assert provider.chat_stream_with_retry.await_count == 1
assert result.final_content == EMPTY_FINAL_RESPONSE_MESSAGE
assert result.stop_reason == "empty_final_response"
@@ -967,7 +795,7 @@ async def test_runner_does_not_auto_continue_goal_after_policy_terminal(
from nanobot.agent.runner import AgentRunner
provider = MagicMock(spec=LLMProvider)
provider.chat_with_retry = AsyncMock(return_value=LLMResponse(
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
content="Request blocked by provider policy.",
finish_reason=finish_reason,
))
@@ -986,7 +814,7 @@ async def test_runner_does_not_auto_continue_goal_after_policy_terminal(
terminal_injection_callback=terminal_injection_callback,
))
assert provider.chat_with_retry.await_count == 1
assert provider.chat_stream_with_retry.await_count == 1
terminal_injection_callback.assert_not_awaited()
assert result.final_content == "Request blocked by provider policy."
assert result.stop_reason == "completed"
@@ -1000,10 +828,10 @@ async def test_runner_uses_specific_message_after_empty_finalization_retry():
provider = MagicMock(spec=LLMProvider)
async def chat_with_retry(*, messages, **kwargs):
async def chat_stream_with_retry(*, messages, **kwargs):
return LLMResponse(content=None, tool_calls=[], usage=None)
provider.chat_with_retry = chat_with_retry
provider.chat_stream_with_retry = chat_stream_with_retry
tools = MagicMock()
tools.get_definitions.return_value = []
@@ -1040,7 +868,7 @@ async def test_empty_finalization_retry_discards_candidate_provider_state():
)
provider = MagicMock(spec=LLMProvider)
provider.can_resume_conversation_state.return_value = True
provider.chat_with_retry = AsyncMock(side_effect=[
provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content=None, tool_calls=[], usage=None),
LLMResponse(content=None, tool_calls=[], usage=None),
LLMResponse(
@@ -1076,7 +904,7 @@ async def test_runner_length_recovery_returns_all_segments():
from nanobot.agent.runner import AgentRunner
provider = MagicMock(spec=LLMProvider)
provider.chat_with_retry = AsyncMock(side_effect=[
provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content="first ", finish_reason="length"),
LLMResponse(content="second ", finish_reason="length"),
LLMResponse(content="third", finish_reason="stop"),
@@ -1099,7 +927,7 @@ async def test_runner_length_recovery_returns_all_segments():
for message in result.messages
if message.get("role") == "assistant"
] == ["first", "second", "third"]
assert provider.chat_with_retry.await_count == 3
assert provider.chat_stream_with_retry.await_count == 3
@pytest.mark.asyncio
@@ -1108,7 +936,7 @@ async def test_runner_length_recovery_preserves_prefix_at_max_iterations():
from nanobot.agent.runner import AgentRunner
provider = MagicMock(spec=LLMProvider)
provider.chat_with_retry = AsyncMock(
provider.chat_stream_with_retry = AsyncMock(
return_value=LLMResponse(content="partial answer", finish_reason="length")
)
tools = MagicMock()
@@ -1142,7 +970,7 @@ async def test_runner_length_recovery_does_not_leak_across_tool_calls():
from nanobot.agent.runner import AgentRunner
provider = MagicMock(spec=LLMProvider)
provider.chat_with_retry = AsyncMock(side_effect=[
provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content="working", finish_reason="length"),
LLMResponse(
content=None,
@@ -1180,7 +1008,7 @@ async def test_runner_empty_response_does_not_break_tool_chain():
provider = MagicMock(spec=LLMProvider)
call_count = 0
async def chat_with_retry(*, messages, tools=None, **kwargs):
async def chat_stream_with_retry(*, messages, tools=None, **kwargs):
nonlocal call_count
call_count += 1
if call_count == 1:
@@ -1203,8 +1031,7 @@ async def test_runner_empty_response_does_not_break_tool_chain():
usage=LLMUsage.reported(input_tokens=10, output_tokens=10),
)
provider.chat_with_retry = chat_with_retry
provider.chat_stream_with_retry = chat_with_retry
provider.chat_stream_with_retry = chat_stream_with_retry
async def fake_tool(name, args, **kw):
return "file content"
@@ -1236,7 +1063,7 @@ async def test_runner_accumulates_usage_and_preserves_cache_reads():
provider = MagicMock(spec=LLMProvider)
call_count = {"n": 0}
async def chat_with_retry(*, messages, **kwargs):
async def chat_stream_with_retry(*, messages, **kwargs):
call_count["n"] += 1
if call_count["n"] == 1:
return LLMResponse(
@@ -1250,7 +1077,7 @@ async def test_runner_accumulates_usage_and_preserves_cache_reads():
usage=LLMUsage.reported(input_tokens=200, output_tokens=20, cache_read_tokens=150),
)
provider.chat_with_retry = chat_with_retry
provider.chat_stream_with_retry = chat_stream_with_retry
tools = MagicMock()
tools.get_definitions.return_value = []
tools.execute = AsyncMock(return_value="file content")
@@ -1288,12 +1115,12 @@ async def test_runner_carries_retry_notifications_in_provider_context():
captured: dict = {}
async def chat_with_retry(**kwargs):
async def chat_stream_with_retry(**kwargs):
captured.update(kwargs)
return LLMResponse(content="done", tool_calls=[], usage=None)
provider = MagicMock(spec=LLMProvider)
provider.chat_with_retry = chat_with_retry
provider.chat_stream_with_retry = chat_stream_with_retry
tools = MagicMock()
tools.get_definitions.return_value = []
@@ -1325,17 +1152,17 @@ async def test_runner_carries_retry_notifications_in_provider_context():
@pytest.mark.asyncio
async def test_runner_passes_temperature_to_provider():
"""temperature from AgentRunSpec should reach provider.chat_with_retry."""
"""temperature from AgentRunSpec should reach provider.chat_stream_with_retry."""
from nanobot.agent.runner import AgentRunner
captured: dict = {}
async def chat_with_retry(**kwargs):
async def chat_stream_with_retry(**kwargs):
captured.update(kwargs)
return LLMResponse(content="done", tool_calls=[], usage=None)
provider = MagicMock(spec=LLMProvider)
provider.chat_with_retry = chat_with_retry
provider.chat_stream_with_retry = chat_stream_with_retry
tools = MagicMock()
tools.get_definitions.return_value = []
@@ -1354,17 +1181,17 @@ async def test_runner_passes_temperature_to_provider():
@pytest.mark.asyncio
async def test_runner_passes_max_tokens_to_provider():
"""max_tokens from AgentRunSpec should reach provider.chat_with_retry."""
"""max_tokens from AgentRunSpec should reach provider.chat_stream_with_retry."""
from nanobot.agent.runner import AgentRunner
captured: dict = {}
async def chat_with_retry(**kwargs):
async def chat_stream_with_retry(**kwargs):
captured.update(kwargs)
return LLMResponse(content="done", tool_calls=[], usage=None)
provider = MagicMock(spec=LLMProvider)
provider.chat_with_retry = chat_with_retry
provider.chat_stream_with_retry = chat_stream_with_retry
tools = MagicMock()
tools.get_definitions.return_value = []
@@ -1383,17 +1210,17 @@ async def test_runner_passes_max_tokens_to_provider():
@pytest.mark.asyncio
async def test_runner_passes_reasoning_effort_to_provider():
"""reasoning_effort from AgentRunSpec should reach provider.chat_with_retry."""
"""reasoning_effort from AgentRunSpec should reach provider.chat_stream_with_retry."""
from nanobot.agent.runner import AgentRunner
captured: dict = {}
async def chat_with_retry(**kwargs):
async def chat_stream_with_retry(**kwargs):
captured.update(kwargs)
return LLMResponse(content="done", tool_calls=[], usage=None)
provider = MagicMock(spec=LLMProvider)
provider.chat_with_retry = chat_with_retry
provider.chat_stream_with_retry = chat_stream_with_retry
tools = MagicMock()
tools.get_definitions.return_value = []