Skip to content

The agent that grows with you

fix(gateway): stop proxy reads immediately at the completion marker

David Dudok de Witaacc466da645
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index 09d3ea19f07..c8727567788 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -935,10 +935,6 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gateway
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.
- break
if not _run_still_current():
return _stale_result("stream")
buffer += chunk.decode("utf-8", errors="replace")
@@ -947,6 +943,9 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gateway
if _consume_sse_line(line):
saw_done = True
break
+ # Exit before the iterator requests another network chunk.
+ if saw_done:
+ break
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
diff --git a/tests/gateway/test_proxy_mode.py b/tests/gateway/test_proxy_mode.py
index c4aed5c87a0..f4b8dbb6cc8 100644
--- a/tests/gateway/test_proxy_mode.py
+++ b/tests/gateway/test_proxy_mode.py
@@ -42,12 +42,14 @@ class _FakeSSEResponse:
self._sse_chunks = sse_chunks or []
self._error_text = error_text
self.content = self
+ self.chunks_requested = 0
async def text(self):
return self._error_text
async def iter_any(self):
for chunk in self._sse_chunks:
+ self.chunks_requested += 1
if isinstance(chunk, str):
chunk = chunk.encode("utf-8")
yield chunk
@@ -392,6 +394,10 @@ class TestStreamingResilience:
assert result["final_response"] == "Hello"
+ # Fetching the next chunk already waits on the peer; dropping it after
+ # arrival is too late when the peer leaves the completed stream open.
+ assert resp.chunks_requested == 2
+
@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.