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

+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