fix(retry): prevent replay amplification and isolate backoff (NAN-313)

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-29 11:13:44 +08:00
1 parent b6d9009bb4
commit 4e77d9c3f2
19 files changed
+1178 -587

No files matched your search

+134
View File
@@ -5,10 +5,12 @@ from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
import pytest
from loguru import logger
from mcp import types as mcp_types
from mcp.shared.exceptions import McpError
from mcp.types import ErrorData
from nanobot.agent.tools.context import RequestContext, request_context
from nanobot.agent.tools.mcp import (
MCPPromptWrapper,
MCPResourceWrapper,
@@ -491,3 +493,135 @@ async def test_prompt_reconnects_on_connection_closed_exception():
assert output == "fresh prompt"
assert old_session.get_prompt.call_count == 1
assert new_session.get_prompt.call_count == 1
async def test_tool_refresh_leaves_one_transient_retry_available():
old, fresh = AsyncMock(), AsyncMock()
old.call_tool.side_effect = ConnectionResetError("old")
fresh.call_tool.side_effect = [ConnectionResetError("fresh"), _make_tool_result("ok")]
wrapper = MCPToolWrapper(old, "srv", _make_tool_def())
reconnect = AsyncMock(return_value=MCPToolWrapper(fresh, "srv", _make_tool_def()))
wrapper.set_reconnect_handler(reconnect)
with patch("nanobot.agent.tools.mcp.asyncio.sleep", new_callable=AsyncMock) as sleep:
assert await wrapper.execute(value="unchanged") == "ok"
old.call_tool.assert_awaited_once_with("test_tool", arguments={"value": "unchanged"})
assert fresh.call_tool.await_count == 2
reconnect.assert_awaited_once_with("srv", wrapper.name, wrapper)
sleep.assert_awaited_once_with(1)
async def test_tool_later_refresh_does_not_reset_transient_budget():
old, fresh = AsyncMock(), AsyncMock()
old.call_tool.side_effect = [ConnectionResetError("first"), _session_terminated_error()]
fresh.call_tool.side_effect = ConnectionResetError("last")
wrapper = MCPToolWrapper(old, "srv", _make_tool_def())
replacement = MCPToolWrapper(fresh, "srv", _make_tool_def())
reconnect = AsyncMock(side_effect=[None, replacement])
wrapper.set_reconnect_handler(reconnect)
with patch("nanobot.agent.tools.mcp.asyncio.sleep", new_callable=AsyncMock) as sleep:
output = await wrapper.execute()
assert output == "(MCP tool call failed after retry: ConnectionResetError)"
assert is_tool_error_result(output)
assert (old.call_tool.await_count, fresh.call_tool.await_count) == (2, 1)
assert reconnect.await_count == 2
sleep.assert_awaited_once_with(1)
@pytest.mark.parametrize("phase", ["refresh", "backoff"])
async def test_tool_real_cancellation_during_recovery_propagates(phase):
entered, finished = asyncio.Event(), asyncio.Event()
async def block(*_args):
entered.set()
try:
await asyncio.Event().wait()
finally:
finished.set()
session = AsyncMock()
session.call_tool.side_effect = ConnectionResetError("gone")
wrapper = MCPToolWrapper(session, "srv", _make_tool_def())
if phase == "refresh":
wrapper.set_reconnect_handler(block)
with patch("nanobot.agent.tools.mcp.asyncio.sleep", side_effect=block):
task = asyncio.create_task(wrapper.execute())
try:
await asyncio.wait_for(entered.wait(), timeout=2)
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
finally:
if not task.done():
task.cancel()
await asyncio.gather(task, return_exceptions=True)
assert task.cancelled() and finished.is_set()
session.call_tool.assert_awaited_once()
async def test_tool_reconnect_failure_is_not_a_retryable_request_failure():
session = AsyncMock()
session.call_tool.side_effect = ConnectionResetError("request")
wrapper = MCPToolWrapper(session, "srv", _make_tool_def())
failure = ConnectionResetError("refresh")
reconnect = AsyncMock(side_effect=failure)
wrapper.set_reconnect_handler(reconnect)
with patch("nanobot.agent.tools.mcp.asyncio.sleep", new_callable=AsyncMock) as sleep:
with pytest.raises(ConnectionResetError) as raised:
await wrapper.execute()
assert raised.value is failure
session.call_tool.assert_awaited_once()
reconnect.assert_awaited_once()
sleep.assert_not_awaited()
async def test_tool_transient_render_failure_cannot_replay_a_successful_request():
session = AsyncMock()
session.call_tool.return_value = _make_tool_result("ok")
wrapper = MCPToolWrapper(session, "srv", _make_tool_def())
reconnect = AsyncMock()
wrapper.set_reconnect_handler(reconnect)
with (
patch.object(wrapper, "_render_call_result", side_effect=ConnectionResetError("Session terminated")),
patch("nanobot.agent.tools.mcp.asyncio.sleep", new_callable=AsyncMock) as sleep,
):
output = await wrapper.execute()
assert output == "(MCP tool returned malformed content: ConnectionResetError)"
assert is_tool_error_result(output)
session.call_tool.assert_awaited_once()
reconnect.assert_not_awaited()
sleep.assert_not_awaited()
@pytest.mark.parametrize("kind", ["tool", "prompt"])
async def test_request_error_logs_hide_content_and_prompt_retains_error_detail(kind):
session = AsyncMock()
if kind == "prompt":
session.get_prompt.side_effect = McpError(ErrorData(code=-32602, message="private-request-content"))
wrapper = MCPPromptWrapper(session, "srv", _make_prompt_def())
old = AsyncMock()
old.get_prompt.side_effect = _session_terminated_error()
stale = MCPPromptWrapper(old, "srv", _make_prompt_def())
stale.set_reconnect_handler(AsyncMock(return_value=wrapper))
wrapper = stale
expected = "(MCP prompt call failed: private-request-content [code -32602])"
else:
session.call_tool.side_effect = ValueError("private-request-content")
wrapper = MCPToolWrapper(session, "srv", _make_tool_def())
expected = "(MCP tool call failed: ValueError)"
records = []
sink = logger.add(lambda message: records.append(message.record), level="DEBUG")
try:
with request_context(RequestContext(channel="test", chat_id="test", log_content=False)):
output = await wrapper.execute()
finally:
logger.remove(sink)
assert output == expected
assert is_tool_error_result(output) is (kind == "tool")
error = next(record for record in records if record["level"].name == "ERROR")
assert "[content hidden]" in error["message"]
assert error["exception"] is None
assert all("private-request-content" not in record["message"] for record in records)
+11 -3
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
import asyncio
from typing import Any
from unittest.mock import AsyncMock, MagicMock, call, patch
from unittest.mock import AsyncMock, MagicMock, patch
import httpx
import pytest
@@ -476,7 +476,11 @@ class TestFallbackWhenPrimaryRaises:
assert result.content == "fallback ok"
assert result.finish_reason == "stop"
factory.assert_called_once_with(_fallback("fallback-a"))
assert sleep.await_args_list == [call(1), call(2), call(4)]
assert sleep.await_count == 3
assert all(
ceiling / 2 <= request.args[0] <= ceiling
for request, ceiling in zip(sleep.await_args_list, (1, 2, 4))
)
@pytest.mark.asyncio
async def test_authentication_exception_message_is_classified(self) -> None:
@@ -927,7 +931,11 @@ class TestFallbackOnPrimaryError:
assert result.content == "fallback ok"
assert fallback_models == ["fallback-b"]
assert sleep.await_args_list == [call(1), call(2), call(4)]
assert sleep.await_count == 3
assert all(
ceiling / 2 <= request.args[0] <= ceiling
for request, ceiling in zip(sleep.await_args_list, (1, 2, 4))
)
@pytest.mark.asyncio
@pytest.mark.parametrize(("provider_name", "status", "code", "kind", "expected"), [
@@ -244,3 +244,132 @@ async def test_dispatcher_shutdown_cleans_active_and_waiting_destination_tasks()
channel.send.assert_awaited_once()
assert not manager._outbound_tasks
assert not manager._outbound_tails
async def test_all_send_slots_in_backoff_leave_healthy_chat_and_fifo_live(monkeypatch):
monkeypatch.setattr(manager_module, "_SEND_RETRY_DELAYS", (0.6,))
manager, channel = make_manager()
failed = set()
delivered = []
async def send(msg):
if msg.chat_id != "healthy" and msg.chat_id not in failed:
failed.add(msg.chat_id)
raise OSError("temporary failure")
delivered.append((msg.chat_id, msg.content))
channel.send.side_effect = send
channel.should_retry_send_error.return_value = True
try:
for i in range(manager_module._OUTBOUND_CONCURRENCY):
await manager._queue_outbound(channel, OutboundMessage("websocket", str(i), "first"))
await wait_until(lambda: len(failed) == manager_module._OUTBOUND_CONCURRENCY)
await manager._queue_outbound(channel, OutboundMessage("websocket", "0", "last"))
await manager._queue_outbound(channel, OutboundMessage("websocket", "healthy", "ok"))
async with asyncio.timeout(0.2):
while ("healthy", "ok") not in delivered:
await asyncio.sleep(0)
assert ("0", "last") not in delivered
await wait_until(lambda: not manager._outbound_tasks)
assert [content for chat, content in delivered if chat == "0"] == ["first", "last"]
finally:
await manager._cancel_outbound()
assert not manager._outbound_tails
async def test_scheduled_cancel_waiting_for_permit_does_not_claim(tmp_path, monkeypatch):
from nanobot.bus.delivery import DeliveryRequest
monkeypatch.setattr(manager_module, "_OUTBOUND_CONCURRENCY", 1)
config = Config.model_validate({"channels": {"websocket": {"enabled": False}}})
manager = ChannelManager(config, MessageBus(), config_path=tmp_path / "config.json")
channel = MagicMock(spec=BaseChannel, send=AsyncMock())
manager.channels["websocket"] = channel
msg = OutboundMessage("websocket", "scheduled", "result",
delivery=DeliveryRequest("run", "websocket:scheduled", None))
manager._outbox.record(msg)
claim = MagicMock(wraps=manager._outbox.claim)
monkeypatch.setattr(manager._outbox, "claim", claim)
await manager._outbound_sends.acquire()
try:
await manager._queue_outbound(channel, msg)
await asyncio.sleep(0)
await manager._cancel_outbound()
claim.assert_not_called()
channel.send.assert_not_awaited()
assert [item.delivery_id for item in manager._outbox.ready()] == [msg.delivery_id]
assert not manager._scheduled_deliveries
finally:
manager._outbound_sends.release()
await manager._cancel_outbound()
async def test_restart_notice_does_not_outwait_send_permit_deadline(tmp_path):
from nanobot.utils.restart import RestartNotice
config = Config.model_validate({"channels": {"websocket": {"enabled": False}}})
manager = ChannelManager(config, MessageBus(), config_path=tmp_path / "config.json")
channel = MagicMock(spec=BaseChannel, is_running=True)
active = 0
release = asyncio.Event()
notices = []
async def send(msg):
nonlocal active
if msg.chat_id == "notice":
notices.append(msg)
return
active += 1
try:
await release.wait()
finally:
active -= 1
channel.send = AsyncMock(side_effect=send)
manager.channels["probe"] = channel
try:
for i in range(manager_module._OUTBOUND_CONCURRENCY):
await manager._queue_outbound(channel, OutboundMessage("probe", str(i), "blocked"))
await wait_until(lambda: active == manager_module._OUTBOUND_CONCURRENCY)
await asyncio.wait_for(manager._send_restart_notice_when_started(
RestartNotice(channel="probe", chat_id="notice", started_at_raw=""), timeout_s=0.05,
), 1)
assert notices == []
assert active == manager_module._OUTBOUND_CONCURRENCY
finally:
await manager._cancel_outbound()
assert active == 0
assert manager._outbound_sends._value == manager_module._OUTBOUND_CONCURRENCY
async def test_restart_notice_deadline_does_not_cancel_submitted_send(tmp_path):
from nanobot.utils.restart import RestartNotice
config = Config.model_validate({"channels": {"websocket": {"enabled": False}}})
manager = ChannelManager(config, MessageBus(), config_path=tmp_path / "config.json")
started = asyncio.Event()
release = asyncio.Event()
async def send(msg):
started.set()
await release.wait()
channel = MagicMock(spec=BaseChannel, is_running=True, send=AsyncMock(side_effect=send))
manager.channels["probe"] = channel
task = asyncio.create_task(manager._send_restart_notice_when_started(
RestartNotice(channel="probe", chat_id="notice", started_at_raw=""), timeout_s=0.05,
))
try:
await asyncio.wait_for(started.wait(), 1)
try:
await asyncio.wait_for(asyncio.shield(task), 0.1)
except TimeoutError:
pass
assert not task.done()
release.set()
await asyncio.wait_for(task, 1)
channel.send.assert_awaited_once()
assert manager._outbound_sends._value == manager_module._OUTBOUND_CONCURRENCY
finally:
task.cancel()
await asyncio.gather(task, return_exceptions=True)
+8
View File
@@ -2997,6 +2997,7 @@ async def test_send_with_retry_succeeds_first_try():
mgr.bus = MessageBus()
mgr.channels = {"failing": _FailingChannel(fake_config, mgr.bus)}
mgr._dispatch_task = None
mgr._outbound_sends = asyncio.Semaphore(32)
msg = OutboundMessage(channel="failing", chat_id="123", content="test")
await mgr._send_with_retry(mgr.channels["failing"], msg)
@@ -3034,6 +3035,7 @@ async def test_send_with_retry_retries_on_failure():
mgr.bus = MessageBus()
mgr.channels = {"failing": _FailingChannel(fake_config, mgr.bus)}
mgr._dispatch_task = None
mgr._outbound_sends = asyncio.Semaphore(32)
msg = OutboundMessage(channel="failing", chat_id="123", content="test")
@@ -3075,6 +3077,7 @@ async def test_send_with_retry_no_retry_when_max_is_zero():
mgr.bus = MessageBus()
mgr.channels = {"failing": _FailingChannel(fake_config, mgr.bus)}
mgr._dispatch_task = None
mgr._outbound_sends = asyncio.Semaphore(32)
msg = OutboundMessage(channel="failing", chat_id="123", content="test")
@@ -3125,6 +3128,7 @@ async def test_send_with_retry_calls_send_delta():
mgr.bus = MessageBus()
mgr.channels = {"streaming": _StreamingChannel(fake_config, mgr.bus)}
mgr._dispatch_task = None
mgr._outbound_sends = asyncio.Semaphore(32)
msg = outbound_message_for_event(
channel="streaming",
@@ -3193,6 +3197,7 @@ async def test_send_with_retry_skips_send_when_streamed():
mgr.bus = MessageBus()
mgr.channels = {"streamed": _StreamedChannel(fake_config, mgr.bus)}
mgr._dispatch_task = None
mgr._outbound_sends = asyncio.Semaphore(32)
msg = outbound_message_for_event(
channel="streamed",
@@ -3309,6 +3314,7 @@ async def test_send_with_retry_propagates_cancelled_error():
mgr.bus = MessageBus()
mgr.channels = {"cancelling": _CancellingChannel(fake_config, mgr.bus)}
mgr._dispatch_task = None
mgr._outbound_sends = asyncio.Semaphore(32)
msg = OutboundMessage(channel="cancelling", chat_id="123", content="test")
@@ -3346,6 +3352,7 @@ async def test_send_with_retry_propagates_cancelled_error_during_sleep():
mgr.bus = MessageBus()
mgr.channels = {"failing": _FailingChannel(fake_config, mgr.bus)}
mgr._dispatch_task = None
mgr._outbound_sends = asyncio.Semaphore(32)
msg = OutboundMessage(channel="failing", chat_id="123", content="test")
@@ -3837,6 +3844,7 @@ async def test_restart_notice_retries_until_running_channel_accepts_delivery():
mgr = ChannelManager.__new__(ChannelManager)
mgr.config = fake_config
mgr.bus = MessageBus()
mgr._outbound_sends = asyncio.Semaphore(32)
channel = _EventuallyDeliverableChannel(fake_config, mgr.bus)
channel._running = True
mgr.channels = {"discord": channel}
+127
View File
@@ -0,0 +1,127 @@
"""Reachable manager/adapter ownership contracts for outbound retries."""
import asyncio
import random
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
import pytest
# Telegram is an optional channel dependency, as in its adapter-owned suite.
pytest.importorskip("telegram")
from telegram.error import NetworkError, RetryAfter, TimedOut
from nanobot.bus.delivery import ChannelNotReadyError
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels import manager as manager_module
from nanobot.channels.manager import ChannelManager
from nanobot.channels.telegram import runtime as telegram_module
from nanobot.channels.telegram.runtime import (
TELEGRAM_MAX_MESSAGE_LEN,
TelegramChannel,
_split_telegram_markdown,
)
from nanobot.config.schema import Config
def make_manager(tmp_path):
config = Config.model_validate({"channels": {"websocket": {"enabled": False}}})
return ChannelManager(config, MessageBus(), config_path=tmp_path / "config.json")
def telegram_channel(manager):
channel = TelegramChannel({"token": "test", "rich_messages": False}, manager.bus)
channel._app = SimpleNamespace(bot=SimpleNamespace(send_message=AsyncMock()))
channel._app_ready.set()
return channel
async def test_telegram_exhausted_second_chunk_never_replays_successful_prefix(tmp_path, monkeypatch):
monkeypatch.setattr(manager_module, "_SEND_RETRY_DELAYS", (0,))
monkeypatch.setattr(telegram_module, "_SEND_RETRY_BASE_DELAY", 0)
manager = make_manager(tmp_path)
channel = telegram_channel(manager)
text = "a" * TELEGRAM_MAX_MESSAGE_LEN + "\n" + "b" * 20
chunks = _split_telegram_markdown(text, TELEGRAM_MAX_MESSAGE_LEN)
assert len(chunks) == 2
submitted = []
async def send_message(**kwargs):
submitted.append(kwargs["text"])
if kwargs["text"] != chunks[0]:
raise TimedOut("second part exhausted")
return SimpleNamespace(message_id=1)
channel._app.bot.send_message.side_effect = send_message
await manager._send_with_retry(channel, OutboundMessage("telegram", "1", text))
assert submitted == [chunks[0], chunks[1], chunks[1], chunks[1]]
@pytest.mark.parametrize(("error", "requests"), [
(TimedOut("timeout"), 3),
(RetryAfter(0), 3),
(NetworkError("ambiguous transport error"), 1),
(RuntimeError("unknown send result"), 1),
])
async def test_telegram_manager_does_not_multiply_part_retry_budget(tmp_path, monkeypatch, error, requests):
monkeypatch.setattr(manager_module, "_SEND_RETRY_DELAYS", (0,))
monkeypatch.setattr(telegram_module, "_SEND_RETRY_BASE_DELAY", 0)
manager = make_manager(tmp_path)
channel = telegram_channel(manager)
channel._app.bot.send_message.side_effect = error
await manager._send_with_retry(channel, OutboundMessage("telegram", "1", "result"))
assert channel._app.bot.send_message.await_count == requests
async def test_telegram_manager_retries_only_pre_submit_not_ready(tmp_path, monkeypatch):
monkeypatch.setattr(manager_module, "_SEND_RETRY_DELAYS", (0,))
manager = make_manager(tmp_path)
channel = telegram_channel(manager)
channel._wait_for_app = AsyncMock(side_effect=[None, channel._app])
await manager._send_with_retry(channel, OutboundMessage("telegram", "1", "result"))
assert channel._wait_for_app.await_count == 2
channel._app.bot.send_message.assert_awaited_once()
async def test_manager_equal_jitter_uses_capped_retry_delays(tmp_path, monkeypatch):
manager = make_manager(tmp_path)
manager.config.channels.send_max_retries = 6
channel = SimpleNamespace(send=AsyncMock(side_effect=OSError("offline")),
should_retry_send_error=Mock(return_value=True))
uniform = Mock(side_effect=lambda lower, upper: (lower + upper) / 2)
monkeypatch.setattr(random, "uniform", uniform)
sleep = AsyncMock()
monkeypatch.setattr(asyncio, "sleep", sleep)
await manager._send_with_retry(channel, OutboundMessage("test", "1", "result"))
assert [call.args for call in uniform.call_args_list] == [(0.5, 1), (1.0, 2), (2.0, 4), (2.0, 4), (2.0, 4)]
assert [call.args[0] for call in sleep.await_args_list] == [0.75, 1.5, 3, 3, 3]
async def test_manager_deadline_clamps_jitter_and_keeps_pre_submit_retry(tmp_path, monkeypatch):
manager = make_manager(tmp_path)
manager.config.channels.send_max_retries = 1
channel = SimpleNamespace(send=AsyncMock(side_effect=[ChannelNotReadyError("starting"), None]),
should_retry_send_error=Mock(return_value=True))
monkeypatch.setattr(manager_module, "_SEND_RETRY_DELAYS", (4,))
monkeypatch.setattr(random, "uniform", lambda lower, upper: upper)
sleep = AsyncMock()
monkeypatch.setattr(asyncio, "sleep", sleep)
await manager._send_with_retry(channel, OutboundMessage("test", "1", "result"),
deadline=asyncio.get_running_loop().time() + 2)
assert channel.send.await_count == 2
assert 0 < sleep.await_args.args[0] <= 2
async def test_telegram_restart_notice_deadline_never_replays_unknown_result(tmp_path):
from nanobot.utils.restart import RestartNotice
manager = make_manager(tmp_path)
channel = telegram_channel(manager)
channel._running = True
channel._app.bot.send_message.side_effect = NetworkError("unknown delivery")
manager.channels["telegram"] = channel
await manager._send_restart_notice_when_started(
RestartNotice(channel="telegram", chat_id="1", started_at_raw=""), timeout_s=0.1,
)
channel._app.bot.send_message.assert_awaited_once()
@@ -698,7 +698,8 @@ async def test_codex_retry_uses_structured_transient_error_metadata(monkeypatch,
assert response.content == "ok"
assert calls == 2
assert delays == [1]
assert len(delays) == 1
assert 0.5 <= delays[0] <= 1.0
@pytest.mark.asyncio
+108 -28
View File
@@ -1,5 +1,6 @@
import asyncio
import copy
import random
import pytest
@@ -14,6 +15,11 @@ from nanobot.providers.base import (
)
def assert_local_backoff(delays: list[float], ceilings: tuple[float, ...]) -> None:
assert len(delays) == len(ceilings)
assert all(ceiling / 2 <= delay <= ceiling for delay, ceiling in zip(delays, ceilings))
class ScriptedProvider(LLMProvider):
def __init__(self, responses):
super().__init__(provider_name="scripted")
@@ -64,9 +70,9 @@ async def test_chat_with_retry_retries_transient_error_then_succeeds(monkeypatch
LLMResponse(content="429 rate limit", finish_reason="error"),
LLMResponse(content="ok"),
])
delays: list[int] = []
delays: list[float] = []
async def _fake_sleep(delay: int) -> None:
async def _fake_sleep(delay: float) -> None:
delays.append(delay)
monkeypatch.setattr("nanobot.providers.base.asyncio.sleep", _fake_sleep)
@@ -76,7 +82,7 @@ async def test_chat_with_retry_retries_transient_error_then_succeeds(monkeypatch
assert response.finish_reason == "stop"
assert response.content == "ok"
assert provider.calls == 2
assert delays == [1]
assert_local_backoff(delays, (1,))
@pytest.mark.asyncio
@@ -156,9 +162,9 @@ async def test_chat_with_retry_does_not_retry_non_transient_error(monkeypatch) -
provider = ScriptedProvider([
LLMResponse(content="401 unauthorized", finish_reason="error"),
])
delays: list[int] = []
delays: list[float] = []
async def _fake_sleep(delay: int) -> None:
async def _fake_sleep(delay: float) -> None:
delays.append(delay)
monkeypatch.setattr("nanobot.providers.base.asyncio.sleep", _fake_sleep)
@@ -171,25 +177,37 @@ async def test_chat_with_retry_does_not_retry_non_transient_error(monkeypatch) -
@pytest.mark.asyncio
async def test_chat_with_retry_returns_final_error_after_retries(monkeypatch) -> None:
@pytest.mark.parametrize("fraction", [0.0, 1.0])
async def test_chat_with_retry_returns_final_error_after_retries(monkeypatch, fraction) -> None:
provider = ScriptedProvider([
LLMResponse(content="429 rate limit a", finish_reason="error"),
LLMResponse(content="429 rate limit b", finish_reason="error"),
LLMResponse(content="429 rate limit c", finish_reason="error"),
LLMResponse(content="503 final server error", finish_reason="error"),
])
delays: list[int] = []
delays: list[float] = []
statuses: list[RetryStatusEvent] = []
monkeypatch.setattr(random, "uniform", lambda low, high: low + (high - low) * fraction)
monkeypatch.setattr("nanobot.providers.base.time.time", lambda: 1000.0)
async def _fake_sleep(delay: int) -> None:
async def _fake_sleep(delay: float) -> None:
delays.append(delay)
monkeypatch.setattr("nanobot.providers.base.asyncio.sleep", _fake_sleep)
async def status(event: RetryStatusEvent) -> None:
statuses.append(event)
response = await provider.chat_with_retry(messages=[{"role": "user", "content": "hello"}])
monkeypatch.setattr("nanobot.providers.base.asyncio.sleep", _fake_sleep)
response = await provider.chat_with_retry(
messages=[{"role": "user", "content": "hello"}], on_retry_status=status,
)
assert response.content == "503 final server error"
assert provider.calls == 4
assert delays == [1, 2, 4]
assert delays == [base * (0.5 + fraction / 2) for base in (1, 2, 4)]
assert [event.next_retry_at for event in statuses if event.state == "waiting"] == [
1000.0 + delay for delay in delays
]
assert statuses[-1].state == "exhausted"
@pytest.mark.asyncio
@@ -207,7 +225,7 @@ async def test_chat_with_retry_emits_terminal_progress_when_standard_retries_exh
progress: list[str] = []
statuses: list[RetryStatusEvent] = []
async def _fake_sleep(delay: int) -> None:
async def _fake_sleep(delay: float) -> None:
return None
async def _progress(msg: str) -> None:
@@ -245,7 +263,7 @@ async def test_chat_with_retry_routes_terminal_progress_to_explicit_callback(mon
retry_progress: list[str] = []
terminal_progress: list[str] = []
async def _fake_sleep(delay: int) -> None:
async def _fake_sleep(delay: float) -> None:
return None
async def _retry_progress(msg: str) -> None:
@@ -284,9 +302,9 @@ async def test_chat_stream_with_retry_does_not_retry_after_emitting_content(monk
LLMResponse(content="ok"),
])
deltas: list[str] = []
delays: list[int] = []
delays: list[float] = []
async def _fake_sleep(delay: int) -> None:
async def _fake_sleep(delay: float) -> None:
delays.append(delay)
async def _on_delta(delta: str) -> None:
@@ -318,9 +336,9 @@ async def test_chat_stream_with_retry_retries_timeout_after_emitting_content(mon
LLMResponse(content="full retry response"),
])
deltas: list[str] = []
delays: list[int] = []
delays: list[float] = []
async def _fake_sleep(delay: int) -> None:
async def _fake_sleep(delay: float) -> None:
delays.append(delay)
async def _on_delta(delta: str) -> None:
@@ -337,7 +355,7 @@ async def test_chat_stream_with_retry_retries_timeout_after_emitting_content(mon
assert response.finish_reason == "stop"
assert provider.calls == 2
assert deltas == ["partial"]
assert delays == [1]
assert_local_backoff(delays, (1,))
assert provider.last_kwargs.get("on_content_delta") is None
@@ -356,9 +374,9 @@ async def test_chat_stream_with_retry_retries_timeout_in_new_stream_segment(
provider = ScriptedProvider([first, second])
deltas: list[str] = []
recoveries: list[str] = []
delays: list[int] = []
delays: list[float] = []
async def _fake_sleep(delay: int) -> None:
async def _fake_sleep(delay: float) -> None:
delays.append(delay)
async def _on_delta(delta: str) -> None:
@@ -380,7 +398,7 @@ async def test_chat_stream_with_retry_retries_timeout_in_new_stream_segment(
assert provider.calls == 2
assert deltas == ["partial", "full retry response"]
assert recoveries == ["recover"]
assert delays == [1]
assert_local_backoff(delays, (1,))
assert provider.last_kwargs.get("on_content_delta") is not None
@@ -633,7 +651,8 @@ async def test_image_fallback_without_meta_uses_default_placeholder() -> None:
@pytest.mark.asyncio
async def test_chat_with_retry_uses_retry_after_and_emits_wait_progress(monkeypatch) -> None:
@pytest.mark.parametrize("retry_mode", ["standard", "persistent"])
async def test_chat_with_retry_uses_retry_after_and_emits_wait_progress(monkeypatch, retry_mode) -> None:
provider = ScriptedProvider([
LLMResponse(content="429 rate limit, retry after 7s", finish_reason="error"),
LLMResponse(content="ok"),
@@ -641,17 +660,21 @@ async def test_chat_with_retry_uses_retry_after_and_emits_wait_progress(monkeypa
delays: list[float] = []
progress: list[str] = []
def unexpected_draw(*args):
pytest.fail("A provider-directed Retry-After must not be jittered")
async def _fake_sleep(delay: float) -> None:
delays.append(delay)
async def _progress(msg: str) -> None:
progress.append(msg)
monkeypatch.setattr(random, "uniform", unexpected_draw)
monkeypatch.setattr("nanobot.providers.base.asyncio.sleep", _fake_sleep)
response = await provider.chat_with_retry(
messages=[{"role": "user", "content": "hello"}],
on_retry_wait=_progress,
on_retry_wait=_progress, retry_mode=retry_mode,
)
assert response.content == "ok"
@@ -744,7 +767,7 @@ async def test_chat_with_retry_retries_structured_status_code_without_keyword(mo
assert response.content == "ok"
assert provider.calls == 2
assert delays == [1]
assert_local_backoff(delays, (1,))
@pytest.mark.asyncio
@@ -821,7 +844,7 @@ async def test_chat_with_retry_retries_structured_timeout_kind(monkeypatch) -> N
assert response.content == "ok"
assert provider.calls == 2
assert delays == [1]
assert_local_backoff(delays, (1,))
@pytest.mark.asyncio
@@ -891,7 +914,7 @@ async def test_persistent_retry_aborts_after_ten_identical_transient_errors(monk
assert response.finish_reason == "error"
assert response.content == "429 rate limit"
assert provider.calls == 10
assert delays == [1, 2, 4, 4, 4, 4, 4, 4, 4]
assert_local_backoff(delays, (1, 2, 4, 4, 4, 4, 4, 4, 4))
@pytest.mark.asyncio
@@ -963,7 +986,7 @@ async def test_chat_with_retry_retries_zhipu_1302_rate_limit(monkeypatch) -> Non
assert response.content == "ok"
assert provider.calls == 2
assert delays == [1]
assert_local_backoff(delays, (1,))
@pytest.mark.asyncio
@@ -989,7 +1012,7 @@ async def test_chat_with_retry_retries_zhipu_1302_with_429_status(monkeypatch) -
assert response.content == "ok"
assert provider.calls == 2
assert delays == [1]
assert_local_backoff(delays, (1,))
@pytest.mark.asyncio
@@ -1006,3 +1029,60 @@ async def test_chat_stream_with_retry_normalizes_explicit_none_max_tokens() -> N
assert response.content == "ok"
assert provider.last_kwargs["max_tokens"] == 4096
assert provider.last_kwargs["temperature"] == 0.7
async def test_concurrent_requests_keep_retry_status_and_attempts_local(monkeypatch) -> None:
ready = asyncio.Event()
calls = {"a": 0, "b": 0}
statuses = {"a": [], "b": []}
class ConcurrentProvider(ScriptedProvider):
async def chat(self, messages, **kwargs):
key = messages[-1]["content"]
calls[key] += 1
if calls[key] == 1:
if all(calls.values()):
ready.set()
await ready.wait()
return LLMResponse(content="connection failed", finish_reason="error")
return LLMResponse(content=key)
provider = ConcurrentProvider([])
monkeypatch.setattr(provider, "_CHAT_RETRY_DELAYS", (0.1,))
async def request(key):
async def status(event):
statuses[key].append((event.state, event.attempt, event.max_attempts))
return await provider.chat_with_retry(
messages=[{"role": "user", "content": key}], on_retry_status=status,
)
results = await asyncio.wait_for(asyncio.gather(request("a"), request("b")), 2)
assert [result.content for result in results] == ["a", "b"]
assert calls == {"a": 2, "b": 2}
assert statuses == {key: [("waiting", 1, 2), ("recovered", 2, 2)] for key in calls}
async def test_cancellation_interrupts_retry_wait_without_another_call() -> None:
provider = ScriptedProvider([LLMResponse(
content="rate limited", finish_reason="error", error_status_code=429, error_retry_after_s=120,
)])
waiting = asyncio.Event()
statuses = []
async def status(event):
statuses.append((event.state, event.attempt))
waiting.set()
task = asyncio.create_task(provider.chat_with_retry(messages=[], on_retry_status=status))
try:
await asyncio.wait_for(waiting.wait(), 2)
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
finally:
task.cancel()
await asyncio.gather(task, return_exceptions=True)
assert provider.calls == 1
assert statuses == [("waiting", 1)]
@@ -1,7 +1,10 @@
from unittest.mock import patch
import pytest
from nanobot.providers.anthropic_provider import AnthropicProvider
from nanobot.providers.azure_openai_provider import AzureOpenAIProvider
from nanobot.providers.bedrock_provider import BedrockProvider
from nanobot.providers.openai_compat_provider import OpenAICompatProvider
@@ -44,3 +47,13 @@ def test_azure_openai_disables_sdk_retries_by_default() -> None:
kwargs = mock_client.call_args.kwargs
assert kwargs["max_retries"] == 0
def test_bedrock_disables_sdk_retries_even_with_environment_attempts(monkeypatch) -> None:
pytest.importorskip("boto3")
monkeypatch.setenv("AWS_MAX_ATTEMPTS", "10")
with patch("boto3.Session") as session:
BedrockProvider(api_base="http://127.0.0.1:1", region="us-east-1")
config = session.return_value.client.call_args.kwargs["config"]
assert config.retries["total_max_attempts"] == 1
+152 -115
View File
@@ -2,6 +2,8 @@
from __future__ import annotations
import asyncio
import base64
import json
from pathlib import Path
from typing import Any
@@ -132,11 +134,14 @@ async def test_sse_error_event(audio_file: Path) -> None:
provider = StepFunTranscriptionProvider(api_key="sk-test")
stream_cm = _make_stream_cm(200, lines)
sleep = AsyncMock()
with patch("httpx.AsyncClient.stream", stream_cm):
with patch("httpx.AsyncClient.stream", stream_cm), patch("asyncio.sleep", sleep):
result = await provider.transcribe(audio_file)
assert result == ""
assert stream_cm.call_count == 1
sleep.assert_not_awaited()
@pytest.mark.asyncio
@@ -186,36 +191,78 @@ async def test_sse_malformed_json_skipped(audio_file: Path) -> None:
@pytest.mark.asyncio
async def test_retries_on_503_then_succeeds(audio_file: Path) -> None:
"""Transient 503 is retried, then a successful SSE stream yields text."""
success_lines = [
f"data: {json.dumps({'type': 'transcript.text.done', 'session_id': 's1', 'text': 'ok'})}",
]
# First call: 503 (FailingResponse), second call: success (FakeResponse with lines)
stream_cm = _make_stream_cm_sequence([503, success_lines])
@pytest.mark.parametrize(
"scenario,expected",
[
([(503, [], None), (200, [], None), (200, ["data: []"], None),
(200, ['data: {"type":"transcript.text.done","text":"ok"}'], None)], "ok"),
([(200, [], httpx.ReadError("lost")),
(200, ['data: {"type":"transcript.text.done","text":"ok"}'], None)], "ok"),
([(200, [], None)] * 4, ""),
([(200, ["data: []"], None)] * 4, ""),
],
ids=["mixed-budget", "read-error", "missing-final-exhaustion", "parser-exhaustion"],
)
async def test_sse_closes_each_attempt_before_backoff(monkeypatch, audio_file, scenario, expected):
original_audio = audio_file.read_bytes()
remaining = iter(scenario)
streams, bodies, waits = [], [], []
provider = StepFunTranscriptionProvider(api_key="sk-test")
with patch("httpx.AsyncClient.stream", stream_cm), patch(
"asyncio.sleep", AsyncMock()
):
result = await provider.transcribe(audio_file)
class Stream(httpx.AsyncByteStream):
closed = False
assert result == "ok"
def __init__(self, lines, error):
self.lines, self.error = lines, error
async def __aiter__(self):
for line in self.lines:
yield (line + "\n").encode()
if self.error is not None:
raise self.error
async def aclose(self):
self.closed = True
def handle(request):
bodies.append(json.loads(request.content))
status, lines, error = next(remaining)
stream = Stream(lines, error)
streams.append(stream)
return httpx.Response(status, stream=stream)
client = httpx.AsyncClient(transport=httpx.MockTransport(handle))
async def sleep(delay):
assert streams[-1].closed
waits.append(delay)
audio_file.write_bytes(b"changed-after-request")
monkeypatch.setattr("nanobot.providers.transcription.httpx.AsyncClient", lambda: client)
monkeypatch.setattr("nanobot.providers.transcription.asyncio.sleep", sleep)
result = await StepFunTranscriptionProvider(api_key="sk-test", language="zh").transcribe(audio_file)
assert result == expected
assert len(bodies) == len(scenario)
assert bodies == [bodies[0]] * len(scenario)
assert base64.b64decode(bodies[0]["audio"]["data"]) == original_audio
assert bodies[0]["audio"]["input"]["transcription"]["language"] == "zh"
assert waits == [1.0, 2.0, 4.0][:len(scenario) - 1]
assert all(stream.closed for stream in streams)
assert client.is_closed
@pytest.mark.asyncio
async def test_gives_up_after_max_retries(audio_file: Path) -> None:
"""Persistent 503 returns "" after all retries exhausted."""
attempts: list[list[str] | int] = [503, 503, 503, 503] # 4 failing HTTP responses
stream_cm = _make_stream_cm_sequence(attempts)
stream_cm = _make_stream_cm(503, [])
provider = StepFunTranscriptionProvider(api_key="sk-test")
with patch("httpx.AsyncClient.stream", stream_cm), patch(
"asyncio.sleep", AsyncMock()
):
sleep = AsyncMock()
with patch("httpx.AsyncClient.stream", stream_cm), patch("asyncio.sleep", sleep):
result = await provider.transcribe(audio_file)
assert result == ""
assert stream_cm.call_count == 4
assert [call.args[0] for call in sleep.await_args_list] == [1.0, 2.0, 4.0]
@pytest.mark.asyncio
@@ -229,18 +276,19 @@ async def test_sse_empty_text_done_returns_empty(audio_file: Path) -> None:
provider = StepFunTranscriptionProvider(api_key="sk-test")
stream_cm = _make_stream_cm(200, lines)
with patch("httpx.AsyncClient.stream", stream_cm), patch(
"asyncio.sleep", AsyncMock()
):
sleep = AsyncMock()
with patch("httpx.AsyncClient.stream", stream_cm), patch("asyncio.sleep", sleep):
result = await provider.transcribe(audio_file)
assert result == ""
assert stream_cm.call_count == 1
sleep.assert_not_awaited()
@pytest.mark.asyncio
async def test_401_returns_empty_without_retry(audio_file: Path) -> None:
"""401 is not retryable; bad credentials should fail immediately."""
stream_cm = _make_stream_cm(401, [])
@pytest.mark.parametrize("status", [401, 501])
async def test_non_retryable_status_returns_empty(audio_file: Path, status: int) -> None:
stream_cm = _make_stream_cm(status, [])
sleep = AsyncMock()
provider = StepFunTranscriptionProvider(api_key="sk-test")
@@ -258,32 +306,9 @@ async def test_retries_on_connect_error(audio_file: Path) -> None:
success_lines = [
f"data: {json.dumps({'type': 'transcript.text.done', 'session_id': 's1', 'text': 'ok'})}",
]
call_count = [0]
class FakeResponse:
"""Serves as both the async context manager returned by stream()
and the response object bound in `async with ... as resp`."""
status_code = 200
reason_phrase = "OK"
async def __aenter__(self) -> "FakeResponse":
return self
async def __aexit__(self, *exc: object) -> None:
pass
async def aiter_lines(self) -> Any:
for line in success_lines:
yield line
def raise_for_status(self) -> None:
pass
def fake_stream(method: str, url: str, *args: object, **kwargs: object) -> FakeResponse:
call_count[0] += 1
if call_count[0] == 1:
raise httpx.ConnectError("boom")
return FakeResponse()
fake_stream = MagicMock(side_effect=[
httpx.ConnectError("boom"), _make_stream_cm(200, success_lines).return_value,
])
provider = StepFunTranscriptionProvider(api_key="sk-test")
with patch("httpx.AsyncClient.stream", fake_stream), patch(
@@ -292,7 +317,82 @@ async def test_retries_on_connect_error(audio_file: Path) -> None:
result = await provider.transcribe(audio_file)
assert result == "ok"
assert call_count[0] == 2
assert fake_stream.call_count == 2
@pytest.mark.asyncio
@pytest.mark.parametrize("cancel_backoff", [False, True], ids=["recover", "cancel-backoff"])
async def test_unread_503_socket_closes_before_backoff(monkeypatch, audio_file, cancel_backoff):
first_closed, entered, blocked = asyncio.Event(), asyncio.Event(), asyncio.Event()
bodies, responses, waits = [], [], []
handlers = set()
async def handle(reader, writer):
handler = asyncio.current_task()
handlers.add(handler)
try:
head = await reader.readuntil(b"\r\n\r\n")
headers = dict(line.split(b":", 1) for line in head.split(b"\r\n")[1:] if b":" in line)
bodies.append(json.loads(await reader.readexactly(int(headers[b"Content-Length"]))))
first = len(bodies) == 1
if first:
# The body never finishes: the retry must close it without reading EOF.
writer.write(b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 1000000\r\n\r\nunread")
else:
payload = b'data: {"type":"transcript.text.done","text":"socket-ok"}\n\n'
writer.write(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: "
+ str(len(payload)).encode() + b"\r\n\r\n" + payload)
await writer.drain()
await reader.read()
if first:
first_closed.set()
finally:
writer.close()
await writer.wait_closed()
handlers.discard(handler)
async def response_received(response):
responses.append(response)
async def sleep(delay):
waits.append(delay)
assert responses[-1].is_closed
await asyncio.wait_for(first_closed.wait(), timeout=2)
entered.set()
if cancel_backoff:
await blocked.wait()
server = await asyncio.start_server(handle, "127.0.0.1", 0)
port = server.sockets[0].getsockname()[1]
client = httpx.AsyncClient(trust_env=False, event_hooks={"response": [response_received]})
monkeypatch.setattr("nanobot.providers.transcription.httpx.AsyncClient", lambda: client)
monkeypatch.setattr("nanobot.providers.transcription.asyncio.sleep", sleep)
task = asyncio.create_task(StepFunTranscriptionProvider(
api_key="local", api_base=f"http://127.0.0.1:{port}",
).transcribe(audio_file))
try:
await asyncio.wait_for(entered.wait(), timeout=5)
if cancel_backoff:
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert len(bodies) == 1
else:
assert await asyncio.wait_for(task, timeout=5) == "socket-ok"
assert len(bodies) == 2
assert bodies[0] == bodies[1]
assert waits == [1.0]
assert client.is_closed
finally:
task.cancel()
await asyncio.gather(task, return_exceptions=True)
await client.aclose()
server.close()
await server.wait_closed()
pending = list(handlers)
for handler in pending:
handler.cancel()
await asyncio.wait_for(asyncio.gather(*pending, return_exceptions=True), timeout=5)
# ---------------------------------------------------------------------------
@@ -362,66 +462,3 @@ def _make_stream_cm(status: int, lines: list[str]) -> MagicMock:
cm = MagicMock()
cm.return_value = FakeResponse()
return cm
def _make_stream_cm_sequence(statuses: list[str | int]) -> MagicMock:
"""Build a stream mock that fails with HTTP status ints, then succeeds with SSE lines.
Entries in *statuses* that are ints produce a stream that raises HTTPStatusError
after `raise_for_status()`. The final entry (a list of SSE lines) succeeds.
"""
remaining = list(statuses)
class FakeResponse:
def __init__(self, lines: list[str]) -> None:
self._lines = lines
self.status_code = 200
self.reason_phrase = "OK"
async def __aenter__(self) -> "FakeResponse":
return self
async def __aexit__(self, *exc: object) -> None:
pass
async def aiter_lines(self) -> Any:
for line in self._lines:
yield line
def raise_for_status(self) -> None:
pass
class FailingResponse:
def __init__(self, status: int) -> None:
self.status_code = status
self.reason_phrase = "Error"
async def __aenter__(self) -> "FailingResponse":
return self
async def __aexit__(self, *exc: object) -> None:
pass
async def aiter_lines(self) -> Any:
yield ""
return
def raise_for_status(self) -> None:
raise httpx.HTTPStatusError(
f"HTTP {self.status_code}",
request=httpx.Request("POST", "https://example.test"),
response=httpx.Response(self.status_code),
)
call_count = [0]
def _next(method: str, url: str, **kwargs: object) -> Any:
idx = min(call_count[0], len(remaining) - 1)
entry = remaining[idx]
call_count[0] += 1
if isinstance(entry, int):
return FailingResponse(entry)
return FakeResponse(entry)
cm = MagicMock(side_effect=_next)
return cm
+92 -39
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import asyncio
import base64
import os
from pathlib import Path
@@ -26,6 +27,7 @@ from nanobot.providers.transcription import (
GroqTranscriptionProvider,
OpenAITranscriptionProvider,
OpenRouterTranscriptionProvider,
StepFunTranscriptionProvider,
XiaomiMiMoTranscriptionProvider,
_audio_format,
_resolve_chat_completions_url,
@@ -419,40 +421,30 @@ def test_resolver_keeps_enabled_and_limits_on_effective_config() -> None:
@pytest.mark.asyncio
async def test_openai_does_not_retry_on_auth_error(audio_file: Path) -> None:
"""401 is the user's misconfiguration — retrying wastes time and rate-limit quota."""
@pytest.mark.parametrize("outcome", [_response(401), _response(501), httpx.LocalProtocolError("bad")])
async def test_openai_does_not_retry_terminal_errors(audio_file: Path, outcome) -> None:
provider = OpenAITranscriptionProvider(api_key="sk-test")
post = AsyncMock(return_value=_response(401, {"error": {"message": "bad key"}}))
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", AsyncMock()):
post = AsyncMock(side_effect=[outcome])
sleep = AsyncMock()
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", sleep):
result = await provider.transcribe(audio_file)
assert result == ""
assert post.await_count == 1
sleep.assert_not_awaited()
@pytest.mark.asyncio
async def test_openai_gives_up_after_max_attempts(audio_file: Path) -> None:
"""Persistent 503 returns "" after the final retry — never hangs."""
@pytest.mark.parametrize("outcome", [_response(503), httpx.ConnectError("offline")])
async def test_openai_gives_up_after_max_attempts(audio_file: Path, outcome) -> None:
provider = OpenAITranscriptionProvider(api_key="sk-test")
post = AsyncMock(return_value=_response(503))
post = AsyncMock(side_effect=[outcome] * 4)
sleep = AsyncMock()
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", sleep):
result = await provider.transcribe(audio_file)
assert result == ""
# 4 attempts total (initial + 3 retries) with 3 sleeps between them.
assert post.await_count == 4
assert sleep.await_count == 3
@pytest.mark.asyncio
async def test_openai_backoff_grows_exponentially(audio_file: Path) -> None:
"""Verify the backoff schedule is exponential (1s, 2s, 4s)."""
provider = OpenAITranscriptionProvider(api_key="sk-test")
post = AsyncMock(return_value=_response(503))
sleep = AsyncMock()
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", sleep):
await provider.transcribe(audio_file)
delays = [call.args[0] for call in sleep.await_args_list]
assert delays == [1.0, 2.0, 4.0]
assert [call.args[0] for call in sleep.await_args_list] == [1.0, 2.0, 4.0]
# ---------------------------------------------------------------------------
@@ -590,16 +582,33 @@ async def test_provider_forwards_file_mime_type(tmp_path: Path) -> None:
@pytest.mark.asyncio
async def test_language_survives_retry(audio_file: Path) -> None:
"""Regression: language must be present on every retry attempt, not just the first."""
provider = OpenAITranscriptionProvider(api_key="sk-test", language="ja")
post = AsyncMock(side_effect=[_response(503), _response(200, {"text": "konnichiwa"})])
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", AsyncMock()):
result = await provider.transcribe(audio_file)
assert result == "konnichiwa"
assert post.await_count == 2
@pytest.mark.parametrize("provider_cls", [OpenAITranscriptionProvider, OpenRouterTranscriptionProvider])
async def test_json_retry_shares_budget_and_rebuilds_cached_audio(audio_file: Path, provider_cls):
original_audio = audio_file.read_bytes()
provider = provider_cls(api_key="sk-test", model="contract-model", language="ja")
post = AsyncMock(side_effect=[
httpx.ReadError("lost"), _response(503), httpx.WriteError("lost"),
_response(200, {"text": "konnichiwa"}),
])
sleep = AsyncMock(side_effect=lambda _: audio_file.write_bytes(b"changed-after-request"))
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", sleep):
assert await provider.transcribe(audio_file) == "konnichiwa"
assert post.await_count == 4
assert [call.args[0] for call in sleep.await_args_list] == [1.0, 2.0, 4.0]
field = "files" if provider_cls is OpenAITranscriptionProvider else "json"
bodies = [call.kwargs[field] for call in post.await_args_list]
assert len({id(body) for body in bodies}) == 4
expected = (
{"file": (audio_file.name, original_audio, "audio/ogg"),
"model": (None, "contract-model"), "language": (None, "ja")}
if field == "files" else
{"model": "contract-model", "language": "ja",
"input_audio": {"data": base64.b64encode(original_audio).decode(), "format": "ogg"}}
)
assert bodies == [expected] * 4
for call in post.await_args_list:
assert call.kwargs["files"]["language"] == (None, "ja")
assert call.kwargs["headers"]["Authorization"] == "Bearer sk-test"
assert call.kwargs["timeout"] == 60.0
# ---------------------------------------------------------------------------
@@ -713,16 +722,6 @@ async def test_openrouter_omits_language_when_unset(audio_file: Path) -> None:
assert "language" not in post.await_args_list[0].kwargs["json"]
@pytest.mark.asyncio
async def test_openrouter_shares_retry_contract(audio_file: Path) -> None:
"""OpenRouter goes through the same retry helper: 503 retried, then 200."""
provider = OpenRouterTranscriptionProvider(api_key="k", model="openai/whisper-1")
post = AsyncMock(side_effect=[_response(503), _response(200, {"text": "recovered"})])
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", AsyncMock()):
assert await provider.transcribe(audio_file) == "recovered"
assert post.await_count == 2
def test_resolve_chat_completions_url_appends_path_to_base() -> None:
default = "https://api.xiaomimimo.com/v1/chat/completions"
assert _resolve_chat_completions_url(None, default) == default
@@ -971,6 +970,60 @@ async def test_retries_on_every_advertised_transient_exception(
assert post.await_count == 2
@pytest.mark.asyncio
@pytest.mark.parametrize("provider_cls", [OpenAITranscriptionProvider, StepFunTranscriptionProvider])
@pytest.mark.parametrize("phase", ["request", "stream", "sleep"])
async def test_transcription_cancellation_releases_client(monkeypatch, audio_file, provider_cls, phase):
entered, blocked = asyncio.Event(), asyncio.Event()
requests, streams, waits = [], [], []
class Stream(httpx.AsyncByteStream):
closed = False
async def __aiter__(self):
if phase == "stream":
entered.set()
await blocked.wait()
yield b""
async def aclose(self):
self.closed = True
async def handle(request):
requests.append(request)
if phase == "request":
entered.set()
await blocked.wait()
stream = Stream()
streams.append(stream)
return httpx.Response(200 if phase == "stream" else 503, stream=stream)
client = httpx.AsyncClient(transport=httpx.MockTransport(handle))
async def sleep(delay):
waits.append(delay)
assert streams[-1].closed
entered.set()
await blocked.wait()
monkeypatch.setattr("nanobot.providers.transcription.httpx.AsyncClient", lambda: client)
monkeypatch.setattr("nanobot.providers.transcription.asyncio.sleep", sleep)
task = asyncio.create_task(provider_cls(api_key="sk-test").transcribe(audio_file))
try:
await asyncio.wait_for(entered.wait(), timeout=5)
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert len(requests) == 1
assert all(stream.closed for stream in streams)
assert client.is_closed
assert waits == ([1.0] if phase == "sleep" else [])
finally:
task.cancel()
await asyncio.gather(task, return_exceptions=True)
await client.aclose()
# ---------------------------------------------------------------------------
# apiBase normalization (#3637): a chat-style base must not be POSTed verbatim
# ---------------------------------------------------------------------------
+77 -2
View File
@@ -1,5 +1,8 @@
"""Tests for multi-provider web search."""
import asyncio
from contextlib import asynccontextmanager
import httpx
import pytest
@@ -97,7 +100,9 @@ async def test_brave_search_retries_rate_limit_once(monkeypatch):
async def mock_get(self, url, **kw):
calls["n"] += 1
if calls["n"] == 1:
return _response(status=429, json={"error": "rate limit"})
response = _response(status=429, json={"error": "rate limit"})
response.headers["Retry-After"] = "3600"
return response
return _response(json={
"web": {"results": [{"title": "Recovered", "url": "https://example.com", "description": "ok"}]}
})
@@ -683,7 +688,9 @@ async def test_deepseek_search_retries_transient_errors_then_succeeds(
async def mock_post(self, url, **kw):
calls["n"] += 1
if calls["n"] == 1:
return _response(status=status, json={"error": {"message": "transient"}})
response = _response(status=status, json={"error": {"message": "transient"}})
response.headers["Retry-After"] = "3600"
return response
return _response(json={
"results": [{"title": "Recovered", "url": "https://example.com/ok", "snippet": "ok"}]
})
@@ -1396,3 +1403,71 @@ async def test_olostep_package_missing_returns_install_hint(monkeypatch):
assert result == (
"Error: Olostep support is not installed. Run `nanobot plugins enable olostep`."
)
@pytest.mark.parametrize("provider,outcome", [
("brave", 500),
("brave", httpx.ReadTimeout("slow")),
("deepseek", httpx.ConnectError("offline")),
])
async def test_search_does_not_retry_unclassified_failures(monkeypatch, provider, outcome):
calls = []
async def request(*args, **kwargs):
calls.append(args)
if isinstance(outcome, Exception):
raise outcome
return _response(status=outcome)
method = "get" if provider == "brave" else "post"
monkeypatch.setattr(httpx.AsyncClient, method, request)
result = await _tool(provider=provider, api_key="test-key").execute(query="failure")
assert is_tool_error_result(result)
assert len(calls) == 1
@pytest.mark.parametrize("provider", ["brave", "deepseek"])
@pytest.mark.parametrize("phase", ["request", "backoff"])
async def test_search_task_cancellation_closes_client_without_replay(monkeypatch, provider, phase):
entered, closed = asyncio.Event(), asyncio.Event()
calls = []
real_client = httpx.AsyncClient
async def block():
entered.set()
await asyncio.Event().wait()
async def handle(request):
calls.append(request)
if phase == "request":
await block()
return httpx.Response(429, json={})
@asynccontextmanager
async def client(**kwargs):
instance = real_client(transport=httpx.MockTransport(handle), **kwargs)
try:
async with instance:
yield instance
finally:
assert instance.is_closed
closed.set()
async def sleep(delay):
assert delay == 1.0
await block()
monkeypatch.setattr("nanobot.agent.tools.web.httpx.AsyncClient", client)
monkeypatch.setattr("nanobot.agent.tools.web.asyncio.sleep", sleep)
task = asyncio.create_task(_tool(provider=provider, api_key="test-key").execute(query="cancel"))
try:
await asyncio.wait_for(entered.wait(), timeout=2)
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
finally:
if not task.done():
task.cancel()
await asyncio.gather(task, return_exceptions=True)
assert len(calls) == 1
assert closed.is_set()