AsyncStream does not close its SSE decoder and byte iterators before releasing the response
Version: openai 3.46.0 (also main as of 2026-11-09), src/openai/_streaming.py
What happens
AsyncStream.__aiter__ is an async generator that delegates to self._iterator, and
_iter_events iterates self._decoder.aiter_bytes(self.response.aiter_bytes()) without closing
either inner iterator. AsyncStream.close() / __stream__'s cleanup call response.aclose()
only. When a consumer stops early, the decoder generator and the byte iterator are left suspended
and are finalized later by the garbage collector, possibly concurrently with other streams, instead
of being closed before the response they read from is released.
Expected
-
__aiter__returnsself(the class already implements__anext__), removing one generator layer. -
_iter_eventscloses what it opened:body = self.response.aiter_bytes() events = self._decoder.aiter_bytes(body) try: async for sse in events: yield sse finally: try: if isinstance(events, AsyncGenerator): await events.aclose() finally: await body.aclose() -
close()and the end of__stream__close the iterator before the response:try: await self._iterator.aclose() finally: await self.response.aclose()
How we test it: an httpx.AsyncByteStream whose __aiter__ sets a flag in its finally,
served through MockTransport, consumed through a Responses stream with an early break; with
this change the body and its iterator are both closed when the consumer's aclosing block exits.
We run this as a local patch; happy to open a PR.
I reproduced this and put together a fix on a branch, since PRs here are limited to collaborators: https://github.com/xh123637/openai-python/tree/fix/4262-async-stream-close-iterators (based on ea5d160; src/openai/_streaming.py is unchanged on upstream main since then).
What I verified first: on an early break, close() only closed the response — the SSE decoder generator and the byte iterator were left suspended for the garbage collector. A new test with a tracking decoder fails on current main (['response'] closed, decoder never closed) and passes with the fix.
The change, in src/openai/_streaming.py:
__aiter__returnsselfinstead of delegating through another async generator (the class already implements__anext__)._iter_eventsholds on to the body and decoder iterators and closes both in afinally, innermost first.__stream__'sfinallynow closes the event iterator before closing the response. This part matters: closing the outer generator does not synchronously close the inner one (I checked with a small async-generator experiment — the innerfinallyonly runs via the event-loop finalizer), so without it the decoder would still only be closed by GC.close()closesself._iteratorfirst, then the response (in afinally, so the response still closes if that raises).
Test: tests/test_streaming.py::test_async_stream_early_break_closes_iterators_before_response — breaks out of the stream inside aclosing(...) and asserts the decoder closes before the response, and that the byte iterator is closed. Full tests/test_streaming.py: 60 passed; the 4 failures are the pre-existing test_done_http11_connection_reuse[...-aiohttp] cases, which fail because the aiohttp extra is not installed in my environment. ruff check and ruff format --check are clean on both touched files.
One thing worth knowing: with httpx2, closing the byte iterator can itself close the response (aiter_raw's finally calls response.aclose()), so the response may be closed more than once on this path — that is idempotent, and the test allows for it while still asserting the decoder closes first.
Happy to adjust the approach if a maintainer prefers a different shape.
I investigated this issue and implemented a fix in my fork:
Branch: [fix/4262-async-stream-close-iterators](https://github.com/alobroke/openai-python/tree/fix/4262-async-stream-close-iterators)
Commit: 4b268817 — fix: close async stream iterators on early exit
I attempted to open a pull request against openai/openai-python:main, but GitHub currently restricts PR creation to repository collaborators. I'm sharing the implementation and verification details here for review.
1. Root cause
The issue occurs when a consumer stops reading an AsyncStream before the stream is exhausted, for example, by using break.
The existing implementation closes the HTTP response, but does not explicitly close all the nested async iterators involved in reading and decoding the SSE response.
In particular:
AsyncStream.__aiter__creates an additional async-generator wrapper aroundself._iterator._iter_events()iterates over the SSE decoder and response byte iterator without explicitly managing their cleanup.close()and the finalizer in__stream__()close the response without first ensuring that the nested iterators are closed.
As a result, the decoder and byte iterators can remain suspended and have their cleanup deferred until asynchronous-generator finalization or garbage collection. This makes resource cleanup less deterministic.
2. Implementation details
I made the following changes in src/openai/_streaming.py.
A. Simplified __aiter__()
Changed it to:
def __aiter__(self) -> Self:
return self
The class already implements __anext__(), so an additional async-generator wrapper is unnecessary. Returning self removes that extra generator layer.
B. Explicitly close the decoder and byte iterators in _iter_events()
The method now stores both iterators:
body = self.response.aiter_bytes()
events = self._decoder.aiter_bytes(body)
It then closes them inside a finally block, in this order:
- Close the SSE decoder iterator.
- Close the underlying response byte iterator.
The nested try/finally ensures that cleanup of the byte iterator is still attempted even if closing the decoder raises an exception.
C. Close the event iterator before the response in __stream__()
The finalizer now explicitly calls:
await iterator.aclose()
before:
await response.aclose()
The response is closed inside a finally block so that its cleanup is still attempted if closing the event iterator raises.
This is important because closing the outer stream generator does not necessarily synchronously finalize the inner event generator. Explicitly closing the event iterator ensures its cleanup runs before the response is released.
D. Update close()
AsyncStream.close() now closes self._iterator first and then closes the response:
try:
await self._iterator.aclose()
finally:
await self.response.aclose()
The existing aclose() alias continues to delegate to close().
3. Regression test
I added:
tests/test_streaming.py::test_async_stream_early_break_closes_iterators_before_response
The test uses a tracking SSE decoder and an async response body. It starts consuming the stream, processes one event, and then exits early using aclosing(...).
It verifies that:
- The decoder iterator's cleanup runs before the response is closed.
- The response is closed after the stream exits.
- The underlying byte iterator has been finalized (
ag_frame is None).
The test also accounts for the possibility that closing the underlying byte iterator may itself close the response, so the response close operation can be invoked more than once.
4. Verification results
I tested the changes locally on Windows using Python 3.10.16.
Focused async stream and connection-related tests:
38 passed, 28 skipped, 32 deselected
This selection included async stream cleanup, request-error handling, and HTTP/1.1 connection-reuse tests. The aiohttp extra was installed before running these tests.
Regression test and existing Unicode tests:
3 passed, 95 deselected
This includes:
test_async_stream_early_break_closes_iterators_before_responsetest_special_new_line_character[sync]test_special_new_line_character[async]
Code quality checks:
ruff check src/openai/_streaming.py tests/test_streaming.py— passed.ruff format --check src/openai/_streaming.py tests/test_streaming.py— passed.git diff --check— passed.git diff --cached --check— passed.
I have not claimed that the entire streaming test module passes; the results above are from the specific test selections listed.
5. Request for review
The implementation and regression test are available in my fork:
https://github.com/alobroke/openai-python/tree/fix/4262-async-stream-close-iterators
I'm happy to adjust the implementation or test structure based on maintainer feedback.
Thank you!