The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(stream): flush residual SSE buffer at EOF and widen resilience to the Gemini native adapter
Teknium11d761eed9b6
diff --git a/agent/gemini_native_adapter.py b/agent/gemini_native_adapter.pyindex 9dafa4d6bfe..41004984e40 100644--- a/agent/gemini_native_adapter.py+++ b/agent/gemini_native_adapter.py@@ -506,24 +506,41 @@ def _make_stream_chunk(return _envelope(model, "chat.completion.chunk", choice, None, cls=_GeminiStreamChunk)+_SSE_DONE = object() # sentinel: terminal [DONE] frame+++def _parse_sse_line(line: str) -> Any:+ """One SSE line → payload dict, ``_SSE_DONE`` for the terminal frame, or None."""+ line = line.rstrip("\r")+ if not line.startswith("data: "):+ return None+ if (data := line[6:]) == "[DONE]":+ return _SSE_DONE+ try:+ payload = json.loads(data)+ except json.JSONDecodeError:+ logger.debug("Non-JSON Gemini SSE line: %s", data[:200])+ return None+ return payload if isinstance(payload, dict) else None++def _iter_sse_events(response: httpx.Response) -> Iterator[Dict[str, Any]]:buffer = ""for chunk in response.iter_text():buffer += chunk or ""while "\n" in buffer:line, buffer = buffer.split("\n", 1)- line = line.rstrip("\r")- if not line.startswith("data: "):- continue- if (data := line[6:]) == "[DONE]":+ payload = _parse_sse_line(line)+ if payload is _SSE_DONE:return- try:- payload = json.loads(data)- except json.JSONDecodeError:- logger.debug("Non-JSON Gemini SSE line: %s", data[:200])- continue- if isinstance(payload, dict):+ if payload is not None:yield payload+ # The final frame may not be newline-terminated: flush the residual buffer+ # after EOF instead of silently dropping its content (pi#8997 bug class).+ if buffer:+ payload = _parse_sse_line(buffer)+ if payload is not None and payload is not _SSE_DONE:+ yield payloaddef translate_stream_event(event: Dict[str, Any], model: str, tool_call_indices: Dict[str, Dict[str, Any]]) -> List[_GeminiStreamChunk]:diff --git a/tests/agent/test_gemini_native_adapter.py b/tests/agent/test_gemini_native_adapter.pyindex c69ae3483e8..6ad2c95068e 100644--- a/tests/agent/test_gemini_native_adapter.py+++ b/tests/agent/test_gemini_native_adapter.py@@ -675,3 +675,39 @@ def test_text_only_tool_result_has_no_parts():)fr = request["contents"][1]["parts"][0]["functionResponse"]assert "parts" not in fr+++class _FakeStreamResponse:+ """Minimal httpx.Response stand-in for _iter_sse_events: text chunks only."""++ def __init__(self, chunks):+ self._chunks = chunks++ def iter_text(self):+ yield from self._chunks+++def test_iter_sse_events_flushes_residual_buffer_after_eof():+ """A final SSE frame without a trailing newline must not be dropped (pi#8997 class)."""+ from agent.gemini_native_adapter import _iter_sse_events++ resp = _FakeStreamResponse([+ 'data: {"candidates": [1]}\n',+ 'data: {"candidates": [2]}', # no newline, then EOF+ ])+ events = list(_iter_sse_events(resp))+ assert events == [{"candidates": [1]}, {"candidates": [2]}]+++def test_iter_sse_events_stops_at_done_and_ignores_trailing_frames():+ """[DONE] terminates iteration even when more frames follow; a residual+ [DONE] in the leftover buffer is not yielded as data."""+ from agent.gemini_native_adapter import _iter_sse_events++ resp = _FakeStreamResponse([+ 'data: {"candidates": [1]}\ndata: [DONE]\ndata: {"candidates": [3]}\n',+ ])+ assert list(_iter_sse_events(resp)) == [{"candidates": [1]}]++ resp = _FakeStreamResponse(['data: {"candidates": [1]}\ndata: [DONE]'])+ assert list(_iter_sse_events(resp)) == [{"candidates": [1]}]diff --git a/tests/gateway/test_proxy_mode.py b/tests/gateway/test_proxy_mode.pyindex c36e6355c62..65194ffa467 100644--- a/tests/gateway/test_proxy_mode.py+++ b/tests/gateway/test_proxy_mode.py@@ -329,6 +329,68 @@ class TestStreamingResilience:assert result["final_response"] == "Hello"+ @pytest.mark.asyncio+ async def test_residual_buffer_flushed_after_eof(self, monkeypatch):+ """A final SSE frame without a trailing newline must not be dropped.++ The line loop only consumes complete lines; if the upstream's last+ frame lacks the newline, its content sat in ``buffer`` at EOF and+ was silently discarded (pi#8997's bug class). The residual buffer+ is now flushed after the read loop.+ """+ monkeypatch.setenv("GATEWAY_PROXY_URL", "http://host:8642")+ monkeypatch.delenv("GATEWAY_PROXY_KEY", raising=False)+ runner = _make_runner()+ source = _make_source()++ resp = _FakeSSEResponse(+ status=200,+ sse_chunks=[+ 'data: {"choices":[{"delta":{"content":"Hello"}}]}\n',+ 'data: {"choices":[{"delta":{"content":" world"}}]}', # no newline, then EOF+ ],+ )+ session = _FakeSession(resp)++ with patch("gateway.run._load_gateway_config", return_value={}):+ with _patch_aiohttp(session):+ with patch("aiohttp.ClientTimeout"):+ result = await runner._run_agent_via_proxy(+ message="hi",+ context_prompt="",+ history=[],+ source=source,+ session_id="test",+ )++ assert result["final_response"] == "Hello world"++ @pytest.mark.asyncio+ async def test_eof_without_done_and_no_content_is_an_error(self, monkeypatch):+ """Clean EOF with no [DONE] and no content must surface an error, not+ an empty 'response'. With content, the partial text is kept (and the+ truncation is logged) rather than thrown away."""+ monkeypatch.setenv("GATEWAY_PROXY_URL", "http://host:8642")+ monkeypatch.delenv("GATEWAY_PROXY_KEY", raising=False)+ runner = _make_runner()+ source = _make_source()++ resp = _FakeSSEResponse(status=200, sse_chunks=[])+ session = _FakeSession(resp)++ with patch("gateway.run._load_gateway_config", return_value={}):+ with _patch_aiohttp(session):+ with patch("aiohttp.ClientTimeout"):+ result = await runner._run_agent_via_proxy(+ message="hi",+ context_prompt="",+ history=[],+ source=source,+ session_id="test",+ )++ assert "closed before the response completed" in result["final_response"]+@pytest.mark.asyncioasync def test_client_timeout_sets_sock_connect(self, monkeypatch):"""ClientTimeout must bound the TCP connect phase.