Repository navigation
Conversation
async_request_streamed raises APIError from inside its `async for` over the
response when the server sends an `{"error": ...}` event. Leaving an
`async for` by exception does not close the iterator, so
HttpResponse.async_segments and the _aiter_response_stream it reads stay
suspended. The connection is released only when the garbage collector
finalizes them, which asyncio does later in a task of its own, outside the
Context of the request that failed.
Wrap both loops in contextlib.aclosing, so the stream is closed before the
error reaches the caller. Annotate the two generators as AsyncGenerator so
the type checker accepts them as closeable.
|
Hi @rcleveng, Thanks for reaching out us! |
|
Hey @Venkaiahbabuneelam I updated it yesterday and then again today - PTAL |
1AbdullahButt
left a comment
There was a problem hiding this comment.
Looks correct. Here's what I checked.
aclosingactually closes the connection. Closing_aiter_response_stream()runs itsfinally, whichawaitsresponse_stream.aclose()for httpx (_api_client.py:609on the branch). The aiohttp branch has a matchingtry/finallythat callsself.response_stream.release(). So the outeraclosing(:2254) closesasync_segments, which closes the inneraclosing(:479), which releases the response beforeAPIErrorreaches the caller. That's what the new test checks withaclose.assert_awaited_once()right after the raise.- Both wrappers are needed, as the description says.
GeneratorExitthrown intoasync_segmentsat itsyieldleaves itsasync forwithout closing_aiter_response_stream, so dropping the inneraclosingwould leave the response open again. - Using
response.async_segments()instead ofasync for chunk in responsedoesn't change anything.HttpResponse.__aiter__only storesself.async_segments()insegment_iteratorand returnsself. Nothing in_api_client.pyreadssegment_iteratorexcept__anext__and_copy_to_dict. The first isn't used on this path anymore, and a code search finds no callers of the second. contextlib.aclosingis available, becauserequires-pythonis>=3.11(it was added in 3.10).- Inside
_aiter_response_stream,_aiter_sse_lines(response_stream.aiter_bytes())is still left to the GC after thefinally. That's harmless, because the response it reads from is already closed by then.
Not covered by this PR, and fine as a follow-up: a caller that breaks out of async for over the stream from generate_content_stream still leaves async_generator() suspended until GC, so it hits the same late close. The fix there would be on the caller's side (aclosing around the returned stream), which this PR doesn't touch.
I didn't run the tests.
Reviewed with help from Claude Code.
chrikrah
left a comment
There was a problem hiding this comment.
@rcleveng Nothing here blocks a merge: your test fails without the change and passes with it.
$ python -m pytest google/genai/tests/client/test_async_stream.py google/genai/tests/client/test_client_close.py google/genai/tests/client/test_retries.py -q -p no:cacheprovider
# Python 3.12.14, google-genai 3.3.0 imported from the export of 12f0062
1 failed, 66 passed # head 12f0062; the failure is test_aiohttp_retries_failed_request_retries_unsuccessfully_mtls
2 failed, 65 passed # _api_client.py from base e2f8345: the same mtls test, plus test_error_event_in_streamed_responses_async_closes_stream
# not run: mypy, the replay suite
non-blocking: on the break follow-up raised in the earlier review, aclosing around the returned stream doesn't close the HTTP stream. The generators at models.py:8443, :8124 and :6819 each iterate the next one without closing it, so the fix belongs in models.py, not with the caller.
$ python genai_break.py # mock transport, two chunks then hang; aclosing(generate_content_stream(...)), break after the first
got hi
caller closed its generator with aclosing; http stream aclose awaited: 0
That fits a follow-up, so this PR can stay on the error path. Want me to open the issue?
Sure, thanks |
Problem
When the server sends an
{"error": ...}event partway through a streamed response,BaseApiClient.async_request_streamedraisesAPIErrorfrom inside itsasync forover the response. Leaving anasync forby exception does not close the iterator, so two generators stay suspended:HttpResponse.async_segmentsHttpResponse._aiter_response_stream, whichasync_segmentsreadsThe HTTP response is closed only when the garbage collector finalizes them. asyncio runs that finalization later, in a task of its own, outside the Context of the request that failed. In production we saw this after mid-stream
504 DEADLINE_EXCEEDEDerrors from Gemini: the connection was released late, and context-dependent cleanup (OpenTelemetry spans,ContextVarresets) ran in the wrong Context.Fix
Wrap both loops in
contextlib.aclosing, so the stream is closed before the error reaches the caller. Each wrapper is needed: closingasync_segmentsalone leaves_aiter_response_streamsuspended, because aGeneratorExitleaving anasync fordoes not close that iterator either.async_segmentsand_aiter_response_streamare now annotatedAsyncGeneratorrather thanAsyncIterator, so mypy accepts them as closeable.Testing
test_error_event_in_streamed_responses_async_closes_stream. The mock server sends an error event and keeps the connection open, and the test asserts the stream'saclosehas already run whenServerErrorsurfaces. It fails without the change, and it fails with eitheraclosingremoved.google/genai/testsin--mode tap: no new failures. The tests that fail do so identically with and without the change, because the replay files are not in the public repo.mypy google/genai/: no new errors.