refactor(events): unify scoped runtime notifications across clients (#5670)
* refactor(events): unify scoped runtime notifications across clients * style(tests): sort auto-compaction event imports * refactor(events): scope connections and remove retry callback plumbing * docs: remove runtime notification design write-up * refactor(bus): route operation events through the message bus * fix(channels): isolate outbound sends by destination * style(events): group shared notification imports * refactor(events): converge runtime and hook delivery on MessageBus * test(events): migrate fixtures to unified message bus
This commit is contained in:
1 parent
3495281282
commit
192e2e90dc
78 files changed
+1620
-1194
No files matched your search
@@ -0,0 +1,187 @@
|
||||
import asyncio
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels import manager as manager_module
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
from nanobot.config.schema import Config
|
||||
|
||||
|
||||
def make_manager():
|
||||
config = Config.model_validate({"channels": {"websocket": {"enabled": False}}})
|
||||
manager = ChannelManager(config, MessageBus())
|
||||
channel = MagicMock(spec=BaseChannel)
|
||||
channel.send = AsyncMock()
|
||||
channel.stop = AsyncMock()
|
||||
manager.channels["websocket"] = channel
|
||||
return manager, channel
|
||||
|
||||
|
||||
async def wait_until(predicate):
|
||||
async with asyncio.timeout(2):
|
||||
while not predicate():
|
||||
await asyncio.sleep(0)
|
||||
|
||||
|
||||
async def test_ten_chats_keep_order_while_one_destination_is_blocked():
|
||||
manager, channel = make_manager()
|
||||
release = asyncio.Event()
|
||||
started = asyncio.Event()
|
||||
received = {str(i): [] for i in range(10)}
|
||||
|
||||
async def send(msg):
|
||||
if msg.chat_id == "0":
|
||||
started.set()
|
||||
await release.wait()
|
||||
received[msg.chat_id].append(msg.content)
|
||||
|
||||
channel.send.side_effect = send
|
||||
manager._dispatch_task = asyncio.create_task(manager._dispatch_outbound())
|
||||
try:
|
||||
for content in ("first", "last"):
|
||||
for i in range(10):
|
||||
await manager.bus.publish_outbound(OutboundMessage("websocket", str(i), content))
|
||||
await asyncio.wait_for(started.wait(), 2)
|
||||
await wait_until(lambda: all(len(received[str(i)]) == 2 for i in range(1, 10)))
|
||||
assert received["0"] == []
|
||||
assert all(received[str(i)] == ["first", "last"] for i in range(1, 10))
|
||||
release.set()
|
||||
await wait_until(lambda: not manager._outbound_tasks)
|
||||
assert received["0"] == ["first", "last"]
|
||||
assert manager._outbound_tails == {}
|
||||
finally:
|
||||
await manager.stop_all()
|
||||
|
||||
|
||||
async def test_retry_does_not_block_other_chats(monkeypatch):
|
||||
monkeypatch.setattr(manager_module, "_SEND_RETRY_DELAYS", (0.1,))
|
||||
manager, channel = make_manager()
|
||||
retry_started = asyncio.Event()
|
||||
healthy_sent = asyncio.Event()
|
||||
attempts = 0
|
||||
|
||||
async def send(msg):
|
||||
nonlocal attempts
|
||||
if msg.chat_id == "retry":
|
||||
attempts += 1
|
||||
if attempts == 1:
|
||||
retry_started.set()
|
||||
raise OSError("temporary failure")
|
||||
assert healthy_sent.is_set()
|
||||
else:
|
||||
healthy_sent.set()
|
||||
|
||||
channel.send.side_effect = send
|
||||
channel.should_retry_send_error.return_value = True
|
||||
try:
|
||||
await manager._queue_outbound(channel, OutboundMessage("websocket", "retry", "a"))
|
||||
await asyncio.wait_for(retry_started.wait(), 2)
|
||||
await manager._queue_outbound(channel, OutboundMessage("websocket", "healthy", "b"))
|
||||
await wait_until(lambda: not manager._outbound_tasks)
|
||||
assert attempts == 2
|
||||
assert healthy_sent.is_set()
|
||||
finally:
|
||||
await manager._cancel_outbound()
|
||||
|
||||
|
||||
async def test_pending_and_concurrent_sends_are_bounded_and_cancellable(monkeypatch):
|
||||
monkeypatch.setattr(manager_module, "_OUTBOUND_PENDING_LIMIT", 4)
|
||||
monkeypatch.setattr(manager_module, "_OUTBOUND_CONCURRENCY", 2)
|
||||
manager, channel = make_manager()
|
||||
blocked = asyncio.Event()
|
||||
active = 0
|
||||
peak = 0
|
||||
|
||||
async def send(msg):
|
||||
nonlocal active, peak
|
||||
active += 1
|
||||
peak = max(peak, active)
|
||||
try:
|
||||
await blocked.wait()
|
||||
finally:
|
||||
active -= 1
|
||||
|
||||
channel.send.side_effect = send
|
||||
for i in range(4):
|
||||
await manager._queue_outbound(channel, OutboundMessage("websocket", str(i), "a"))
|
||||
extra = asyncio.create_task(manager._queue_outbound(
|
||||
channel, OutboundMessage("websocket", "extra", "a"),
|
||||
))
|
||||
try:
|
||||
await wait_until(lambda: active == 2)
|
||||
assert not extra.done()
|
||||
assert len(manager._outbound_tasks) == 4
|
||||
extra.cancel()
|
||||
await asyncio.gather(extra, return_exceptions=True)
|
||||
await manager._cancel_outbound()
|
||||
assert peak == 2
|
||||
assert active == 0
|
||||
assert not manager._outbound_tasks
|
||||
assert not manager._outbound_tails
|
||||
# Cancellation returns admission permits, including tasks not yet sending.
|
||||
for i in range(4):
|
||||
await asyncio.wait_for(manager._queue_outbound(
|
||||
channel, OutboundMessage("websocket", str(i), "b"),
|
||||
), 2)
|
||||
finally:
|
||||
extra.cancel()
|
||||
await asyncio.gather(extra, return_exceptions=True)
|
||||
await manager._cancel_outbound()
|
||||
|
||||
|
||||
async def test_channel_stop_cancels_only_its_sends_before_stopping_runtime():
|
||||
manager, channel = make_manager()
|
||||
active = asyncio.Event()
|
||||
cancelled = asyncio.Event()
|
||||
|
||||
async def send(msg):
|
||||
active.set()
|
||||
try:
|
||||
await asyncio.Event().wait()
|
||||
finally:
|
||||
cancelled.set()
|
||||
|
||||
async def stop():
|
||||
assert cancelled.is_set()
|
||||
|
||||
channel.send.side_effect = send
|
||||
channel.stop.side_effect = stop
|
||||
other = MagicMock(spec=BaseChannel)
|
||||
other.send = AsyncMock()
|
||||
manager.channels["other"] = other
|
||||
await manager._queue_outbound(channel, OutboundMessage("websocket", "a", "1"))
|
||||
await asyncio.wait_for(active.wait(), 2)
|
||||
await manager._stop_channel("websocket")
|
||||
await manager._queue_outbound(other, OutboundMessage("other", "b", "2"))
|
||||
await wait_until(lambda: not manager._outbound_tasks)
|
||||
other.send.assert_awaited_once()
|
||||
assert not manager._outbound_tails
|
||||
|
||||
|
||||
async def test_dispatcher_shutdown_cleans_active_and_waiting_destination_tasks():
|
||||
manager, channel = make_manager()
|
||||
active = asyncio.Event()
|
||||
cancelled = asyncio.Event()
|
||||
|
||||
async def send(msg):
|
||||
active.set()
|
||||
try:
|
||||
await asyncio.Event().wait()
|
||||
finally:
|
||||
cancelled.set()
|
||||
|
||||
channel.send.side_effect = send
|
||||
manager._dispatch_task = asyncio.create_task(manager._dispatch_outbound())
|
||||
try:
|
||||
for content in ("one", "two", "three"):
|
||||
await manager.bus.publish_outbound(OutboundMessage("websocket", "chat", content))
|
||||
await asyncio.wait_for(active.wait(), 2)
|
||||
await wait_until(lambda: len(manager._outbound_tasks) == 3)
|
||||
finally:
|
||||
await manager.stop_all()
|
||||
assert cancelled.is_set()
|
||||
channel.send.assert_awaited_once()
|
||||
assert not manager._outbound_tasks
|
||||
assert not manager._outbound_tails
|
||||
@@ -11,7 +11,6 @@ from nanobot.bus.outbound_events import (
|
||||
RetryWaitEvent,
|
||||
StreamDeltaEvent,
|
||||
StreamEndEvent,
|
||||
outbound_event_from_message,
|
||||
outbound_message_for_event,
|
||||
)
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -120,13 +119,13 @@ class TestDeltaCoalescing:
|
||||
async def process_one():
|
||||
try:
|
||||
m = await asyncio.wait_for(bus.consume_outbound(), timeout=0.1)
|
||||
event = outbound_event_from_message(m)
|
||||
event = m.event
|
||||
if isinstance(event, StreamDeltaEvent):
|
||||
m, pending = manager._coalesce_stream_deltas(m)
|
||||
for p in pending:
|
||||
await bus.publish_outbound(p)
|
||||
channel = manager.channels.get(m.channel)
|
||||
event = outbound_event_from_message(m)
|
||||
event = m.event
|
||||
if channel and isinstance(event, StreamDeltaEvent):
|
||||
await channel.send_delta(
|
||||
m.chat_id,
|
||||
@@ -274,13 +273,13 @@ class TestDispatchOutboundWithCoalescing:
|
||||
processed = []
|
||||
|
||||
msg = pending.pop(0) if pending else await bus.consume_outbound()
|
||||
event = outbound_event_from_message(msg)
|
||||
event = msg.event
|
||||
if isinstance(event, StreamDeltaEvent):
|
||||
msg, extra_pending = manager._coalesce_stream_deltas(msg)
|
||||
pending.extend(extra_pending)
|
||||
|
||||
channel = manager.channels.get(msg.channel)
|
||||
event = outbound_event_from_message(msg)
|
||||
event = msg.event
|
||||
if channel and isinstance(event, StreamDeltaEvent):
|
||||
await channel.send_delta(
|
||||
msg.chat_id,
|
||||
@@ -394,38 +393,6 @@ class TestProgressFiltering:
|
||||
assert send_mock.await_count == 1
|
||||
assert send_mock.await_args_list[0].args[0].content == "final answer"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_legacy_progress_flag_uses_runtime_progress_filter(self, manager, bus):
|
||||
manager.channels["mock"].send_progress = False
|
||||
await bus.publish_outbound(OutboundMessage(
|
||||
channel="mock",
|
||||
chat_id="chat1",
|
||||
content="legacy progress-shaped message",
|
||||
metadata={"_progress": True},
|
||||
))
|
||||
await bus.publish_outbound(OutboundMessage(
|
||||
channel="mock",
|
||||
chat_id="chat1",
|
||||
content="processing sentinel",
|
||||
))
|
||||
|
||||
task = asyncio.create_task(manager._dispatch_outbound())
|
||||
try:
|
||||
for _ in range(30):
|
||||
if manager.channels["mock"]._send_mock.await_count >= 1:
|
||||
break
|
||||
await asyncio.sleep(0.05)
|
||||
finally:
|
||||
task.cancel()
|
||||
try:
|
||||
await task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
send_mock = manager.channels["mock"]._send_mock
|
||||
assert send_mock.await_count == 1
|
||||
assert send_mock.await_args.args[0].content == "processing sentinel"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_channel_override_can_enable_tool_hints(self, manager, bus):
|
||||
manager.channels["mock"].send_tool_hints = True
|
||||
|
||||
@@ -23,7 +23,6 @@ import pytest
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import (
|
||||
ProgressEvent,
|
||||
outbound_event_from_message,
|
||||
outbound_message_for_event,
|
||||
)
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -282,7 +281,7 @@ async def _pump_one(manager: ChannelManager) -> None:
|
||||
"""Process currently queued messages through the reasoning dispatch branch."""
|
||||
|
||||
async def dispatch_one(msg: OutboundMessage) -> None:
|
||||
event = outbound_event_from_message(msg)
|
||||
event = msg.event
|
||||
if isinstance(event, ProgressEvent) and (
|
||||
event.reasoning_delta
|
||||
or event.reasoning_end
|
||||
|
||||
@@ -3534,6 +3534,8 @@ async def test_stop_all_cancels_dispatcher_and_stops_channels():
|
||||
ch = _StartableChannel(fake_config, mgr.bus)
|
||||
mgr.channels = {"startable": ch}
|
||||
mgr._channel_tasks = {}
|
||||
mgr._outbound_tasks = {}
|
||||
mgr._stopping_channels = set()
|
||||
|
||||
# Create a real cancelled task
|
||||
async def dummy_task():
|
||||
@@ -3612,6 +3614,8 @@ async def test_stop_all_handles_channel_exception():
|
||||
mgr.bus = MessageBus()
|
||||
mgr.channels = {"stopfailing": _StopFailingChannel(fake_config, mgr.bus)}
|
||||
mgr._channel_tasks = {}
|
||||
mgr._outbound_tasks = {}
|
||||
mgr._stopping_channels = set()
|
||||
mgr._dispatch_task = None
|
||||
|
||||
# Should not raise even if channel.stop() raises
|
||||
@@ -3651,6 +3655,8 @@ async def test_stop_all_handles_channel_stop_cancelled_task():
|
||||
"next": next_channel,
|
||||
}
|
||||
mgr._channel_tasks = {}
|
||||
mgr._outbound_tasks = {}
|
||||
mgr._stopping_channels = set()
|
||||
mgr._dispatch_task = None
|
||||
|
||||
await mgr.stop_all()
|
||||
|
||||
Reference in new issue
Block a user