openai-python icon indicating copy to clipboard operation
openai-python copied to clipboard

fix(streaming): drain response body after [DONE] to prevent connection destruction

Open mukktinaadh opened this issue 4 months ago • 0 comments

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:

  1. TCP FIN emitted immediately after [DONE], producing downstream_remote_disconnect spikes on upstream proxies (envoy, nginx, custom gateways).
  2. Occasional httpcore.RemoteProtocolError / httpx.RemoteProtocolError: peer closed connection without sending complete message body on 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 both Stream.__stream__ and AsyncStream.__stream__.

mukktinaadh avatar Jul 16 '26 18:07 mukktinaadh