fix(streaming): drain response body after [DONE] to prevent connection destruction
Summary
Fixes #3440.
Problem
When Stream.__stream__ (sync) or AsyncStream.__stream__ (async) encounters the [DONE] SSE event, it breaks out of the iteration loop and calls response.close() / await response.aclose() in the finally block. At this point, the underlying iter_bytes() / aiter_bytes() has not been fully consumed — the HTTP/1.1 chunked transfer-encoding terminator (0\r\n\r\n) may still be buffered in the kernel or in h11.
Because h11's their_state is still SEND_RESPONSE (not DONE), httpcore takes the "destroy the connection" branch instead of the "return to pool (IDLE)" branch. This causes:
- TCP FIN emitted immediately after
[DONE], producingdownstream_remote_disconnectspikes on upstream proxies (envoy, nginx, custom gateways). - Occasional
httpcore.RemoteProtocolError/httpx.RemoteProtocolError: peer closed connection without sending complete message bodyon subsequent requests.
Fix
Drain the remaining bytes from iter_bytes() / aiter_bytes() after observing [DONE], before the finally block calls close(). This allows h11 to parse the chunked terminator and advance to DONE state, enabling graceful connection reuse.
Regression History
This drain was originally present in 7e2b2544 (2023-11, "fix(client): correctly flush the stream response body") and was removed in 6132922c (2025-10-29, "fix(client): close streams without requiring full consumption"). This commit restores the drain for both sync and async paths.
Changes
src/openai/_streaming.py: Added drain loops after[DONE]break in bothStream.__stream__andAsyncStream.__stream__.