fix(retry): prevent replay amplification and isolate backoff (NAN-313)
This commit is contained in:
1 parent
b6d9009bb4
commit
4e77d9c3f2
19 files changed
+1178
-587
No files matched your search
+129
-213
@@ -12,7 +12,7 @@ import traceback
|
||||
import urllib.parse
|
||||
from collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Mapping
|
||||
from contextlib import AsyncExitStack, suppress
|
||||
from typing import TYPE_CHECKING, Any, Literal, Protocol, cast
|
||||
from typing import TYPE_CHECKING, Any, Literal, Protocol, TypeVar, cast
|
||||
|
||||
import httpx
|
||||
from loguru import logger
|
||||
@@ -62,6 +62,7 @@ _HTTP_READ_TIMEOUT = 300.0
|
||||
# Replace anything outside [a-zA-Z0-9_-] with underscore and collapse runs.
|
||||
_SANITIZE_RE = re.compile(r"_+")
|
||||
_ReconnectCallback = Callable[[str, str, Tool], Awaitable[Tool | None]]
|
||||
_MCPResultT = TypeVar("_MCPResultT")
|
||||
MCPServerLoader = Callable[[], tuple[Mapping[str, "MCPServerConfig"], NetworkConfig]]
|
||||
MCPRuntimeStatus = Literal["connecting", "connected", "failed"]
|
||||
|
||||
@@ -572,6 +573,75 @@ class _MCPWrapperBase(Tool):
|
||||
self._session = refreshed_session
|
||||
return True
|
||||
|
||||
async def _request_with_recovery(
|
||||
self,
|
||||
request: Callable[[], Awaitable[_MCPResultT]],
|
||||
timeout: float,
|
||||
capability_kind: Literal["tool", "resource", "prompt"],
|
||||
) -> _MCPResultT | ToolResult:
|
||||
"""Recover requests only; rendering and reconnect/backoff failures stay outside replay."""
|
||||
from mcp.shared.exceptions import McpError
|
||||
|
||||
operation = f"{capability_kind} {'read' if capability_kind == 'resource' else 'call'}"
|
||||
refreshed_session = False
|
||||
retried = False
|
||||
while True:
|
||||
try:
|
||||
return await asyncio.wait_for(request(), timeout=timeout)
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning(
|
||||
"MCP {} '{}' timed out after {}s", capability_kind, self._name, timeout
|
||||
)
|
||||
return ToolResult.error(f"(MCP {operation} timed out after {timeout}s)")
|
||||
except asyncio.CancelledError:
|
||||
# MCP SDK cancel scopes can leak cancellation without cancelling our task.
|
||||
if task_is_cancelling():
|
||||
raise
|
||||
logger.warning("MCP {} '{}' was cancelled by server/SDK", capability_kind, self._name)
|
||||
return ToolResult.error(f"(MCP {operation} was cancelled)")
|
||||
except Exception as exc:
|
||||
if await self._refresh_session_after_termination(
|
||||
exc, refreshed_session, capability_kind
|
||||
):
|
||||
refreshed_session = True
|
||||
continue
|
||||
if capability_kind == "prompt" and isinstance(exc, McpError):
|
||||
logger.opt(exception=exc if tool_log_content_allowed() else False).error(
|
||||
"MCP prompt '{}' failed: code={} message={}",
|
||||
self._name,
|
||||
exc.error.code,
|
||||
exc.error.message if tool_log_content_allowed() else "[content hidden]",
|
||||
)
|
||||
return ToolResult.error(
|
||||
f"(MCP prompt call failed: {exc.error.message} [code {exc.error.code}])"
|
||||
)
|
||||
if _is_transient(exc):
|
||||
if not retried:
|
||||
logger.warning(
|
||||
"MCP {} '{}' hit transient error ({}), retrying once...",
|
||||
capability_kind,
|
||||
self._name,
|
||||
type(exc).__name__,
|
||||
)
|
||||
retried = True
|
||||
await asyncio.sleep(1)
|
||||
continue
|
||||
logger.opt(exception=exc if tool_log_content_allowed() else False).error(
|
||||
"MCP {} '{}' failed after retry: {}",
|
||||
capability_kind,
|
||||
self._name,
|
||||
type(exc).__name__,
|
||||
)
|
||||
return ToolResult.error(f"(MCP {operation} failed after retry: {type(exc).__name__})")
|
||||
logger.opt(exception=exc if tool_log_content_allowed() else False).error(
|
||||
"MCP {} '{}' failed: {}: {}",
|
||||
capability_kind,
|
||||
self._name,
|
||||
type(exc).__name__,
|
||||
exc if tool_log_content_allowed() else "[content hidden]",
|
||||
)
|
||||
return ToolResult.error(f"(MCP {operation} failed: {type(exc).__name__})")
|
||||
|
||||
|
||||
def _image_block_data_url(block: Any, types: Any) -> str | None:
|
||||
"""Return a base64 ``data:`` URL for an MCP image-bearing content block.
|
||||
@@ -653,81 +723,29 @@ class MCPToolWrapper(_MCPWrapperBase):
|
||||
return self._parameters
|
||||
|
||||
async def execute(self, **kwargs: Any) -> str:
|
||||
retried_transient = False
|
||||
refreshed_session = False
|
||||
while True:
|
||||
try:
|
||||
result = await asyncio.wait_for(
|
||||
self._session.call_tool(self._original_name, arguments=kwargs),
|
||||
timeout=self._tool_timeout,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning(
|
||||
"MCP tool '{}' timed out after {}s", self._name, self._tool_timeout
|
||||
)
|
||||
return ToolResult.error(
|
||||
f"(MCP tool call timed out after {self._tool_timeout}s)"
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
# MCP SDK's anyio cancel scopes can leak CancelledError on timeout/failure.
|
||||
# Re-raise only if our task was externally cancelled (e.g. /stop).
|
||||
if task_is_cancelling():
|
||||
raise
|
||||
logger.warning("MCP tool '{}' was cancelled by server/SDK", self._name)
|
||||
return ToolResult.error("(MCP tool call was cancelled)")
|
||||
except Exception as exc:
|
||||
if await self._refresh_session_after_termination(
|
||||
exc,
|
||||
refreshed_session,
|
||||
"tool",
|
||||
):
|
||||
refreshed_session = True
|
||||
continue
|
||||
if _is_transient(exc):
|
||||
if not retried_transient:
|
||||
retried_transient = True
|
||||
logger.warning(
|
||||
"MCP tool '{}' hit transient error ({}), retrying once...",
|
||||
self._name,
|
||||
type(exc).__name__,
|
||||
)
|
||||
await asyncio.sleep(1) # Brief backoff before retry
|
||||
continue
|
||||
# Second transient failure — give up with retry-specific message
|
||||
logger.opt(exception=tool_log_content_allowed()).error(
|
||||
"MCP tool '{}' failed after retry: {}",
|
||||
self._name,
|
||||
type(exc).__name__,
|
||||
)
|
||||
return ToolResult.error(
|
||||
f"(MCP tool call failed after retry: {type(exc).__name__})"
|
||||
)
|
||||
logger.opt(exception=tool_log_content_allowed()).error(
|
||||
"MCP tool '{}' failed: {}: {}",
|
||||
self._name,
|
||||
type(exc).__name__,
|
||||
exc if tool_log_content_allowed() else "[content hidden]",
|
||||
)
|
||||
return ToolResult.error(
|
||||
f"(MCP tool call failed: {type(exc).__name__})"
|
||||
)
|
||||
else:
|
||||
# Success — extract text and persist any image content as artifacts.
|
||||
try:
|
||||
rendered = self._render_call_result(result.content, kwargs)
|
||||
if getattr(result, "isError", False):
|
||||
return ToolResult.error(rendered)
|
||||
return rendered
|
||||
except Exception as exc:
|
||||
logger.opt(exception=tool_log_content_allowed()).error(
|
||||
"MCP tool '{}' failed while rendering result: {}: {}",
|
||||
self._name,
|
||||
type(exc).__name__,
|
||||
exc if tool_log_content_allowed() else "[content hidden]",
|
||||
)
|
||||
return ToolResult.error(
|
||||
f"(MCP tool returned malformed content: {type(exc).__name__})"
|
||||
)
|
||||
result = await self._request_with_recovery(
|
||||
lambda: self._session.call_tool(self._original_name, arguments=kwargs),
|
||||
self._tool_timeout,
|
||||
"tool",
|
||||
)
|
||||
if isinstance(result, ToolResult):
|
||||
return result
|
||||
# Success — extract text and persist any image content as artifacts.
|
||||
try:
|
||||
rendered = self._render_call_result(result.content, kwargs)
|
||||
if getattr(result, "isError", False):
|
||||
return ToolResult.error(rendered)
|
||||
return rendered
|
||||
except Exception as exc:
|
||||
logger.opt(exception=tool_log_content_allowed()).error(
|
||||
"MCP tool '{}' failed while rendering result: {}: {}",
|
||||
self._name,
|
||||
type(exc).__name__,
|
||||
exc if tool_log_content_allowed() else "[content hidden]",
|
||||
)
|
||||
return ToolResult.error(
|
||||
f"(MCP tool returned malformed content: {type(exc).__name__})"
|
||||
)
|
||||
|
||||
def _render_call_result(self, content: Any, arguments: Mapping[str, Any]) -> str:
|
||||
"""Turn MCP content blocks into a tool result string.
|
||||
@@ -825,65 +843,22 @@ class MCPResourceWrapper(_MCPWrapperBase):
|
||||
async def execute(self, **kwargs: Any) -> str:
|
||||
from mcp import types
|
||||
|
||||
retried_transient = False
|
||||
refreshed_session = False
|
||||
while True:
|
||||
try:
|
||||
result = await asyncio.wait_for(
|
||||
self._session.read_resource(self._uri),
|
||||
timeout=self._resource_timeout,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning(
|
||||
"MCP resource '{}' timed out after {}s", self._name, self._resource_timeout
|
||||
)
|
||||
return f"(MCP resource read timed out after {self._resource_timeout}s)"
|
||||
except asyncio.CancelledError:
|
||||
if task_is_cancelling():
|
||||
raise
|
||||
logger.warning("MCP resource '{}' was cancelled by server/SDK", self._name)
|
||||
return "(MCP resource read was cancelled)"
|
||||
except Exception as exc:
|
||||
if await self._refresh_session_after_termination(
|
||||
exc,
|
||||
refreshed_session,
|
||||
"resource",
|
||||
):
|
||||
refreshed_session = True
|
||||
continue
|
||||
if _is_transient(exc):
|
||||
if not retried_transient:
|
||||
retried_transient = True
|
||||
logger.warning(
|
||||
"MCP resource '{}' hit transient error ({}), retrying once...",
|
||||
self._name,
|
||||
type(exc).__name__,
|
||||
)
|
||||
await asyncio.sleep(1)
|
||||
continue
|
||||
logger.opt(exception=tool_log_content_allowed()).error(
|
||||
"MCP resource '{}' failed after retry: {}",
|
||||
self._name,
|
||||
type(exc).__name__,
|
||||
)
|
||||
return f"(MCP resource read failed after retry: {type(exc).__name__})"
|
||||
logger.opt(exception=tool_log_content_allowed()).error(
|
||||
"MCP resource '{}' failed: {}: {}",
|
||||
self._name,
|
||||
type(exc).__name__,
|
||||
exc if tool_log_content_allowed() else "[content hidden]",
|
||||
)
|
||||
return f"(MCP resource read failed: {type(exc).__name__})"
|
||||
result = await self._request_with_recovery(
|
||||
lambda: self._session.read_resource(self._uri),
|
||||
self._resource_timeout,
|
||||
"resource",
|
||||
)
|
||||
if isinstance(result, ToolResult):
|
||||
return str(result)
|
||||
parts: list[str] = []
|
||||
for block in result.contents:
|
||||
if isinstance(block, types.TextResourceContents):
|
||||
parts.append(block.text)
|
||||
elif isinstance(cast(object, block), types.BlobResourceContents):
|
||||
parts.append(f"[Binary resource: {len(block.blob)} bytes]")
|
||||
else:
|
||||
parts: list[str] = []
|
||||
for block in result.contents:
|
||||
if isinstance(block, types.TextResourceContents):
|
||||
parts.append(block.text)
|
||||
elif isinstance(cast(object, block), types.BlobResourceContents):
|
||||
parts.append(f"[Binary resource: {len(block.blob)} bytes]")
|
||||
else:
|
||||
parts.append(str(block))
|
||||
return "\n".join(parts) or "(no output)"
|
||||
parts.append(str(block))
|
||||
return "\n".join(parts) or "(no output)"
|
||||
|
||||
|
||||
class MCPPromptWrapper(_MCPWrapperBase):
|
||||
@@ -942,87 +917,28 @@ class MCPPromptWrapper(_MCPWrapperBase):
|
||||
|
||||
async def execute(self, **kwargs: Any) -> str:
|
||||
from mcp import types
|
||||
from mcp.shared.exceptions import McpError
|
||||
|
||||
retried_transient = False
|
||||
refreshed_session = False
|
||||
while True:
|
||||
try:
|
||||
result = await asyncio.wait_for(
|
||||
self._session.get_prompt(self._prompt_name, arguments=kwargs),
|
||||
timeout=self._prompt_timeout,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning(
|
||||
"MCP prompt '{}' timed out after {}s", self._name, self._prompt_timeout
|
||||
)
|
||||
return f"(MCP prompt call timed out after {self._prompt_timeout}s)"
|
||||
except asyncio.CancelledError:
|
||||
if task_is_cancelling():
|
||||
raise
|
||||
logger.warning("MCP prompt '{}' was cancelled by server/SDK", self._name)
|
||||
return "(MCP prompt call was cancelled)"
|
||||
except McpError as exc:
|
||||
if await self._refresh_session_after_termination(
|
||||
exc,
|
||||
refreshed_session,
|
||||
"prompt",
|
||||
):
|
||||
refreshed_session = True
|
||||
continue
|
||||
logger.opt(exception=tool_log_content_allowed()).error(
|
||||
"MCP prompt '{}' failed: code={} message={}",
|
||||
self._name,
|
||||
exc.error.code,
|
||||
exc.error.message if tool_log_content_allowed() else "[content hidden]",
|
||||
)
|
||||
return f"(MCP prompt call failed: {exc.error.message} [code {exc.error.code}])"
|
||||
except Exception as exc:
|
||||
if await self._refresh_session_after_termination(
|
||||
exc,
|
||||
refreshed_session,
|
||||
"prompt",
|
||||
):
|
||||
refreshed_session = True
|
||||
continue
|
||||
if _is_transient(exc):
|
||||
if not retried_transient:
|
||||
retried_transient = True
|
||||
logger.warning(
|
||||
"MCP prompt '{}' hit transient error ({}), retrying once...",
|
||||
self._name,
|
||||
type(exc).__name__,
|
||||
)
|
||||
await asyncio.sleep(1)
|
||||
continue
|
||||
logger.opt(exception=tool_log_content_allowed()).error(
|
||||
"MCP prompt '{}' failed after retry: {}",
|
||||
self._name,
|
||||
type(exc).__name__,
|
||||
)
|
||||
return f"(MCP prompt call failed after retry: {type(exc).__name__})"
|
||||
logger.opt(exception=tool_log_content_allowed()).error(
|
||||
"MCP prompt '{}' failed: {}: {}",
|
||||
self._name,
|
||||
type(exc).__name__,
|
||||
exc if tool_log_content_allowed() else "[content hidden]",
|
||||
)
|
||||
return f"(MCP prompt call failed: {type(exc).__name__})"
|
||||
else:
|
||||
parts: list[str] = []
|
||||
for message in result.messages:
|
||||
content = message.content
|
||||
if isinstance(content, types.TextContent):
|
||||
parts.append(content.text)
|
||||
elif isinstance(content, list):
|
||||
for block in content:
|
||||
if isinstance(block, types.TextContent):
|
||||
parts.append(block.text)
|
||||
else:
|
||||
parts.append(str(block))
|
||||
result = await self._request_with_recovery(
|
||||
lambda: self._session.get_prompt(self._prompt_name, arguments=kwargs),
|
||||
self._prompt_timeout,
|
||||
"prompt",
|
||||
)
|
||||
if isinstance(result, ToolResult):
|
||||
return str(result)
|
||||
parts: list[str] = []
|
||||
for message in result.messages:
|
||||
content = message.content
|
||||
if isinstance(content, types.TextContent):
|
||||
parts.append(content.text)
|
||||
elif isinstance(content, list):
|
||||
for block in content:
|
||||
if isinstance(block, types.TextContent):
|
||||
parts.append(block.text)
|
||||
else:
|
||||
parts.append(str(content))
|
||||
return "\n".join(parts) or "(no output)"
|
||||
parts.append(str(block))
|
||||
else:
|
||||
parts.append(str(content))
|
||||
return "\n".join(parts) or "(no output)"
|
||||
|
||||
|
||||
async def connect_mcp_servers(
|
||||
|
||||
+26
-10
@@ -5,6 +5,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import hashlib
|
||||
import inspect
|
||||
import random
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Awaitable, Callable, Iterable, Mapping
|
||||
@@ -62,7 +63,7 @@ def _default_webui_dist() -> Path | None:
|
||||
return candidate if candidate.is_dir() else None
|
||||
|
||||
|
||||
# Retry delays for message sending (exponential backoff: 1s, 2s, 4s)
|
||||
# Upper bounds for local equal-jitter send backoff (1s, 2s, then 4s).
|
||||
_SEND_RETRY_DELAYS = (1, 2, 4)
|
||||
_OUTBOUND_CONCURRENCY = 32
|
||||
_OUTBOUND_PENDING_LIMIT = 256
|
||||
@@ -797,8 +798,8 @@ class ChannelManager:
|
||||
async def _queue_outbound(self, channel: BaseChannel, msg: OutboundMessage) -> None:
|
||||
"""Bound scheduled sends; preserve FIFO per destination, not across chats.
|
||||
|
||||
Retry waits occupy only their destination and one send slot. Saturation
|
||||
pauses dispatch rather than creating unbounded tasks or dropping messages.
|
||||
Retry waits retain their destination tail and admission, not a send permit.
|
||||
Saturation pauses dispatch rather than creating unbounded tasks or dropping messages.
|
||||
"""
|
||||
if msg.delivery_id in self._scheduled_deliveries:
|
||||
return
|
||||
@@ -816,11 +817,12 @@ class ChannelManager:
|
||||
async def send() -> None:
|
||||
if previous is not None:
|
||||
await asyncio.shield(asyncio.gather(previous, return_exceptions=True))
|
||||
async with self._outbound_sends:
|
||||
if msg.delivery_id is not None:
|
||||
if msg.delivery_id is not None:
|
||||
# Acquire before claiming: queued cancellation must remain pending.
|
||||
async with self._outbound_sends:
|
||||
await self._send_scheduled(channel, msg)
|
||||
else:
|
||||
await self._send_with_retry(channel, msg)
|
||||
else:
|
||||
await self._send_with_retry(channel, msg)
|
||||
|
||||
task = asyncio.create_task(send(), name=f"outbound-{msg.channel}-{msg.chat_id}")
|
||||
self._outbound_tasks[task] = key
|
||||
@@ -1168,9 +1170,22 @@ class ChannelManager:
|
||||
attempt = 0
|
||||
|
||||
while True:
|
||||
attempt += 1
|
||||
try:
|
||||
await self._send_once(channel, msg)
|
||||
async with asyncio.timeout_at(deadline):
|
||||
await self._outbound_sends.acquire()
|
||||
except TimeoutError:
|
||||
logger.warning("Send to {} deadline expired waiting for a send slot", msg.channel)
|
||||
return
|
||||
try:
|
||||
try:
|
||||
if deadline is not None and asyncio.get_running_loop().time() >= deadline:
|
||||
logger.warning("Send to {} deadline expired before submission", msg.channel)
|
||||
return
|
||||
attempt += 1
|
||||
# The deadline bounds admission, not an already-submitted send.
|
||||
await self._send_once(channel, msg)
|
||||
finally:
|
||||
self._outbound_sends.release()
|
||||
return # Send succeeded
|
||||
except asyncio.CancelledError:
|
||||
raise # Propagate cancellation for graceful shutdown
|
||||
@@ -1195,7 +1210,8 @@ class ChannelManager:
|
||||
msg.channel, attempt,
|
||||
)
|
||||
return
|
||||
delay = _SEND_RETRY_DELAYS[min(attempt - 1, len(_SEND_RETRY_DELAYS) - 1)]
|
||||
base = _SEND_RETRY_DELAYS[min(attempt - 1, len(_SEND_RETRY_DELAYS) - 1)]
|
||||
delay = random.uniform(base / 2, base)
|
||||
if deadline is not None:
|
||||
delay = min(delay, max(0.0, deadline - loop.time()))
|
||||
attempt_label = str(attempt)
|
||||
|
||||
@@ -1136,6 +1136,11 @@ class TelegramChannel(BaseChannel):
|
||||
buf.message_id = sent.message_id
|
||||
buf.draft_id = None
|
||||
|
||||
def should_retry_send_error(self, error: Exception) -> bool:
|
||||
# Per-part API retries belong to this adapter. Whole-message replay is safe
|
||||
# only before submission; otherwise it may duplicate a successful prefix.
|
||||
return isinstance(error, ChannelNotReadyError)
|
||||
|
||||
async def send(self, msg: OutboundMessage) -> None:
|
||||
"""Send a message through Telegram."""
|
||||
if isinstance(msg.event, ContextCompactionEvent) and not (
|
||||
|
||||
@@ -118,6 +118,7 @@ async def test_channel_manager_does_not_retry_permanent_weixin_error(monkeypatch
|
||||
manager = ChannelManager.__new__(ChannelManager)
|
||||
manager.config = Config.model_validate({"channels": {"sendMaxRetries": 3}})
|
||||
manager.bus = MessageBus()
|
||||
manager._outbound_sends = asyncio.Semaphore(32)
|
||||
channel = _channel()
|
||||
channel.send = AsyncMock(
|
||||
side_effect=WeixinAPIError(
|
||||
|
||||
@@ -667,6 +667,7 @@ def test_manager_retry_resumes_after_acknowledged_parts(
|
||||
monkeypatch.setattr("nanobot.channels.manager._SEND_RETRY_DELAYS", (0,))
|
||||
manager = object.__new__(ChannelManager)
|
||||
manager.config = Config()
|
||||
manager._outbound_sends = asyncio.Semaphore(32)
|
||||
message = OutboundMessage(channel=channel.name, chat_id="creator", content="A" * 4096 + "B")
|
||||
asyncio.run(manager._send_with_retry(channel, message))
|
||||
assert delivered == ["A" * 4096, "B"]
|
||||
@@ -764,6 +765,7 @@ def test_media_failure_never_replays_accepted_text_or_attachments(
|
||||
monkeypatch.setattr("nanobot.channels.manager._SEND_RETRY_DELAYS", (0,))
|
||||
manager = object.__new__(ChannelManager)
|
||||
manager.config = Config()
|
||||
manager._outbound_sends = asyncio.Semaphore(32)
|
||||
message = OutboundMessage(
|
||||
channel=channel.name, chat_id="creator", content="Files",
|
||||
media=[str(attachment), str(attachment)],
|
||||
|
||||
+105
-116
@@ -5,6 +5,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import time
|
||||
from abc import ABC, abstractmethod
|
||||
@@ -1590,34 +1591,29 @@ class LLMProvider(ABC):
|
||||
should_retry_guard: Callable[[], bool] | None = None,
|
||||
on_stream_recover: Callable[[], Awaitable[None]] | None = None,
|
||||
) -> LLMResponse:
|
||||
attempt = 0
|
||||
delays = list(self._CHAT_RETRY_DELAYS)
|
||||
response = await call(**kw)
|
||||
if response.finish_reason != "error":
|
||||
return response
|
||||
|
||||
attempt = 1
|
||||
delays = self._CHAT_RETRY_DELAYS
|
||||
persistent = retry_mode == "persistent"
|
||||
last_response: LLMResponse | None = None
|
||||
max_attempts = None if persistent else len(delays) + 1
|
||||
last_error_key: str | None = None
|
||||
identical_error_count = 0
|
||||
|
||||
async def _finish_retry_status(
|
||||
state: Literal["recovered", "cleared"],
|
||||
response: LLMResponse,
|
||||
state: Literal["recovered", "cleared", "exhausted"],
|
||||
result: LLMResponse,
|
||||
) -> None:
|
||||
if attempt > 1 and on_retry_status:
|
||||
await on_retry_status(
|
||||
RetryStatusEvent(
|
||||
state=state,
|
||||
attempt=attempt,
|
||||
max_attempts=None if persistent else len(delays) + 1,
|
||||
error_kind=self.public_error_kind(response),
|
||||
)
|
||||
)
|
||||
if on_retry_status and (attempt > 1 or state == "exhausted"):
|
||||
await on_retry_status(RetryStatusEvent(
|
||||
state=state,
|
||||
attempt=attempt,
|
||||
max_attempts=max_attempts,
|
||||
error_kind=self.public_error_kind(result),
|
||||
))
|
||||
|
||||
while True:
|
||||
attempt += 1
|
||||
response = await call(**kw)
|
||||
if response.finish_reason != "error":
|
||||
await _finish_retry_status("recovered", response)
|
||||
return response
|
||||
last_response = response
|
||||
if should_retry_guard is not None and not should_retry_guard():
|
||||
is_timeout = (response.error_kind or "").lower() == "timeout"
|
||||
if is_timeout:
|
||||
@@ -1632,7 +1628,6 @@ class LLMProvider(ABC):
|
||||
"LLM stream stalled after content was emitted; "
|
||||
"suppressing delta callbacks and retrying"
|
||||
)
|
||||
kw.setdefault("on_content_delta", None)
|
||||
kw["on_content_delta"] = None
|
||||
kw["on_thinking_delta"] = None
|
||||
kw["on_tool_call_delta"] = None
|
||||
@@ -1651,106 +1646,29 @@ class LLMProvider(ABC):
|
||||
identical_error_count = 1 if error_key else 0
|
||||
|
||||
if not self.is_transient_response(response):
|
||||
# Removing the user's images cannot repair account access.
|
||||
# Do not rebuild native provider state for an unrelated failure.
|
||||
if (
|
||||
(response.error_kind or "").lower() in {"authentication", "oauth_auth_required"}
|
||||
or response.error_status_code in {401, 403}
|
||||
or self.is_arrearage_response(response)
|
||||
):
|
||||
await _finish_retry_status("cleared", response)
|
||||
return response
|
||||
stripped = self._strip_image_content(kw["messages"])
|
||||
provider_context = kw.get("provider_context")
|
||||
stripped_context: ProviderCallContext | None = None
|
||||
if isinstance(provider_context, ProviderCallContext):
|
||||
state = provider_context.conversation_state
|
||||
if state is not None and (
|
||||
stripped is not None
|
||||
or self._strip_image_content(state.pending_messages) is not None
|
||||
or self._contains_image_content(state.payload)
|
||||
):
|
||||
# Provider-owned payloads may retain earlier input_image items.
|
||||
# Rebuild from the stripped public transcript for this retry.
|
||||
stripped_context = ProviderCallContext(
|
||||
context_window_tokens=(
|
||||
provider_context.context_window_tokens
|
||||
),
|
||||
session_id=provider_context.session_id,
|
||||
events=provider_context.events,
|
||||
response_preset=provider_context.response_preset,
|
||||
response_is_fallback=provider_context.response_is_fallback,
|
||||
)
|
||||
if stripped is not None or stripped_context is not None:
|
||||
logger.warning(
|
||||
"Non-transient LLM error with image content, retrying without images"
|
||||
)
|
||||
retry_kw = dict(kw)
|
||||
if stripped is not None:
|
||||
retry_kw["messages"] = stripped
|
||||
if stripped_context is not None:
|
||||
retry_kw["provider_context"] = stripped_context
|
||||
result = await call(**retry_kw)
|
||||
# Permanently strip images from the original messages so
|
||||
# subsequent iterations do not repeat the error-retry cycle.
|
||||
if result.finish_reason != "error":
|
||||
self._strip_image_content_inplace(original_messages)
|
||||
await _finish_retry_status(
|
||||
"recovered" if result.finish_reason != "error" else "cleared",
|
||||
result,
|
||||
)
|
||||
return result
|
||||
await _finish_retry_status("cleared", response)
|
||||
response = await self._retry_without_images(
|
||||
call, kw, original_messages, response,
|
||||
)
|
||||
await _finish_retry_status(
|
||||
"recovered" if response.finish_reason != "error" else "cleared",
|
||||
response,
|
||||
)
|
||||
return response
|
||||
|
||||
if persistent and identical_error_count >= self._PERSISTENT_IDENTICAL_ERROR_LIMIT:
|
||||
logger.warning(
|
||||
"Stopping persistent retry after {} identical transient errors: {}",
|
||||
identical_error_count,
|
||||
(response.content or "")[:120].lower(),
|
||||
)
|
||||
if on_retry_exhausted:
|
||||
await on_retry_exhausted(
|
||||
f"Persistent retry stopped after {identical_error_count} identical errors."
|
||||
)
|
||||
if on_retry_status:
|
||||
await on_retry_status(
|
||||
RetryStatusEvent(
|
||||
state="exhausted",
|
||||
attempt=attempt,
|
||||
max_attempts=None,
|
||||
error_kind=self.public_error_kind(response),
|
||||
)
|
||||
)
|
||||
return response
|
||||
|
||||
if not persistent and attempt > len(delays):
|
||||
logger.warning(
|
||||
"LLM request failed after {} attempts, giving up: {}",
|
||||
attempt,
|
||||
(response.content or "")[:120].lower(),
|
||||
)
|
||||
if on_retry_exhausted:
|
||||
await on_retry_exhausted(
|
||||
f"Model request failed after {attempt} attempts, giving up."
|
||||
)
|
||||
if on_retry_status:
|
||||
await on_retry_status(
|
||||
RetryStatusEvent(
|
||||
state="exhausted",
|
||||
attempt=attempt,
|
||||
max_attempts=len(delays) + 1,
|
||||
error_kind=self.public_error_kind(response),
|
||||
)
|
||||
)
|
||||
if (
|
||||
persistent and identical_error_count >= self._PERSISTENT_IDENTICAL_ERROR_LIMIT
|
||||
or not persistent and attempt > len(delays)
|
||||
):
|
||||
break
|
||||
|
||||
retry_after = self._extract_retry_after_from_response(response)
|
||||
base_delay = delays[min(attempt - 1, len(delays) - 1)]
|
||||
delay = retry_after + RETRY_AFTER_BUFFER if retry_after else base_delay
|
||||
delay = (
|
||||
retry_after + RETRY_AFTER_BUFFER
|
||||
if retry_after else random.uniform(base_delay / 2, base_delay)
|
||||
)
|
||||
if persistent:
|
||||
delay = min(delay, self._PERSISTENT_MAX_DELAY)
|
||||
|
||||
logger.warning(
|
||||
"LLM transient error (attempt {}{}), retrying in {}s: {}",
|
||||
attempt,
|
||||
@@ -1763,12 +1681,83 @@ class LLMProvider(ABC):
|
||||
attempt=attempt,
|
||||
persistent=persistent,
|
||||
error_kind=self.public_error_kind(response),
|
||||
max_attempts=None if persistent else len(delays) + 1,
|
||||
max_attempts=max_attempts,
|
||||
on_retry_wait=on_retry_wait,
|
||||
on_retry_status=on_retry_status,
|
||||
)
|
||||
attempt += 1
|
||||
response = await call(**kw)
|
||||
if response.finish_reason != "error":
|
||||
await _finish_retry_status("recovered", response)
|
||||
return response
|
||||
|
||||
return last_response if last_response is not None else await call(**kw) # pyright: ignore[reportUnnecessaryComparison]
|
||||
if persistent:
|
||||
logger.warning(
|
||||
"Stopping persistent retry after {} identical transient errors: {}",
|
||||
identical_error_count,
|
||||
(response.content or "")[:120].lower(),
|
||||
)
|
||||
exhausted_message = (
|
||||
f"Persistent retry stopped after {identical_error_count} identical errors."
|
||||
)
|
||||
else:
|
||||
logger.warning(
|
||||
"LLM request failed after {} attempts, giving up: {}",
|
||||
attempt,
|
||||
(response.content or "")[:120].lower(),
|
||||
)
|
||||
exhausted_message = f"Model request failed after {attempt} attempts, giving up."
|
||||
if on_retry_exhausted:
|
||||
await on_retry_exhausted(exhausted_message)
|
||||
await _finish_retry_status("exhausted", response)
|
||||
return response
|
||||
|
||||
async def _retry_without_images(
|
||||
self,
|
||||
call: Callable[..., Awaitable[LLMResponse]],
|
||||
kw: dict[str, Any],
|
||||
original_messages: list[dict[str, Any]],
|
||||
response: LLMResponse,
|
||||
) -> LLMResponse:
|
||||
"""Try image compatibility repair once, outside transient retries."""
|
||||
# Removing the user's images cannot repair account access.
|
||||
if (
|
||||
(response.error_kind or "").lower() in {"authentication", "oauth_auth_required"}
|
||||
or response.error_status_code in {401, 403}
|
||||
or self.is_arrearage_response(response)
|
||||
):
|
||||
return response
|
||||
stripped = self._strip_image_content(kw["messages"])
|
||||
provider_context = kw.get("provider_context")
|
||||
stripped_context: ProviderCallContext | None = None
|
||||
if isinstance(provider_context, ProviderCallContext):
|
||||
state = provider_context.conversation_state
|
||||
if state is not None and (
|
||||
stripped is not None
|
||||
or self._strip_image_content(state.pending_messages) is not None
|
||||
or self._contains_image_content(state.payload)
|
||||
):
|
||||
# Native payloads may retain images: rebuild from the public transcript.
|
||||
stripped_context = ProviderCallContext(
|
||||
context_window_tokens=provider_context.context_window_tokens,
|
||||
session_id=provider_context.session_id,
|
||||
events=provider_context.events,
|
||||
response_preset=provider_context.response_preset,
|
||||
response_is_fallback=provider_context.response_is_fallback,
|
||||
)
|
||||
if stripped is None and stripped_context is None:
|
||||
return response
|
||||
logger.warning("Non-transient LLM error with image content, retrying without images")
|
||||
retry_kw = dict(kw)
|
||||
if stripped is not None:
|
||||
retry_kw["messages"] = stripped
|
||||
if stripped_context is not None:
|
||||
retry_kw["provider_context"] = stripped_context
|
||||
result = await call(**retry_kw)
|
||||
# Keep later iterations from repeating the same image repair.
|
||||
if result.finish_reason != "error":
|
||||
self._strip_image_content_inplace(original_messages)
|
||||
return result
|
||||
|
||||
async def aclose(self) -> None:
|
||||
"""Close provider-owned transports after their active requests have stopped."""
|
||||
|
||||
@@ -90,7 +90,10 @@ class BedrockProvider(LLMProvider):
|
||||
|
||||
idle_timeout_s = resolve_stream_idle_timeout_s()
|
||||
client_kwargs: dict[str, Any] = {
|
||||
"config": Config(connect_timeout=idle_timeout_s, read_timeout=idle_timeout_s),
|
||||
"config": Config(
|
||||
connect_timeout=idle_timeout_s, read_timeout=idle_timeout_s,
|
||||
retries={"total_max_attempts": 1},
|
||||
),
|
||||
}
|
||||
if self.region:
|
||||
client_kwargs["region_name"] = self.region
|
||||
|
||||
@@ -350,77 +350,71 @@ async def _post_stepfun_asr_with_retry(
|
||||
}
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
async def request_once() -> str | None:
|
||||
# The entire stream closes before the owner decides whether to wait.
|
||||
async with client.stream(
|
||||
"POST", url, headers=headers, json=body, timeout=60.0
|
||||
) as resp:
|
||||
resp.raise_for_status()
|
||||
async for line in resp.aiter_lines():
|
||||
if not line.startswith("data:"):
|
||||
continue
|
||||
payload_str = line[len("data:") :].strip()
|
||||
if not payload_str:
|
||||
continue
|
||||
try:
|
||||
payload = json.loads(payload_str)
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
continue
|
||||
payload = cast(dict[str, Any], payload)
|
||||
event_type = payload.get("type", "")
|
||||
if event_type == "error":
|
||||
msg = payload.get("message", "unknown error")
|
||||
logger.error("{} ASR error: {}", provider_label, msg)
|
||||
return ""
|
||||
if event_type == "transcript.text.done":
|
||||
return payload.get("text", "")
|
||||
return None
|
||||
|
||||
for attempt in range(_MAX_RETRIES + 1):
|
||||
try:
|
||||
async with client.stream(
|
||||
"POST", url, headers=headers, json=body, timeout=60.0
|
||||
) as resp:
|
||||
if resp.status_code in _RETRYABLE_STATUS and attempt < _MAX_RETRIES:
|
||||
logger.warning(
|
||||
"{} transcription transient HTTP {} (attempt {}/{})",
|
||||
provider_label,
|
||||
resp.status_code,
|
||||
attempt + 1,
|
||||
_MAX_RETRIES + 1,
|
||||
)
|
||||
await asyncio.sleep(_BACKOFF_S[attempt])
|
||||
continue
|
||||
resp.raise_for_status()
|
||||
final_text = None
|
||||
async for line in resp.aiter_lines():
|
||||
if not line.startswith("data:"):
|
||||
continue
|
||||
payload_str = line[len("data:") :].strip()
|
||||
if not payload_str:
|
||||
continue
|
||||
try:
|
||||
payload = json.loads(payload_str)
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
continue
|
||||
payload = cast(dict[str, Any], payload)
|
||||
event_type = payload.get("type", "")
|
||||
if event_type == "error":
|
||||
msg = payload.get("message", "unknown error")
|
||||
logger.error("{} ASR error: {}", provider_label, msg)
|
||||
return ""
|
||||
if event_type == "transcript.text.done":
|
||||
final_text = payload.get("text", "")
|
||||
break
|
||||
if final_text is not None:
|
||||
return final_text
|
||||
# Stream ended without a final event — retry if attempts remain
|
||||
if attempt < _MAX_RETRIES:
|
||||
logger.warning(
|
||||
"{} transcription: no final event (attempt {}/{})",
|
||||
provider_label,
|
||||
attempt + 1,
|
||||
_MAX_RETRIES + 1,
|
||||
)
|
||||
await asyncio.sleep(_BACKOFF_S[attempt])
|
||||
continue
|
||||
final_text = await request_once()
|
||||
if final_text is not None:
|
||||
return final_text
|
||||
if attempt == _MAX_RETRIES:
|
||||
logger.error(
|
||||
"{} transcription: stream ended without final text after {} attempts",
|
||||
provider_label,
|
||||
_MAX_RETRIES + 1,
|
||||
)
|
||||
return ""
|
||||
logger.warning(
|
||||
"{} transcription: no final event (attempt {}/{})",
|
||||
provider_label,
|
||||
attempt + 1,
|
||||
_MAX_RETRIES + 1,
|
||||
)
|
||||
except httpx.HTTPStatusError as e:
|
||||
if e.response.status_code in _RETRYABLE_STATUS and attempt < _MAX_RETRIES:
|
||||
await asyncio.sleep(_BACKOFF_S[attempt])
|
||||
continue
|
||||
logger.error(
|
||||
"{} transcription HTTP {}{}",
|
||||
if e.response.status_code not in _RETRYABLE_STATUS or attempt == _MAX_RETRIES:
|
||||
logger.error(
|
||||
"{} transcription HTTP {}{}",
|
||||
provider_label,
|
||||
e.response.status_code,
|
||||
f" {e.response.reason_phrase}" if e.response.reason_phrase else "",
|
||||
)
|
||||
return ""
|
||||
logger.warning(
|
||||
"{} transcription transient HTTP {} (attempt {}/{})",
|
||||
provider_label,
|
||||
e.response.status_code,
|
||||
f" {e.response.reason_phrase}" if e.response.reason_phrase else "",
|
||||
attempt + 1,
|
||||
_MAX_RETRIES + 1,
|
||||
)
|
||||
return ""
|
||||
except (httpx.RequestError, Exception):
|
||||
if attempt < _MAX_RETRIES:
|
||||
await asyncio.sleep(_BACKOFF_S[attempt])
|
||||
continue
|
||||
logger.exception("{} transcription request error", provider_label)
|
||||
return ""
|
||||
except Exception:
|
||||
if attempt == _MAX_RETRIES:
|
||||
logger.exception("{} transcription request error", provider_label)
|
||||
return ""
|
||||
await asyncio.sleep(_BACKOFF_S[attempt])
|
||||
return ""
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user