perf(gateway): replace SSE poll loop with call_soon_threadsafe-fed asyncio.Queue

_write_sse_chat_completion and _write_sse_responses bridged their
stream_delta_callback queue into the event loop via
`await loop.run_in_executor(None, lambda: stream_q.get(timeout=0.5))`
in a while-True poll — a thread-pool round trip on every 0.5s tick even
when idle, plus up to 500ms of tail latency between a delta landing in
the queue and it reaching the SSE response.

Add ThreadSafeAsyncQueue (asyncio.Queue + a put_threadsafe() that wraps
call_soon_threadsafe), used by both streaming producer closures
(_on_delta, tool start/complete callbacks — all invoked from the worker
thread running run_conversation via loop.run_in_executor). Consumers
now do a plain `await asyncio.wait_for(stream_q.get(), timeout=0.5)` —
woken immediately when a delta arrives, no executor hop, no poll
interval.

Updated tests/gateway/test_sse_agent_cancel.py's 7 call sites to
construct ThreadSafeAsyncQueue inside the running loop (required, since
it captures asyncio.get_running_loop() at construction) instead of a
bare queue.Queue() at test-method scope.
This commit is contained in:
zabih-sudo
2026-07-15 15:38:07 +02:00
committed by kshitij
parent 9076adaca5
commit 7098862dea
2 changed files with 226 additions and 35 deletions
+50 -25
View File
@@ -158,6 +158,32 @@ RESPONSES_AUTO_TRUNCATION_HISTORY_LIMIT = 100
_COMPRESSED_SUMMARY_METADATA_KEY = "_compressed_summary"
class ThreadSafeAsyncQueue(asyncio.Queue):
"""An ``asyncio.Queue`` that a non-loop thread can push into safely.
The SSE writers' streaming loops used to bridge a plain ``queue.Queue``
into the event loop via ``await loop.run_in_executor(None, lambda:
stream_q.get(timeout=0.5))`` inside a ``while True`` poll — a thread-pool
round trip on every 0.5s tick even when idle, plus up to 500ms of tail
latency between a delta landing in the queue and it reaching the
response. ``run_conversation`` itself runs on a worker thread (via
``loop.run_in_executor``), so its ``stream_delta_callback`` closures
(``_on_delta`` etc.) call ``put_threadsafe`` from off the loop thread;
the consumer side just does a plain ``await queue.get()``/
``asyncio.wait_for(queue.get(), timeout=...)``, woken immediately by
``call_soon_threadsafe`` instead of polling.
"""
def put_threadsafe(self, item, *, loop: asyncio.AbstractEventLoop = None) -> None:
(loop or self._loop_ref).call_soon_threadsafe(self.put_nowait, item)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Always constructed inside a running async handler (the SSE
# request handlers below), so get_running_loop() is safe here.
self._loop_ref = asyncio.get_running_loop()
def _coerce_port(value: Any, default: int = DEFAULT_PORT) -> int:
"""Parse a listen port without letting malformed env/config values crash startup."""
try:
@@ -3985,8 +4011,7 @@ class APIServerAdapter(BasePlatformAdapter):
return web.json_response(_openai_error(selection_error), status=400)
if stream:
import queue as _q
_stream_q: _q.Queue = _q.Queue()
_stream_q = ThreadSafeAsyncQueue()
def _on_delta(delta):
# Filter out None — the agent fires stream_delta_callback(None)
@@ -3996,8 +4021,10 @@ class APIServerAdapter(BasePlatformAdapter):
# response, causing Open WebUI (and similar frontends) to miss
# the final answer after tool calls. The SSE loop detects
# completion via agent_task.done() instead.
# Called from the worker thread running run_conversation —
# put_threadsafe (not put_nowait) is required here.
if delta is not None:
_stream_q.put(delta)
_stream_q.put_threadsafe(delta)
# Track which tool_call_ids we've emitted a "running" lifecycle
# event for, so a "completed" event without a matching "running"
@@ -4023,7 +4050,7 @@ class APIServerAdapter(BasePlatformAdapter):
_started_tool_call_ids.add(tool_call_id)
from agent.display import build_tool_preview, get_tool_emoji
label = build_tool_preview(function_name, function_args) or function_name
_stream_q.put(("__tool_progress__", {
_stream_q.put_threadsafe(("__tool_progress__", {
"tool": function_name,
"emoji": get_tool_emoji(function_name),
"label": label,
@@ -4041,7 +4068,7 @@ class APIServerAdapter(BasePlatformAdapter):
if not tool_call_id or tool_call_id not in _started_tool_call_ids:
return
_started_tool_call_ids.discard(tool_call_id)
_stream_q.put(("__tool_progress__", {
_stream_q.put_threadsafe(("__tool_progress__", {
"tool": function_name,
"toolCallId": tool_call_id,
"status": "completed",
@@ -4071,7 +4098,7 @@ class APIServerAdapter(BasePlatformAdapter):
))
# Ensure SSE drain loops can terminate without relying on polling
# agent_task.done(), which can race with queue timeout checks.
agent_task.add_done_callback(lambda _fut: _stream_q.put(None))
agent_task.add_done_callback(lambda _fut: _stream_q.put_nowait(None))
return await self._write_sse_chat_completion(
request, completion_id, model_name, created, _stream_q,
@@ -4206,8 +4233,6 @@ class APIServerAdapter(BasePlatformAdapter):
the agent is interrupted via ``agent.interrupt()`` so it stops making
LLM API calls, and the asyncio task wrapper is cancelled.
"""
import queue as _q
sse_headers = {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
@@ -4263,12 +4288,14 @@ class APIServerAdapter(BasePlatformAdapter):
await response.write(f"data: {json.dumps(content_chunk)}\n\n".encode())
return time.monotonic()
# Stream content chunks as they arrive from the agent
loop = asyncio.get_running_loop()
# Stream content chunks as they arrive from the agent. Woken
# directly by put_threadsafe's call_soon_threadsafe — no
# executor hop, no poll-interval latency (see
# ThreadSafeAsyncQueue's docstring).
while True:
try:
delta = await loop.run_in_executor(None, lambda: stream_q.get(timeout=0.5))
except _q.Empty:
delta = await asyncio.wait_for(stream_q.get(), timeout=0.5)
except asyncio.TimeoutError:
if agent_task.done():
# Drain any remaining items
while True:
@@ -4277,7 +4304,7 @@ class APIServerAdapter(BasePlatformAdapter):
if delta is None:
break
last_activity = await _emit(delta)
except _q.Empty:
except asyncio.QueueEmpty:
break
break
if time.monotonic() - last_activity >= CHAT_COMPLETIONS_SSE_KEEPALIVE_SECONDS:
@@ -4437,8 +4464,6 @@ class APIServerAdapter(BasePlatformAdapter):
``previous_response_id`` chaining still have something to
recover from.
"""
import queue as _q
sse_headers = {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
@@ -4759,11 +4784,10 @@ class APIServerAdapter(BasePlatformAdapter):
_batch_buf = []
await _emit_text_delta(combined)
loop = asyncio.get_running_loop()
while True:
try:
item = await loop.run_in_executor(None, lambda: stream_q.get(timeout=0.5))
except _q.Empty:
item = await asyncio.wait_for(stream_q.get(), timeout=0.5)
except asyncio.TimeoutError:
if agent_task.done():
# Drain remaining
while True:
@@ -4773,7 +4797,7 @@ class APIServerAdapter(BasePlatformAdapter):
break
await _dispatch(item)
last_activity = time.monotonic()
except _q.Empty:
except asyncio.QueueEmpty:
break
break
if time.monotonic() - last_activity >= CHAT_COMPLETIONS_SSE_KEEPALIVE_SECONDS:
@@ -5135,15 +5159,16 @@ class APIServerAdapter(BasePlatformAdapter):
# Streaming branch — emit OpenAI Responses SSE events as the
# agent runs so frontends can render text deltas and tool
# calls in real time. See _write_sse_responses for details.
import queue as _q
_stream_q: _q.Queue = _q.Queue()
_stream_q = ThreadSafeAsyncQueue()
def _on_delta(delta):
# None from the agent is a CLI box-close signal, not EOS.
# Forwarding would kill the SSE stream prematurely; the
# SSE writer detects completion via agent_task.done().
# Called from the worker thread running run_conversation —
# put_threadsafe (not put_nowait) is required here.
if delta is not None:
_stream_q.put(delta)
_stream_q.put_threadsafe(delta)
def _on_tool_progress(event_type, name, preview, args, **kwargs):
"""Queue non-start tool progress events if needed in future.
@@ -5156,7 +5181,7 @@ class APIServerAdapter(BasePlatformAdapter):
def _on_tool_start(tool_call_id, function_name, function_args):
"""Queue a started tool for live function_call streaming."""
_stream_q.put(("__tool_started__", {
_stream_q.put_threadsafe(("__tool_started__", {
"tool_call_id": tool_call_id,
"name": function_name,
"arguments": function_args or {},
@@ -5164,7 +5189,7 @@ class APIServerAdapter(BasePlatformAdapter):
def _on_tool_complete(tool_call_id, function_name, function_args, function_result):
"""Queue a completed tool result for live function_call_output streaming."""
_stream_q.put(("__tool_completed__", {
_stream_q.put_threadsafe(("__tool_completed__", {
"tool_call_id": tool_call_id,
"name": function_name,
"arguments": function_args or {},
@@ -5188,7 +5213,7 @@ class APIServerAdapter(BasePlatformAdapter):
))
# Ensure SSE drain loops can terminate without relying on polling
# agent_task.done(), which can race with queue timeout checks.
agent_task.add_done_callback(lambda _fut: _stream_q.put(None))
agent_task.add_done_callback(lambda _fut: _stream_q.put_nowait(None))
response_id = f"resp_{uuid.uuid4().hex[:28]}"
model_name = body.get("model", self._model_name)
+176 -10
View File
@@ -7,7 +7,6 @@ task wrapper is cancelled.
"""
import asyncio
import queue
from unittest.mock import AsyncMock, MagicMock, patch
@@ -44,9 +43,6 @@ class TestSSEAgentCancelOnDisconnect:
the agent task must be cancelled."""
adapter = _make_adapter()
stream_q = queue.Queue()
stream_q.put("hello ") # Some data already queued
# Agent task that runs forever (simulates a long LLM call)
agent_done = asyncio.Event()
@@ -56,6 +52,12 @@ class TestSSEAgentCancelOnDisconnect:
async def run():
from aiohttp import web
from gateway.platforms.api_server import ThreadSafeAsyncQueue
# Constructed inside the running loop — ThreadSafeAsyncQueue
# captures asyncio.get_running_loop() at construction time.
stream_q = ThreadSafeAsyncQueue()
stream_q.put_nowait("hello ") # Some data already queued
agent_task = asyncio.ensure_future(fake_agent())
@@ -89,19 +91,54 @@ class TestSSEAgentCancelOnDisconnect:
asyncio.run(run())
def test_agent_task_not_cancelled_on_normal_completion(self):
"""On normal stream completion, agent task should NOT be cancelled."""
adapter = _make_adapter()
async def fake_agent():
return {"final_response": "done"}, {"input_tokens": 10, "output_tokens": 5, "total_tokens": 15}
async def run():
from aiohttp import web
from gateway.platforms.api_server import ThreadSafeAsyncQueue
stream_q = ThreadSafeAsyncQueue()
stream_q.put_nowait("hello")
stream_q.put_nowait(None) # End-of-stream sentinel
agent_task = asyncio.ensure_future(fake_agent())
await asyncio.sleep(0) # Let agent complete
mock_response = AsyncMock(spec=web.StreamResponse)
mock_response.write = AsyncMock()
mock_response.prepare = AsyncMock()
with patch("gateway.platforms.api_server.web.StreamResponse",
return_value=mock_response):
await adapter._write_sse_chat_completion(
_make_request(), "cmpl-456", "gpt-4", 1234567890,
stream_q, agent_task,
)
# Agent should have completed normally, not been cancelled
assert agent_task.done()
assert not agent_task.cancelled()
asyncio.run(run())
def test_broken_pipe_also_cancels_agent(self):
"""BrokenPipeError (another disconnect variant) also cancels the task."""
adapter = _make_adapter()
stream_q = queue.Queue()
async def fake_agent():
await asyncio.sleep(0.2) # Never completes
return {}, {}
async def run():
from aiohttp import web
from gateway.platforms.api_server import ThreadSafeAsyncQueue
stream_q = ThreadSafeAsyncQueue()
agent_task = asyncio.ensure_future(fake_agent())
@@ -120,6 +157,132 @@ class TestSSEAgentCancelOnDisconnect:
asyncio.run(run())
def test_already_done_task_not_cancelled_on_disconnect(self):
"""If agent already finished before disconnect, don't try to cancel."""
adapter = _make_adapter()
async def fake_agent():
return {"final_response": "done"}, {}
async def run():
from aiohttp import web
from gateway.platforms.api_server import ThreadSafeAsyncQueue
stream_q = ThreadSafeAsyncQueue()
stream_q.put_nowait("data")
agent_task = asyncio.ensure_future(fake_agent())
await asyncio.sleep(0) # Let agent complete
mock_response = AsyncMock(spec=web.StreamResponse)
call_count = 0
async def write_side_effect(data):
nonlocal call_count
call_count += 1
if call_count >= 2:
raise ConnectionResetError("late disconnect")
mock_response.write = AsyncMock(side_effect=write_side_effect)
mock_response.prepare = AsyncMock()
with patch("gateway.platforms.api_server.web.StreamResponse",
return_value=mock_response):
await adapter._write_sse_chat_completion(
_make_request(), "cmpl-done", "gpt-4", 1234567890,
stream_q, agent_task,
)
# Task was already done — should not be cancelled
assert agent_task.done()
assert not agent_task.cancelled()
asyncio.run(run())
def test_agent_interrupt_called_on_disconnect(self):
"""When the client disconnects, agent.interrupt() must be called
so the agent thread stops making LLM API calls."""
adapter = _make_adapter()
agent_done = asyncio.Event()
async def fake_agent():
await agent_done.wait()
return {"final_response": "done"}, {}
# Mock agent with an interrupt method
mock_agent = MagicMock()
mock_agent.interrupt = MagicMock()
async def run():
from aiohttp import web
from gateway.platforms.api_server import ThreadSafeAsyncQueue
stream_q = ThreadSafeAsyncQueue()
stream_q.put_nowait("hello ")
agent_task = asyncio.ensure_future(fake_agent())
agent_ref = [mock_agent]
mock_response = AsyncMock(spec=web.StreamResponse)
call_count = 0
async def write_side_effect(data):
nonlocal call_count
call_count += 1
if call_count >= 2:
raise ConnectionResetError("client disconnected")
mock_response.write = AsyncMock(side_effect=write_side_effect)
mock_response.prepare = AsyncMock()
with patch("gateway.platforms.api_server.web.StreamResponse",
return_value=mock_response):
await adapter._write_sse_chat_completion(
_make_request(), "cmpl-int", "gpt-4", 1234567890,
stream_q, agent_task, agent_ref,
)
# agent.interrupt() must have been called
mock_agent.interrupt.assert_called_once_with("SSE client disconnected")
# Clean up
agent_done.set()
asyncio.run(run())
def test_agent_ref_none_still_cancels_task(self):
"""When agent_ref is not provided (None), the task is still cancelled
on disconnect — just without the interrupt() call."""
adapter = _make_adapter()
async def fake_agent():
await asyncio.sleep(999)
return {}, {}
async def run():
from aiohttp import web
from gateway.platforms.api_server import ThreadSafeAsyncQueue
stream_q = ThreadSafeAsyncQueue()
agent_task = asyncio.ensure_future(fake_agent())
mock_response = AsyncMock(spec=web.StreamResponse)
mock_response.write = AsyncMock(side_effect=BrokenPipeError("gone"))
mock_response.prepare = AsyncMock()
with patch("gateway.platforms.api_server.web.StreamResponse",
return_value=mock_response):
# No agent_ref passed — should still handle disconnect cleanly
await adapter._write_sse_chat_completion(
_make_request(), "cmpl-noref", "gpt-4", 1234567890,
stream_q, agent_task,
)
assert agent_task.cancelled() or agent_task.done()
asyncio.run(run())
def _capturing_response():
"""Mock StreamResponse that records all written SSE bytes as text."""
@@ -161,12 +324,15 @@ class TestSSEAgentFailureFinishReason:
def _run(self, fake_agent, queue_items=("partial",)):
adapter = _make_adapter()
stream_q = queue.Queue()
for item in queue_items:
stream_q.put(item)
stream_q.put(None) # clean end-of-stream sentinel
async def run():
from gateway.platforms.api_server import ThreadSafeAsyncQueue
stream_q = ThreadSafeAsyncQueue()
for item in queue_items:
stream_q.put_nowait(item)
stream_q.put_nowait(None) # clean end-of-stream sentinel
agent_task = asyncio.ensure_future(fake_agent())
resp, chunks = _capturing_response()
with patch("gateway.platforms.api_server.web.StreamResponse",