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

+1 -13
View File
@@ -78,10 +78,7 @@ from nanobot.security.workspace_access import (
)
from nanobot.session import turn_continuation
from nanobot.session.automation_turns import automation_history_overrides
from nanobot.session.goal_state import (
goal_state_runtime_lines,
runner_wall_llm_timeout_s,
)
from nanobot.session.goal_state import goal_state_runtime_lines
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
from nanobot.session.keys import UNIFIED_SESSION_KEY, remember_last_channel
from nanobot.session.manager import SESSION_CACHE_MAX_SIZE, Session, SessionManager
@@ -395,7 +392,6 @@ class AgentLoop:
disabled_skills=disabled_skills,
max_iterations=self.max_iterations,
max_concurrent_subagents=max_concurrent_subagents,
llm_wall_timeout_for_session=lambda sk: runner_wall_llm_timeout_s(self.sessions, sk),
)
self._unified_session = unified_session
self._running = False
@@ -1207,14 +1203,6 @@ class AgentLoop:
),
injection_callback=_drain_pending,
terminal_injection_callback=_wait_for_pending,
# Sustained goals may legitimately exceed NANOBOT_LLM_TIMEOUT_S; idle stall
# is still capped by NANOBOT_STREAM_IDLE_TIMEOUT_S in streaming providers.
llm_timeout_s=runner_wall_llm_timeout_s(
self.sessions,
session.key if session is not None else request_ctx.session_key,
metadata=session_metadata,
message_metadata=request_metadata,
),
continuation_callback=_goal_continue,
finalize_on_max_iterations=turn_continuation.should_finalize_on_max_iterations(
pending_queue_available=pending_queue is not None and session is not None,
+1 -1
View File
@@ -899,7 +899,7 @@ class MemoryArchiver:
try:
with llm_usage_source("dream"):
response = await runtime.provider.chat_with_retry(
response = await runtime.provider.chat_stream_with_retry(
model=runtime.model,
messages=request_messages,
tools=call_tools,
+4 -60
View File
@@ -4,7 +4,6 @@ from __future__ import annotations
import asyncio
import inspect
import os
import time
from collections.abc import Awaitable, Callable, Iterable
from copy import deepcopy
@@ -109,7 +108,6 @@ class AgentRunSpec:
consolidate_provider_compaction: ProviderCompactionConsolidator | None = None
injection_callback: InjectionCallback | None = None
terminal_injection_callback: InjectionCallback | None = None
llm_timeout_s: float | None = None
continuation_callback: ContinuationCallback | None = None
finalize_on_max_iterations: bool = True
provider_state: ProviderConversationState | None = None
@@ -873,7 +871,6 @@ class AgentRunner:
malformed_retry: bool = False,
transcript: list[dict[str, Any]] | None,
) -> tuple[LLMResponse, LLMUsage]:
timeout_s = self._resolve_llm_timeout_s(spec)
tool_definitions = spec.tools.get_definitions()
messages, provider_context = await self.context_governor.prepare_request(
request_state,
@@ -991,44 +988,19 @@ class AgentRunner:
on_stream_recover=_stream_recover,
)
else:
coro = spec.runtime.provider.chat_with_retry(
coro = spec.runtime.provider.chat_stream_with_retry(
**kwargs,
provider_context=provider_context,
)
# Streaming requests also have provider-level idle timeouts
# (NANOBOT_STREAM_IDLE_TIMEOUT_S), but a stream that keeps producing
# very slow deltas can still run forever. Use a more generous wall-clock
# timeout for streaming while preserving NANOBOT_LLM_TIMEOUT_S=0 as an
# opt-out for all LLM wall-clock timeouts.
outer_timeout_s = (
max(300.0, timeout_s * 2)
if wants_streaming and timeout_s is not None
else timeout_s
)
# Providers bound the wait for each stream event, including reasoning and tool deltas.
request_started_at = time.perf_counter()
try:
response = (
await coro if outer_timeout_s is None
else await asyncio.wait_for(coro, timeout=outer_timeout_s)
)
response = await coro
except asyncio.CancelledError:
_pause_generation()
await _close_native_reasoning()
raise
except asyncio.TimeoutError:
if outer_timeout_s is None:
response = LLMResponse(
content="Error calling LLM: stream stalled",
finish_reason="error",
error_kind="timeout",
)
else:
response = LLMResponse(
content=f"Error calling LLM: timed out after {outer_timeout_s:g}s",
finish_reason="error",
error_kind="timeout",
)
_pause_generation()
await _close_native_reasoning()
if first_output_at is not None:
@@ -1261,23 +1233,10 @@ class AgentRunner:
messages,
tools=None,
)
coro = spec.runtime.provider.chat_with_retry(
response = await spec.runtime.provider.chat_stream_with_retry(
**kwargs,
provider_context=provider_context,
)
timeout_s = self._resolve_llm_timeout_s(spec)
try:
response = (
await coro
if timeout_s is None
else await asyncio.wait_for(coro, timeout=timeout_s)
)
except asyncio.TimeoutError:
response = LLMResponse(
content=f"Error calling LLM: timed out after {timeout_s:g}s",
finish_reason="error",
error_kind="timeout",
)
await self.context_governor.summarize_provider_compaction(
request_state,
response,
@@ -1286,21 +1245,6 @@ class AgentRunner:
request_state.provider_compaction_applied |= response.provider_compaction_applied
return response
@staticmethod
def _resolve_llm_timeout_s(spec: AgentRunSpec) -> float | None:
"""Resolve the wall-clock limit shared by every model request path."""
timeout_s = spec.llm_timeout_s
if timeout_s is None:
# Default to a finite timeout to avoid per-session lock starvation when an LLM
# request hangs indefinitely (e.g. gateway/network stall).
# Set NANOBOT_LLM_TIMEOUT_S=0 to disable.
raw = os.environ.get("NANOBOT_LLM_TIMEOUT_S", "300").strip()
try:
timeout_s = float(raw)
except (TypeError, ValueError):
timeout_s = 300.0
return timeout_s if timeout_s > 0 else None
@staticmethod
def _budget_exhausted_finalization_messages(
messages: list[dict[str, Any]],
+1 -9
View File
@@ -8,7 +8,7 @@ import warnings
from collections.abc import Mapping
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Callable, NotRequired, TypedDict
from typing import Any, NotRequired, TypedDict
from loguru import logger
@@ -105,7 +105,6 @@ class SubagentManager:
disabled_skills: list[str] | None = None,
max_iterations: int | None = None,
max_concurrent_subagents: int | None = None,
llm_wall_timeout_for_session: Callable[[str | None], float | None] | None = None,
):
if workspace is None:
raise TypeError("SubagentManager.__init__() missing required argument: 'workspace'")
@@ -151,7 +150,6 @@ class SubagentManager:
self._run_slots = asyncio.Semaphore(self.max_concurrent_subagents)
self.runner = AgentRunner()
self._exec_session_manager = ExecSessionManager()
self._llm_wall_timeout_for_session = llm_wall_timeout_for_session
self._running_tasks: dict[str, asyncio.Task[str]] = {}
self._task_statuses: dict[str, SubagentStatus] = {}
self._session_tasks: dict[str, set[str]] = {} # session_key -> {task_id, ...}
@@ -417,11 +415,6 @@ class SubagentManager:
]
sess_key = origin.get("session_key")
llm_timeout = (
self._llm_wall_timeout_for_session(sess_key)
if self._llm_wall_timeout_for_session
else None
)
request_token = bind_request_context(RequestContext(
channel=origin["channel"],
chat_id=origin["chat_id"],
@@ -444,7 +437,6 @@ class SubagentManager:
checkpoint_callback=_on_checkpoint,
session_key=sess_key,
workspace=root,
llm_timeout_s=llm_timeout,
llm_usage_source=origin.get(
"llm_usage_source",
current_llm_usage_source(),