The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway): route all three SSE writers through _sse_frame()
zabih-sudo1a09b0725360
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex f8ea6b9948a..839cdb92f1e 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -184,20 +184,26 @@ class ThreadSafeAsyncQueue(asyncio.Queue):self._loop_ref = asyncio.get_running_loop()-def _sse_frame(data: Any, *, event: str = None) -> bytes:- """Encode one SSE frame: optional ``event:`` line, then ``data: <json>\\n\\n``.-- Replaces five near-identical inline- ``f"data: {json.dumps(...)}\\n\\n".encode()`` call sites in the- ``_write_sse_chat_completion`` streaming path — pure dedup, no- behavior change intended for those. Left the pre-serialized-string- sites elsewhere (e.g. the ``_write_event``/``queue`` writers that- already dumps with ``ensure_ascii=False``) alone, since routing them- through this helper's plain ``json.dumps(data)`` would silently- change their unicode-escaping behavior.+def _sse_frame(data: Any, *, event: str = None, ensure_ascii: bool = True) -> bytes:+ """Encode one SSE frame: optional ``event:`` line, then ``data: <json>\n\n``.++ The single source of truth for SSE frame serialization across every+ streaming writer in this module — ``_write_sse_chat_completion`` (the+ five call sites it was first extracted from), ``_write_sse_responses``'s+ inner ``_write_event`` closure, and the ``/v1/runs`` event stream. All+ three used the identical ``json.dumps(data)`` / ``json.dumps(...,+ ensure_ascii=False)`` + ``"\\ndata: ...\\n\\n"`` shape; routing them all+ through here keeps the on-the-wire format in exactly one place.++ ``ensure_ascii`` defaults to ``True``, byte-identical to a bare+ ``json.dumps(data)``. Callers that must preserve raw non-ASCII bytes on+ the wire (the Responses-API writer historically used+ ``ensure_ascii=False``) pass ``ensure_ascii=False`` explicitly — the+ option exists so every writer shares one helper without changing any+ existing byte stream."""prefix = f"event: {event}\n" if event else ""- return f"{prefix}data: {json.dumps(data)}\n\n".encode()+ return f"{prefix}data: {json.dumps(data, ensure_ascii=ensure_ascii)}\n\n".encode()def _coerce_port(value: Any, default: int = DEFAULT_PORT) -> int:@@ -4521,8 +4527,7 @@ class APIServerAdapter(BasePlatformAdapter):if "sequence_number" not in data:data["sequence_number"] = sequence_numbersequence_number += 1- payload = f"event: {event_type}\ndata: {json.dumps(data)}\n\n"- await response.write(payload.encode())+ await response.write(_sse_frame(data, event=event_type))def _envelope(status: str) -> Dict[str, Any]:env: Dict[str, Any] = {@@ -6753,8 +6758,8 @@ class APIServerAdapter(BasePlatformAdapter):# Run finished — send final SSE comment and closeawait response.write(b": stream closed\n\n")break- payload = f"data: {json.dumps(event)}\n\n"- await response.write(payload.encode())+ payload = _sse_frame(event)+ await response.write(payload)except Exception as exc:logger.debug("[api_server] SSE stream error for run %s: %s", run_id, exc)finally:diff --git a/tests/gateway/test_sse_frame.py b/tests/gateway/test_sse_frame.pynew file mode 100644index 00000000000..0c8e68be662--- /dev/null+++ b/tests/gateway/test_sse_frame.py@@ -0,0 +1,65 @@+"""Byte-contract tests for the shared ``_sse_frame`` SSE encoder.++``_sse_frame`` is the single source of truth for SSE frame serialization+across ``_write_sse_chat_completion``, ``_write_sse_responses._write_event``,+and the ``/v1/runs`` event stream. These tests assert the *invariant* that+``_sse_frame`` reproduces the exact on-the-wire bytes the inline encoders+used to emit — not a snapshot of a frozen value. If a writer's bytes ever+diverge, a real client breaks, so we pin the relationship, not a literal.+"""++import json++from gateway.platforms.api_server import _sse_frame+++def _inline_frame(data, *, event=None):+ """Reproduce the historical inline SSE encoder (pre-dedup)."""+ prefix = f"event: {event}\n" if event else ""+ return f"{prefix}data: {json.dumps(data)}\n\n".encode()+++def test_sse_frame_matches_inline_encoder_no_event():+ for data in (+ {"id": "c1", "choices": [{"delta": {"role": "assistant"}}]},+ {"event": "ping", "sequence_number": 1},+ {"text": "plain ascii"},+ ):+ assert _sse_frame(data) == _inline_frame(data)+++def test_sse_frame_matches_inline_encoder_with_event():+ for event, data in (+ ("hermes.tool.progress", {"name": "x", "status": "running"}),+ ("response.created", {"id": "r1", "status": "in_progress"}),+ ):+ assert _sse_frame(data, event=event) == _inline_frame(data, event=event)+++def test_sse_frame_event_line_shape():+ out = _sse_frame({"a": 1}, event="my.event")+ assert out.startswith(b"event: my.event\n")+ assert b"data: " in out+ assert out.endswith(b"\n\n")+++def test_sse_frame_default_ensure_ascii_matches_bare_json():+ payload = {"text": "café — Münchner 🏔"}+ # Default must equal a bare json.dumps (the original writers used no+ # ensure_ascii override), so existing byte streams are unchanged.+ assert _sse_frame(payload) == _inline_frame(payload)+ assert _sse_frame(payload) == f"data: {json.dumps(payload)}\n\n".encode()+++def test_sse_frame_ensure_ascii_false_preserves_raw_bytes():+ payload = {"text": "café — Münchner 🏔"}+ raw = _sse_frame(payload, ensure_ascii=False)+ assert "café" in raw.decode("utf-8")+ assert raw != _sse_frame(payload) # different bytes from the default+++def test_sse_frame_typed_object_roundtrip():+ obj = {"id": "x", "choices": [{"index": 0, "delta": {"content": "hi"}}]}+ out = _sse_frame(obj)+ line = out.decode().split("data: ", 1)[1].strip()+ assert json.loads(line) == obj