"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(session): close race that double delivers SSE events on reconnect (#1798)
Lanre Shittu3879484970d8
diff --git a/agent/src/session/events.py b/agent/src/session/events.pyindex f76b6ebf5..eeddc8af9 100644--- a/agent/src/session/events.py+++ b/agent/src/session/events.py@@ -212,19 +212,29 @@ class EventBus:List of events that should be replayed."""with self._lock:- buffer = self._buffers.get(session_id, [])- if not last_event_id:- return list(buffer) if replay_all else [] # First connect: history loaded via REST by default.- found = False- result: List[SSEEvent] = []- for event in buffer:- if found:- result.append(event)- elif event.event_id == last_event_id:- found = True- if not found and replay_all:- return list(buffer)- return result+ return self._replay_locked(session_id, last_event_id, replay_all=replay_all)++ def _replay_locked(+ self,+ session_id: str,+ last_event_id: Optional[str] = None,+ *,+ replay_all: bool = False,+ ) -> List[SSEEvent]:+ """Compute the replay list. Caller must already hold ``self._lock``."""+ buffer = self._buffers.get(session_id, [])+ if not last_event_id:+ return list(buffer) if replay_all else [] # First connect: history loaded via REST by default.+ found = False+ result: List[SSEEvent] = []+ for event in buffer:+ if found:+ result.append(event)+ elif event.event_id == last_event_id:+ found = True+ if not found and replay_all:+ return list(buffer)+ return resultasync def subscribe(self,@@ -246,13 +256,17 @@ class EventBus:"""queue: asyncio.Queue[SSEEvent] = asyncio.Queue(maxsize=200)+ # The replay snapshot and queue registration must happen under the+ # same lock acquisition: otherwise a publish() landing between them+ # would land in both the replay buffer and the live queue, and the+ # subscriber would see that event delivered twice.with self._lock:+ replay_events = self._replay_locked(session_id, last_event_id, replay_all=replay_all)if session_id not in self._subscribers:self._subscribers[session_id] = []self._subscribers[session_id].append(queue)try:- replay_events = self.replay(session_id, last_event_id, replay_all=replay_all)for event in replay_events:yield eventdiff --git a/agent/tests/test_session_events.py b/agent/tests/test_session_events.pyindex 0a12b0ac5..89aa2edd2 100644--- a/agent/tests/test_session_events.py+++ b/agent/tests/test_session_events.py@@ -2,6 +2,10 @@from __future__ import annotations+import asyncio+import threading+import time+from src.session.events import EventBus, SSEEvent@@ -48,3 +52,49 @@ def test_synthetic_heartbeat_frame_has_no_replay_id() -> None:assert "event: heartbeat" in frameassert "id:" not in frame+++def test_subscribe_does_not_double_deliver_an_event_published_during_replay() -> None:+ """A publish() landing between queue registration and the replay snapshot+ must not be returned through both paths.+ """++ class SlowEventBus(EventBus):+ def replay(self, *args, **kwargs):+ time.sleep(0.15)+ return super().replay(*args, **kwargs)++ async def run() -> list:+ bus = SlowEventBus()+ bus.set_loop(asyncio.get_running_loop())+ baseline = bus.emit("s1", "baseline", {})++ def publish_from_another_thread() -> None:+ time.sleep(0.05)+ bus.emit("s1", "race", {})++ thread = threading.Thread(target=publish_from_another_thread)+ thread.start()++ gen = bus.subscribe("s1", last_event_id=baseline.event_id)+ received = []++ async def collect_one() -> None:+ async for event in gen:+ received.append(event.event_id)+ return++ await asyncio.wait_for(collect_one(), timeout=3)+ thread.join()++ try:+ await asyncio.wait_for(gen.__anext__(), timeout=0.3)+ received.append("unexpected-second-event")+ except asyncio.TimeoutError:+ pass+ return received++ received = asyncio.run(run())++ assert len(received) == 1+