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

@@ -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)