Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(eventbus): notify and remove subscribers on clear

santhreal705f3132f423
diff --git a/agent/src/session/events.py b/agent/src/session/events.py
index 31c40fb9f..c3fcda420 100644
--- a/agent/src/session/events.py
+++ b/agent/src/session/events.py
@@ -215,7 +215,6 @@ class EventBus:
while True:
try:
event = await asyncio.wait_for(queue.get(), timeout=30.0)
- yield event
except asyncio.TimeoutError:
yield SSEEvent(
event_id=None,
@@ -223,6 +222,11 @@ class EventBus:
data={"ts": time.time()},
session_id=session_id,
)
+ continue
+ if event.event_type == "session_cleared":
+ yield event
+ break
+ yield event
finally:
with self._lock:
subs = self._subscribers.get(session_id, [])
@@ -230,10 +234,31 @@ class EventBus:
subs.remove(queue)
def clear(self, session_id: str) -> None:
- """Clear the buffered events for a session.
+ """Clear the buffered events and notify subscribers for a session.
+
+ Subscriber queues receive a ``session_cleared`` sentinel event so
+ they can break out of their ``while True`` loop instead of waiting
+ indefinitely on a cleared session. The subscriber list is then
+ dropped so future ``publish`` calls do not enqueue to dead queues.
Args:
session_id: Session ID.
"""
with self._lock:
self._buffers.pop(session_id, None)
+ subs = self._subscribers.pop(session_id, [])
+
+ sentinel = SSEEvent(
+ event_id=None,
+ event_type="session_cleared",
+ data={},
+ session_id=session_id,
+ )
+ for queue in subs:
+ if self._loop and self._loop.is_running():
+ self._loop.call_soon_threadsafe(self._safe_put, queue, sentinel)
+ else:
+ try:
+ queue.put_nowait(sentinel)
+ except asyncio.QueueFull:
+ pass
diff --git a/agent/tests/test_eventbus_clear_subscribers.py b/agent/tests/test_eventbus_clear_subscribers.py
new file mode 100644
index 000000000..cf20b2cc4
--- /dev/null
+++ b/agent/tests/test_eventbus_clear_subscribers.py
@@ -0,0 +1,107 @@
+"""Regression: EventBus.clear must notify and remove subscribers.
+
+The original clear() only removed the buffer but left subscriber queues
+in self._subscribers. Subscribers would keep receiving heartbeats
+forever on a cleared session, and future publish() calls would still
+enqueue to those dead queues.
+
+The fix sends a ``session_cleared`` sentinel to each subscriber queue
+and removes the subscriber list so the subscribe() generator can break
+out of its loop.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from src.session.events import EventBus
+
+
+def test_clear_removes_buffer() -> None:
+ bus = EventBus()
+ bus.emit("s1", "tool_call", {"tool": "x"})
+ bus.clear("s1")
+ assert bus.replay("s1", replay_all=True) == []
+
+
+def test_clear_removes_subscribers() -> None:
+ """After clear, the subscriber list for the session must be empty."""
+ bus = EventBus()
+
+ async def _run() -> None:
+ gen = bus.subscribe("s1")
+ task = asyncio.ensure_future(gen.__anext__())
+ await asyncio.sleep(0.05)
+ bus.clear("s1")
+ assert "s1" not in bus._subscribers
+ # The generator yields the sentinel, then breaks.
+ event = await asyncio.wait_for(task, timeout=2.0)
+ assert event.event_type == "session_cleared"
+ # Next __anext__ should raise StopAsyncIteration (generator exited).
+ with pytest.raises(StopAsyncIteration):
+ await gen.__anext__()
+
+ asyncio.run(_run())
+
+
+def test_clear_sends_session_cleared_sentinel() -> None:
+ """Subscribers must receive a session_cleared event before the generator exits."""
+ bus = EventBus()
+ received: list[str] = []
+
+ async def _run() -> None:
+ gen = bus.subscribe("s1")
+ task = asyncio.ensure_future(_collect(gen))
+ await asyncio.sleep(0.05)
+ bus.clear("s1")
+ await asyncio.wait_for(task, timeout=2.0)
+
+ async def _collect(gen) -> None:
+ async for event in gen:
+ received.append(event.event_type)
+
+ asyncio.run(_run())
+ assert "session_cleared" in received
+
+
+def test_publish_after_clear_does_not_enqueue() -> None:
+ """After clear, publish must not enqueue to any subscriber queue."""
+ bus = EventBus()
+
+ async def _run() -> None:
+ gen = bus.subscribe("s1")
+ task = asyncio.ensure_future(gen.__anext__())
+ await asyncio.sleep(0.05)
+ bus.clear("s1")
+ bus.emit("s1", "tool_call", {"tool": "x"})
+ assert "s1" not in bus._subscribers
+ event = await asyncio.wait_for(task, timeout=2.0)
+ assert event.event_type == "session_cleared"
+
+ asyncio.run(_run())
+
+
+def test_clear_nonexistent_session_does_not_crash() -> None:
+ bus = EventBus()
+ bus.clear("nonexistent") # should not raise
+
+
+def test_subscribe_terminates_after_clear() -> None:
+ """The subscribe generator must stop after clear sends the sentinel."""
+ bus = EventBus()
+ received: list[str] = []
+
+ async def _subscribe() -> None:
+ async for event in bus.subscribe("s1"):
+ received.append(event.event_type)
+
+ async def _run() -> None:
+ task = asyncio.create_task(_subscribe())
+ await asyncio.sleep(0.1)
+ bus.clear("s1")
+ await asyncio.wait_for(task, timeout=2.0)
+
+ asyncio.run(_run())
+ assert "session_cleared" in received