AsyncStream leaves its SSE event iterators to the garbage collector after [DONE] or close()
Maintainer antworten meist innerhalb von 1 Tag
Dieses Issue hat noch niemand übernommen.
Bewertung
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Anfängerfreundlichkeit
- 35/100
Rechercherichtung
Start with src/openai/_streaming.py and trace how AsyncStream.__stream__, _iter_events, close(), and the __aiter__ wrapper open and close their iterators. Read the linked pull request for the proposed cleanup policy and regression tests, then check whether its tests cover full reads and early exits. Done means the stream generators are explicitly closed across those paths and cleanup errors follow the stated policy.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Beschreibung
Confirm this is an issue with the Python library and not an underlying OpenAI API
- This is an issue with the Python library
Describe the bug
AsyncStream never closes the async generators it opens. After a stream is read to [DONE], or after the caller stops early and calls await stream.close(), these generators are still suspended and are only closed when the garbage collector reaches them:
AsyncStream._iter_events- the decoder iterator (
SSEDecoder.aiter_bytes) - the
response.aiter_bytes()iterator it wraps - after an early exit, the
AsyncStream.__aiter__wrapper
Where this happens in src/openai/_streaming.py (v3.37.0):
__stream__breaks out ofasync for sse in iteratorat[DONE]. Itsfinallycloses onlyresponse, notiterator._iter_eventsiteratesself._decoder.aiter_bytes(self.response.aiter_bytes()). An interruptedasync fordoes not close the iterator it was looping over, so neither of those two is closed.close()closes onlyresponse, notself._iterator.
asyncio's GC finalizer starts a separate aclose() task for each unreachable async generator. A nested chain that becomes unreachable at the same time is therefore closed concurrently. In production (Python 3.13, httpx2 2.13.1) this logs:
Task exception was never retrieved
future: <Task finished name='Task-1220' coro=<<async_generator_athrow without __name__>()> exception=RuntimeError('aclose(): asynchronous generator is already running')>
That generator is never closed, so its cleanup does not run. The httpx2 half of the race, inside httpx2's own nested iterators, is pydantic/httpx2#1280, fixed by pydantic/httpx2#1281. Even with that PR, the openai-owned generators above are still left to the GC.
This is separate from #3440 / #4040 (connection reuse after [DONE]) and from #3561 (server-side state after an aborted stream).
To Reproduce
The script below is self-contained: a local SSE server, no API key.
import asyncio, gc, sys, collections, json
import openai
CHUNK = {"id": "x", "object": "chat.completion.chunk", "created": 0, "model": "m",
"choices": [{"index": 0, "delta": {"content": "hi"}, "finish_reason": None}]}
async def handle(reader, writer):
while (await reader.readline()) not in (b"\r\n", b""):
pass
body = "".join(f"data: {json.dumps(CHUNK)}\n\n" for _ in range(3)) + "data: [DONE]\n\n"
writer.write(b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ncontent-length: %d\r\n\r\n"
% len(body) + body.encode())
await writer.drain()
writer.close()
async def main():
loop = asyncio.get_running_loop()
original, finalized = loop._asyncgen_finalizer_hook, collections.Counter()
def hook(agen):
finalized[agen.__qualname__] += 1
original(agen)
sys.set_asyncgen_hooks(firstiter=loop._asyncgen_firstiter_hook, finalizer=hook)
server = await asyncio.start_server(handle, "127.0.0.1", 0)
client = openai.AsyncOpenAI(api_key="x", base_url=f"http://127.0.0.1:{server.sockets[0].getsockname()[1]}/v1")
for case in ("full read", "early exit + close()"):
stream = await client.chat.completions.create(model="m", messages=[{"role": "user", "content": "x"}], stream=True)
async for _ in stream:
if case != "full read":
break
await stream.close()
del stream
gc.collect()
await asyncio.sleep(0.2)
print(f"{case}: finalized by GC = {dict(finalized) or 'none'}")
finalized.clear()
await client.close()
server.close()
asyncio.run(main())
Output with openai 3.37.0 and httpx2 2.16.0 on Python 3.13.16:
full read: finalized by GC = {'AsyncStream._iter_events': 1, 'SSEDecoder.aiter_bytes': 1, 'Response.aiter_bytes': 1, 'PoolByteStream.__aiter__': 1}
early exit + close(): finalized by GC = {'AsyncStream.__aiter__': 1}
With the change below:
full read: finalized by GC = {'PoolByteStream.__aiter__': 1} # httpx2-internal, see pydantic/httpx2#1281
early exit + close(): finalized by GC = {'PoolByteStream.__aiter__': 1}
With the change below and httpx2 at pydantic/httpx2#1281, the only generator left is the httpcore2-internal HTTP11ConnectionByteStream.__aiter__. On its own it cannot race.
Suggested fix
Close what each layer opens, with one cleanup policy:
- Try every resource.
- An exception already propagating, or leaving a
withblock, wins over a cleanup error. - Cancellation is never dropped.
- Normal closure does not hide cleanup errors.
The same applies to the Chat, Responses and agent stream wrappers. The full diff, with regression tests that fail on main and pass with the fix, is here: https://github.com/fancyboi999/openai-python/pull/1
Checks run against main (718aee9):
- Whole suite except
tests/api_resourcesandtests/lib/live: 10201 passed (+41 new) and no new failures. - ruff, mypy and pyright 1.1.414 are clean.
OS
Linux / macOS
Python version
3.13.16 (also reproduced on 3.12.11)
Library version
openai 3.37.0 (also 3.29.0), httpx2 2.16.0 (also 2.13.1)
- Vorherrschende Sprache
- Python
- Sterne
- 32.2k
- Forks
- 5.8k
- Ø Merge
- 12 Std. 29 Min.
- Gemergte PRs (30 T.)
- 112
Entwicklungsumgebung
Startet den Dev-Container des Projekts im Browser, mit Ihrem eigenen GitHub-Konto.
- Kein Dockerfile und keine Docker-Compose-Datei
- Hat eine Pull-Request-Vorlage
- Beitragsleitfaden lesen
Erste Schritte
- Lesen Sie das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreiben Sie ins Issue, dass Sie es übernehmen — das erspart doppelte Arbeit.
- Forken Sie das Repository und arbeiten Sie in einem Branch.
- Öffnen Sie einen Pull Request, der die Issue-Nummer nennt.
Mehr aus openai/openai-python
-
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 76/100
openai/openai-python#4338 ·
Maintainer antworten meist innerhalb von 1 Tag
-
bug
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 65/100
openai/openai-python#4337 ·
Maintainer antworten meist innerhalb von 1 Tag
-
`BaseClient._prepare_url()` corrupts relative endpoint URLs when `base_url` contains query parametersEvtl. vergeben @Rewaskc02-lang hat das vor 1 Tag übernommen. Offen
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 78/100
openai/openai-python#4311 · 4 Kommentare ·
Maintainer antworten meist innerhalb von 1 Tag
-
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 78/100
openai/openai-python#4310 · 1 Kommentar ·
Maintainer antworten meist innerhalb von 1 Tag
-
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 82/100
openai/openai-python#4309 · 1 Kommentar ·
Maintainer antworten meist innerhalb von 1 Tag
Alle Issues in openai/openai-python
Ähnliche Issues
-
triage
Schwierigkeit 1/5 1-3 Stunden Anfängerfreundlichkeit 88/100
kornia/kornia-rs#1416 · 1 Kommentar ·
Maintainer antworten meist innerhalb von 2 Tagen
-
ui
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 78/100
Maintainer antworten meist innerhalb von 1 Tag
-
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 76/100
PolicyEngine/ai-inequality#64 ·
Maintainer antworten meist innerhalb von 1 Tag
-
LinearGaussianStateSpace.dist splits states and observations wrongly when the transition varies over timeEvtl. vergeben @PabloRoque hat das heute übernommen. Offen
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 88/100
pymc-devs/pymc-extras#839 ·
Maintainer antworten meist innerhalb von 1 Tag
-
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 76/100
Maintainer antworten meist innerhalb von 1 Tag