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
+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)],
|
||||
|
||||
Reference in new issue
Block a user