Skip to content

The agent that grows with you

fix(api-server): /v1/runs events stream shares the SSE keepalive cadence; trim tests

teknium18e00832d9b9c
diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.py
index 3976ff02de2..33f97555615 100644
--- a/gateway/platforms/api_server_runs.py
+++ b/gateway/platforms/api_server_runs.py
@@ -746,7 +746,8 @@ async def _handle_run_events(self, request: "web.Request", *, _api_server) -> "w
try:
while True:
try:
- event = await asyncio.wait_for(q.get(), timeout=30.0)
+ event = await asyncio.wait_for(
+ q.get(), timeout=_api_server.CHAT_COMPLETIONS_SSE_KEEPALIVE_SECONDS)
except asyncio.TimeoutError:
await response.write(b": keepalive\n\n")
continue
diff --git a/tests/gateway/test_api_server_sse_keepalive.py b/tests/gateway/test_api_server_sse_keepalive.py
index dee1d0f160d..6eb3776bdee 100644
--- a/tests/gateway/test_api_server_sse_keepalive.py
+++ b/tests/gateway/test_api_server_sse_keepalive.py
@@ -1,12 +1,23 @@
-"""Regression coverage for prompt SSE activity during long preflight work."""
+"""API-server SSE keepalive cadence while the agent is silent (preflight compression, long
+tool calls). Remote OpenAI-compatible clients commonly drop an idle stream after ~20 s and the
+disconnect interrupts the turn, so every SSE writer must emit a comment frame before that
+window closes (issue #111512)."""
import asyncio
+import types
import pytest
+from aiohttp import web
+from aiohttp.test_utils import TestClient, TestServer
+from gateway.config import PlatformConfig
from gateway.platforms import api_server
+from gateway.platforms import api_server_openai_routes as routes
+from gateway.platforms.api_server import APIServerAdapter
from gateway.platforms.api_server_openai_routes import _iter_stream_items
+REMOTE_CLIENT_IDLE_DEADLINE_S = 20.0
+
class _RecordingResponse:
def __init__(self) -> None:
@@ -16,36 +27,65 @@ class _RecordingResponse:
self.writes.append(data)
+def adapter():
+ return APIServerAdapter(PlatformConfig(enabled=True, extra={}))
+
+
@pytest.mark.asyncio
-async def test_idle_stream_writes_keepalive_before_remote_client_timeout(monkeypatch):
- """A compression-bound agent must produce a byte within a 20s client window.
+async def test_idle_openai_stream_writes_keepalive_before_remote_client_deadline(monkeypatch):
+ """Chat/Responses streams (``_iter_stream_items``) keep the wire alive inside the client window."""
+ assert api_server.CHAT_COMPLETIONS_SSE_KEEPALIVE_SECONDS <= REMOTE_CLIENT_IDLE_DEADLINE_S
+
+ # Module-local fake clock: each read is one keepalive interval later, so the poll loop
+ # observes an idle stream without waiting real seconds (asyncio keeps the real clock).
+ reads = [0.0]
+ step = api_server.CHAT_COMPLETIONS_SSE_KEEPALIVE_SECONDS
+
+ def monotonic():
+ reads[0] += step
+ return reads[0]
- ``_iter_stream_items`` is shared by OpenAI chat and Responses streaming;
- native session streaming uses the same API-server keepalive constant.
- """
- stream_q = asyncio.Queue()
+ monkeypatch.setattr(routes, "time", types.SimpleNamespace(monotonic=monotonic))
+ stream_q: asyncio.Queue = asyncio.Queue()
agent_task = asyncio.get_running_loop().create_future()
response = _RecordingResponse()
- clock = [0.0, 20.0, 20.0]
- def monotonic() -> float:
- return clock.pop(0) if clock else 20.0
+ async def _finish_after_first_keepalive():
+ while not response.writes:
+ await asyncio.sleep(0.05)
+ agent_task.set_result(None)
- monkeypatch.setattr("gateway.platforms.api_server_openai_routes.time.monotonic", monotonic)
+ finisher = asyncio.create_task(_finish_after_first_keepalive())
+ items = [item async for item in _iter_stream_items(stream_q, agent_task, response)]
+ await finisher
+
+ assert items == []
+ assert response.writes[0] == b": keepalive\n\n"
+
+
+async def test_idle_run_events_stream_uses_shared_keepalive_cadence(monkeypatch, adapter):
+ """``GET /v1/runs/{id}/events`` follows the same keepalive constant as the OpenAI routes."""
+ monkeypatch.setattr(api_server, "CHAT_COMPLETIONS_SSE_KEEPALIVE_SECONDS", 0.2)
+ queue: asyncio.Queue = asyncio.Queue()
+ adapter._run_streams["run_idle"] = queue
+ adapter._set_run_status("run_idle", "running")
+ monkeypatch.setattr(adapter, "_request_owns_run", lambda request, run_id: True)
- waits = 0
+ app = web.Application()
+ app["api_server_adapter"] = adapter
+ app.router.add_get("/v1/runs/{run_id}/events", adapter._handle_run_events)
- async def elapsed_wait_for(*_args, **_kwargs):
- nonlocal waits
- waits += 1
- if waits == 2:
- agent_task.set_result(None)
- raise asyncio.TimeoutError
+ async def _close_after_idle():
+ await asyncio.sleep(0.5)
+ await queue.put(None)
- monkeypatch.setattr(
- "gateway.platforms.api_server_openai_routes.asyncio.wait_for", elapsed_wait_for
- )
+ async with TestClient(TestServer(app)) as cli:
+ closer = asyncio.create_task(_close_after_idle())
+ resp = await cli.get("/v1/runs/run_idle/events")
+ body = await resp.text()
+ await closer
- assert api_server.CHAT_COMPLETIONS_SSE_KEEPALIVE_SECONDS <= 20.0
- assert [item async for item in _iter_stream_items(stream_q, agent_task, response)] == []
- assert response.writes == [b": keepalive\n\n"]
+ assert resp.status == 200
+ assert body.count(": keepalive\n\n") >= 1