Repository navigation
fix(streaming): run async generator cleanup when a stream is dropped - #1450
Zhiguo-Chen wants to merge 1 commit into
Conversation
When a client disconnects, the Rust driver drops the AsyncGeneratorWrapper
before the generator is exhausted. The wrapper never closed the generator,
so it was finalized synchronously on whichever thread released it: its
`finally` / `async with` cleanup aborted at the first `await` ("async
generator ignored GeneratorExit"). Anything released that way, such as a
pooled DB connection, was never returned.
Register the finalizer for both the handler-loop and background-loop
branches, and have it schedule `aclose()` on the generator's own loop,
stopping the background loop (sync handlers) once that cleanup is done.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configuration
📒 Files selected for processing (4)
Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. 📝 WalkthroughWalkthroughAsyncGeneratorWrapper now schedules unfinished async-generator cleanup on its associated event loop. Unit and integration tests cover cleanup after wrapper abandonment and an SSE client disconnect. ChangesStream cleanup
Priority: ➖ Normal Estimated code review effort: 2 (Simple) | ~15 minutes Change: Bug fix Merge Risk: ⚪ Minimal · up to The cleanup change is mergeable after normal checks; no actionable merge-blocking risk is established. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1🛠️ Fix failing CI checks 💡
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Description
Follow-up to #1412 (#1219). No existing issue covers this.
Summary
AsyncGeneratorWrapperno longer leaks an event loop per stream (#1412), but when a client disconnects the generator's async cleanup still never runs.On disconnect,
create_python_streaminsrc/types/response.rsdrops the wrapper before the generator is exhausted. The wrapper never closes the generator, so the generator is finalized synchronously on whichever thread drops the last reference. Its first__anext__()call was made on a tokio worker thread, which has no asyncgen hooks installed, so the event loop never tracks the generator. CPython then falls back to a synchronousclose(). Cleanup code infinally/async withruns up to its firstawaitand then aborts:So anything that needs an
awaitto be released is never released. A typical case is an async SQLAlchemy session or a Redis client that returns its connection to a pool. With an endless SSE stream and clients that reconnect, the pool runs dry. In the handler-loop branch, which serves everyasync defhandler, nothing closes the generator at all. The background-loop branch stops its loop, but it does not close the generator either.Fix: register the existing
weakref.finalizefor both branches. Its callback schedulesasync_gen.aclose()on the generator's own loop withrun_coroutine_threadsafe. For sync handlers, the callback stops the background loop once that cleanup is done.aclose()is a no-op for a generator that has already finished, so streams that end normally behave as before.Tests
integration_tests/test_sse.py::test_sse_disconnect_runs_async_generator_cleanup): goes through the real Rust driver. The test reads one event from an endless async SSE stream, closes the connection, and then polls a status route until the generator's awaitingfinallyreports completion.main, it fails, and the server log showsasync generator ignored GeneratorExit.unit_tests/test_streaming_response.py): one test per branch, the handler loop and the background loop. Each test abandons a stream after one chunk and asserts that theawaitinfinallycompletes, on the handler's loop for the first branch. Both tests fail onmain.pytestgives 543 passed (374 integration and 169 unit).ruff check .,ruff format --check .(ruff 0.14.13, as pinned in pre-commit) andisort --check-only .are all clean. The new unit tests also pass 30 times in a row underpython -X dev -W error.PR Checklist
Please ensure that:
finallycleanup works)Pre-Commit Instructions:
🤖 Generated with Claude Code
Summary by CodeRabbit