Skip to content

The agent that grows with you

fix(api): /v1/runs/{id}/events fans out to every subscriber (X15, reported by @Xipong)

teknium1911715155406
diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.py
index 2c7e633f53e..be944ef2d97 100644
--- a/gateway/platforms/api_server_runs.py
+++ b/gateway/platforms/api_server_runs.py
@@ -92,12 +92,11 @@ def _initialize_run_state(self, *, store_factory) -> None:
self._run_owner_started = int(get_process_start_time(self._run_owner_pid) or 0)
except Exception:
self._run_owner_started = 0
- # All keyed by run_id: SSE queues (+creation time for the TTL sweep), connected
- # subscribers, live agent/task refs for cooperative stop (the executor thread may
- # outlive the request, hence the separate stopping set), pollable statuses, and
- # approval session keys (approval core resolves by session key, clients by run_id).
+ # All keyed by run_id: SSE fanout streams (+creation time for the TTL sweep), live
+ # agent/task refs for cooperative stop (the executor thread may outlive the request,
+ # hence the separate stopping set), pollable statuses, and approval session keys
+ # (approval core resolves by session key, clients by run_id).
self._run_idempotency_ids: set[str] = set()
- self._run_stream_subscribers: set[str] = set()
self._stopping_run_ids: set[str] = set()
(
self._run_owners, self._run_streams, self._run_streams_created, self._active_run_agents,
@@ -319,6 +318,29 @@ def _replay_or_conflict(self, request, outcome, record, gateway_session_key, _op
return _accepted_response(original_id, status.get("status", "queued"), gateway_session_key, replayed=True)
+class _RunStream:
+ """Fanout transport for one run: every subscriber reads the whole ordered event log,
+ including events published before it connected; ``None`` is the close sentinel. A
+ shared ``asyncio.Queue`` would hand each event to exactly one reader and let the first
+ disconnect tear the stream down under the others."""
+
+ def __init__(self) -> None:
+ self.events: List[Optional[Dict]] = []
+ self.subscribers: set["asyncio.Queue[Optional[Dict]]"] = set()
+
+ def put_nowait(self, event: Optional[Dict]) -> None:
+ self.events.append(event)
+ for queue in self.subscribers:
+ queue.put_nowait(event)
+
+ def subscribe(self) -> "asyncio.Queue[Optional[Dict]]":
+ queue: "asyncio.Queue[Optional[Dict]]" = asyncio.Queue()
+ for event in self.events:
+ queue.put_nowait(event)
+ self.subscribers.add(queue)
+ return queue
+
+
@dataclass(slots=True)
class _RunLaunch:
"""State for an admitted run's background task; contextvars are captured here
@@ -326,7 +348,7 @@ class _RunLaunch:
owner: Any
run_id: str
- queue: "asyncio.Queue[Optional[Dict]]"
+ queue: _RunStream
session_id: str
gateway_session_key: Optional[str]
declared_selected: bool
@@ -483,7 +505,7 @@ async def _handle_runs(self, request: "web.Request", *, _api_server) -> "web.Res
session_history_delivery = not previous_response_id and not conversation_history
if not conversation_history and selected_session_id and not previous_response_id:
conversation_history = await self._conversation_history_for_session(str(selected_session_id))
- q = self._run_streams[run_id] = asyncio.Queue()
+ q = self._run_streams[run_id] = _RunStream()
created_at = self._run_streams_created[run_id] = time.time()
self._run_approval_sessions[run_id] = run_id # approval session key (see _RunLaunch)
initial_status = self._set_run_status(
@@ -796,8 +818,8 @@ async def _handle_run_events(self, request: "web.Request", *, _api_server) -> "w
await asyncio.sleep(0.05)
else:
return _run_not_found(_api_server._openai_error, run_id)
- q = self._run_streams[run_id]
- self._run_stream_subscribers.add(run_id)
+ stream = self._run_streams[run_id]
+ q = stream.subscribe()
response = web.StreamResponse(status=200, headers={
"Content-Type": "text/event-stream", "Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
await response.prepare(request)
@@ -815,8 +837,9 @@ async def _handle_run_events(self, request: "web.Request", *, _api_server) -> "w
except Exception as exc:
logger.debug("[api_server] SSE stream error for run %s: %s", run_id, exc)
finally:
- self._run_stream_subscribers.discard(run_id)
- _drop_run_transport(self, run_id)
+ stream.subscribers.discard(q)
+ if not stream.subscribers:
+ _drop_run_transport(self, run_id)
return response
@@ -998,7 +1021,7 @@ def _sweep_orphaned_runs_once(self, now: Optional[float] = None) -> None:
if now is None:
now = time.time()
for run_id, created_at in list(self._run_streams_created.items()):
- if now - created_at <= self._RUN_STREAM_TTL or run_id in self._run_stream_subscribers:
+ if now - created_at <= self._RUN_STREAM_TTL or self._run_streams[run_id].subscribers:
continue
logger.debug("[api_server] sweeping expired run transport %s", run_id)
task = self._active_run_tasks.get(run_id)
diff --git a/tests/gateway/test_api_server_runs.py b/tests/gateway/test_api_server_runs.py
index 273ef8c91de..1a0945d0cf1 100644
--- a/tests/gateway/test_api_server_runs.py
+++ b/tests/gateway/test_api_server_runs.py
@@ -443,6 +443,43 @@ class TestRunEvents:
assert "run.completed" in body
assert "Hello!" in body
+ @pytest.mark.asyncio
+ async def test_two_subscribers_each_receive_every_event_and_survive_one_disconnect(self, adapter):
+ """/events is fanout, not a work queue: every subscriber sees the whole ordered stream,
+ and one client's disconnect never tears down the stream another client still reads."""
+
+ from gateway.platforms.api_server_runs import _mark_run_event
+
+ async def frame(resp):
+ return (await asyncio.wait_for(resp.content.readuntil(b"\n\n"), timeout=2.0)).decode()
+
+ app = _create_runs_app(adapter)
+ async with TestClient(TestServer(app)) as cli:
+ with patch.object(adapter, "_create_agent") as mock_create:
+ mock_agent, agent_ready, _ = _make_slow_agent()
+ mock_create.return_value = mock_agent
+ run_id = (await (await cli.post("/v1/runs", json={"input": "hello"})).json())["run_id"]
+ assert agent_ready.wait(timeout=3.0)
+ first = await cli.get(f"/v1/runs/{run_id}/events")
+ second = await cli.get(f"/v1/runs/{run_id}/events")
+ assert first.status == second.status == 200
+
+ _mark_run_event(adapter, run_id, "run.steered", accepted=True)
+ assert "run.steered" in await frame(first)
+ assert "run.steered" in await frame(second)
+
+ first.close()
+ # The server only notices the dropped socket on its next write.
+ _mark_run_event(adapter, run_id, "run.steered", accepted=False)
+ assert "run.steered" in await frame(second)
+ await asyncio.sleep(0.05)
+ _mark_run_event(adapter, run_id, "approval.responded", choice="once")
+ assert "approval.responded" in await frame(second)
+
+ assert (await cli.post(f"/v1/runs/{run_id}/stop")).status == 200
+ tail = await asyncio.wait_for(second.content.read(), timeout=5.0)
+ assert b"stream closed" in tail
+
@pytest.mark.asyncio
async def test_approval_resolve_all_is_scoped_to_target_run(self, auth_adapter):
diff --git a/tests/gateway/test_api_server_runs_extraction.py b/tests/gateway/test_api_server_runs_extraction.py
index c67d86926f7..1aa43100a79 100644
--- a/tests/gateway/test_api_server_runs_extraction.py
+++ b/tests/gateway/test_api_server_runs_extraction.py
@@ -132,7 +132,6 @@ def test_run_state_initialization_and_teardown_are_shard_owned():
assert adapter._run_owners == {}
assert adapter._run_streams == {}
assert adapter._run_streams_created == {}
- assert adapter._run_stream_subscribers == set()
assert adapter._active_run_agents == {}
assert adapter._active_run_tasks == {}
assert adapter._stopping_run_ids == set()