The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): harden proxy mode SSE streaming — 3 resilience bugs
0xbyt4c2b9a517e044
diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex c04e91bc84b..b6e7fb91639 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -2568,8 +2568,35 @@ class GatewayTurnMixin:full_response = ""_start = time.time()+ saw_done = False++ def _consume_sse_line(line: str) -> bool:+ """Parse one SSE line into full_response; True when the terminal ``[DONE]`` was seen.++ Malformed frames (bad JSON, ``choices: [null]``, non-dict deltas) are skipped —+ one bad chunk must not abort the whole stream."""+ nonlocal full_response+ line = line.strip()+ if not line.startswith("data: "):+ return False+ data = line[6:]+ if data.strip() == "[DONE]":+ return True+ try:+ choices = json.loads(data).get("choices") or []+ content = choices[0].get("delta", {}).get("content", "") if choices else ""+ except (json.JSONDecodeError, TypeError, AttributeError, IndexError):+ return False+ if content:+ full_response += content+ if _stream_consumer:+ _stream_consumer.on_delta(content)+ return False+try:- _timeout = ClientTimeout(total=0, sock_read=1800)+ # sock_connect bounds the TCP connect phase so an unreachable proxy host+ # (DNS fail, firewall, remote down) fails fast instead of hanging on the OS default.+ _timeout = ClientTimeout(total=0, sock_read=1800, sock_connect=30)async with _AioClientSession(timeout=_timeout) as session:async with session.post(f"{proxy_url}/v1/chat/completions", json=body, headers=headers) as resp:if resp.status != 200:@@ -2579,28 +2606,35 @@ class GatewayTurnMixin:buffer = ""async for chunk in resp.content.iter_any():+ if saw_done:+ # A buggy upstream that holds the connection open after [DONE]+ # would otherwise block us for up to sock_read seconds.+ breakif not _run_still_current():return _stale_result("stream")buffer += chunk.decode("utf-8", errors="replace")while "\n" in buffer:line, buffer = buffer.split("\n", 1)- line = line.strip()- if not line.startswith("data: "):- continue- data = line[6:]- if data.strip() == "[DONE]":+ if _consume_sse_line(line):+ saw_done = Truebreak- try:- choices = json.loads(data).get("choices", [])- except json.JSONDecodeError:- continue- content = choices[0].get("delta", {}).get("content", "") if choices else ""- if content:- full_response += content- if _stream_consumer:- _stream_consumer.on_delta(content)if len(buffer) > _GATEWAY_PROXY_SSE_BUFFER_MAX_CHARS:raise ValueError("Proxy SSE stream exceeded max buffer size without a line boundary")+ # The final SSE frame may not be newline-terminated: flush the residual+ # buffer after EOF instead of silently dropping its content.+ if not saw_done and buffer:+ saw_done = _consume_sse_line(buffer)+ if not saw_done:+ # Clean EOF without [DONE] — the upstream dropped the response+ # mid-stream. Keep any partial text but say so instead of+ # presenting the truncation as a complete answer.+ logger.warning(+ "Proxy SSE stream from %s ended without [DONE] — response may be truncated "+ "(%d chars received)", proxy_url, len(full_response),+ )+ if not full_response:+ return self._proxy_error_result(+ "⚠️ Proxy connection closed before the response completed")except asyncio.CancelledError:raiseexcept Exception as e:diff --git a/tests/gateway/test_proxy_mode.py b/tests/gateway/test_proxy_mode.pyindex 8dfd1370ec0..c36e6355c62 100644--- a/tests/gateway/test_proxy_mode.py+++ b/tests/gateway/test_proxy_mode.py@@ -285,6 +285,135 @@ class TestRunAgentViaProxy:assert messages[0]["content"] == "hello"+class TestStreamingResilience:+ """Tests for SSE streaming robustness — hang avoidance and malformed-chunk tolerance."""++ @pytest.mark.asyncio+ async def test_done_marker_stops_reading_trailing_chunks(self, monkeypatch):+ """After `[DONE]`, no further SSE chunks must be processed.++ A buggy upstream that holds the connection open and streams more+ chunks after `[DONE]` should not leak those chunks into the+ response. Regression test for the inner `break` that only exited+ the line-parse loop, leaving the outer chunk loop to keep reading+ until sock_read timeout.+ """+ monkeypatch.setenv("GATEWAY_PROXY_URL", "http://host:8642")+ monkeypatch.delenv("GATEWAY_PROXY_KEY", raising=False)+ runner = _make_runner()+ source = _make_source()++ # Content → [DONE] → MORE content. The trailing chunk must be+ # dropped. With the pre-fix code it would be appended to+ # full_response, since `break` only exited the inner loop.+ resp = _FakeSSEResponse(+ status=200,+ sse_chunks=[+ 'data: {"choices":[{"delta":{"content":"Hello"}}]}\n',+ 'data: [DONE]\n',+ 'data: {"choices":[{"delta":{"content":" IGNORED"}}]}\n',+ ],+ )+ 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"++ @pytest.mark.asyncio+ async def test_client_timeout_sets_sock_connect(self, monkeypatch):+ """ClientTimeout must bound the TCP connect phase.++ Without an explicit ``sock_connect``, an unreachable proxy host+ hangs for the OS default (minutes) before failing. The fix sets+ a short connect cap so the gateway surfaces the error quickly.+ """+ 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: [DONE]\n'])+ session = _FakeSession(resp)++ captured = {}++ def _capture_timeout(**kwargs):+ captured.update(kwargs)+ return MagicMock()++ with patch("gateway.run._load_gateway_config", return_value={}):+ with _patch_aiohttp(session):+ with patch("aiohttp.ClientTimeout", side_effect=_capture_timeout):+ await runner._run_agent_via_proxy(+ message="hi",+ context_prompt="",+ history=[],+ source=source,+ session_id="test",+ )++ assert "sock_connect" in captured, (+ "ClientTimeout should set sock_connect to bound TCP connect"+ )+ assert 0 < captured["sock_connect"] <= 60, (+ f"sock_connect should be a short, reasonable cap — got {captured['sock_connect']}"+ )++ @pytest.mark.asyncio+ async def test_malformed_chunk_is_skipped_not_fatal(self, monkeypatch):+ """One bad SSE chunk must not abort the whole stream.++ Pre-fix: `choices[0].get(...)` raised ``AttributeError`` when+ ``choices[0]`` was ``None``, escaping the narrow+ ``except json.JSONDecodeError`` and bubbling to the outer+ ``except Exception`` which returned whatever partial response+ was accumulated. All later chunks were lost.++ Post-fix: type guards + broader exception handling skip the bad+ chunk and keep parsing.+ """+ 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":[null]}\n',+ 'data: {"choices":"wrong-type"}\n',+ 'data: {"choices":[{"delta":"wrong-type"}]}\n',+ 'data: {"choices":[{"delta":{"content":" world"}}]}\n',+ 'data: [DONE]\n',+ ],+ )+ 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"++class TestEnvVarRegistration:"""Verify GATEWAY_PROXY_URL and GATEWAY_PROXY_KEY are registered."""