From 8e00832d9b9ca88d2d63de39b69a133de5cd3546 Mon Sep 17 00:00:00 2001 From: teknium1 <127238744+teknium1@users.noreply.github.com> Date: Tue, 15 Sep 2026 11:59:38 -0700 Subject: [PATCH] fix(api-server): /v1/runs events stream shares the SSE keepalive cadence; trim tests The durable-run events stream (`GET /v1/runs/{id}/events`) hardcoded its own 30 s idle keepalive, so it still fell outside the ~20 s idle deadline common to remote OpenAI-compatible clients even after CHAT_COMPLETIONS_SSE_KEEPALIVE_SECONDS dropped to 10 s. Point it at the shared constant so every API-server SSE writer (chat completions, Responses, native session stream, run events) keeps the wire alive on the same cadence. Rewrite the salvaged regression test as two invariants: an idle OpenAI stream writes a `: keepalive` comment inside the remote-client window (module-local fake clock, no global `time.monotonic`/`asyncio.wait_for` patching, which would also steer asyncio), and the run events stream follows the shared constant end-to-end through aiohttp. Both are red on origin/main. --- gateway/platforms/api_server_runs.py | 3 +- .../gateway/test_api_server_sse_keepalive.py | 90 +++++++++++++------ 2 files changed, 67 insertions(+), 26 deletions(-) diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.py index 3976ff02de..33f9755561 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 dee1d0f160..6eb3776bde 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) -@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. +@pytest.fixture +def adapter(): + return APIServerAdapter(PlatformConfig(enabled=True, extra={})) - ``_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() + +@pytest.mark.asyncio +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] + + 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 - waits = 0 + assert items == [] + assert response.writes[0] == b": keepalive\n\n" - async def elapsed_wait_for(*_args, **_kwargs): - nonlocal waits - waits += 1 - if waits == 2: - agent_task.set_result(None) - raise asyncio.TimeoutError - monkeypatch.setattr( - "gateway.platforms.api_server_openai_routes.asyncio.wait_for", elapsed_wait_for - ) +@pytest.mark.asyncio +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) - 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"] + app = web.Application() + app["api_server_adapter"] = adapter + app.router.add_get("/v1/runs/{run_id}/events", adapter._handle_run_events) + + async def _close_after_idle(): + await asyncio.sleep(0.5) + await queue.put(None) + + 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 resp.status == 200 + assert body.count(": keepalive\n\n") >= 1