Skip to content

fix(streaming): run async generator cleanup when a stream is dropped - #1450

Open
Zhiguo-Chen wants to merge 1 commit into
sparckles:mainfrom
Zhiguo-Chen:fix/streaming-aclose-on-disconnect
Open

Zhiguo-Chen wants to merge 1 commit into
sparckles:mainfrom
Zhiguo-Chen:fix/streaming-aclose-on-disconnect

Conversation

@Zhiguo-Chen

@Zhiguo-Chen Zhiguo-Chen commented Oct 7, 2026 •

Copy link
Copy Markdown

Description

Follow-up to #1412 (#1219). No existing issue covers this.

Summary

AsyncGeneratorWrapper no 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_stream in src/types/response.rs drops 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 synchronous close(). Cleanup code in finally / async with runs up to its first await and then aborts:

Exception ignored in: <async_generator object ...>
RuntimeError: async generator ignored GeneratorExit

So anything that needs an await to 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 every async def handler, 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.finalize for both branches. Its callback schedules async_gen.aclose() on the generator's own loop with run_coroutine_threadsafe. For sync handlers, the callback stops the background loop once that cleanup is done.

  • The callback does not wait for the result. It can run on any thread, including the loop's own, so blocking there could deadlock.
  • aclose() is a no-op for a generator that has already finished, so streams that end normally behave as before.

Tests

  • Integration (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 awaiting finally reports completion.
    • On main, it fails, and the server log shows async generator ignored GeneratorExit.
    • With this change, it passes.
  • Unit (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 the await in finally completes, on the handler's loop for the first branch. Both tests fail on main.
  • Full suite: pytest gives 543 passed (374 integration and 169 unit). ruff check ., ruff format --check . (ruff 0.14.13, as pinned in pre-commit) and isort --check-only . are all clean. The new unit tests also pass 30 times in a row under python -X dev -W error.

PR Checklist

Please ensure that:

  • The PR contains a descriptive title
  • The PR contains a descriptive summary of the changes
  • You build and test your changes before submitting a PR.
  • You have added relevant documentation (no user-facing API change; the existing streaming docs already assume finally cleanup works)
  • You have added relevant tests. We prefer integration tests wherever possible

Pre-Commit Instructions:

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Streaming responses now reliably finish cleanup when a client disconnects or stops consuming the stream. Asynchronous cleanup work can complete after the connection ends, helping prevent lingering stream-related activity and ensuring resources are released as expected.

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>
@vercel

vercel Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
robyn Error Error Oct 7, 2026 10:43am UTC

@coderabbitai

coderabbitai Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 500d1a01-f445-438e-93c7-a6a6e245b24e
📥 Commits

Reviewing files that changed from the base of the PR and between 1170748 and 2a7c376.

📒 Files selected for processing (4)
  • integration_tests/base_routes.py
  • integration_tests/test_sse.py
  • robyn/responses.py
  • unit_tests/test_streaming_response.py

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.


📝 Walkthrough

Walkthrough

AsyncGeneratorWrapper 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.

Changes

Stream cleanup

Layer / File(s) Summary
Close abandoned generators on their event loop
robyn/responses.py, unit_tests/test_streaming_response.py
The finalizer schedules aclose() on the associated loop. If the wrapper owns the loop, it schedules loop shutdown after generator closure. Unit tests check async cleanup on the handler loop and the owned background loop.
Verify cleanup after SSE disconnect
integration_tests/base_routes.py, integration_tests/test_sse.py
The SSE endpoint yields tick events and sets a cleanup marker when its generator finishes. The integration test closes the response and polls the status route for the marker.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~15 minutes

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 2a7c3

The cleanup change is mergeable after normal checks; no actionable merge-blocking risk is established.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 45.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 20 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: running async-generator cleanup when a stream is dropped.
Description check ✅ Passed The description includes the required Description, Summary, checklist, and pre-commit sections. It explains the bug, fix, and tests in detail. The documentation item is unchecked, but the author expla…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

This branch had an error being deployed

1 failed deployment
Preview — 2a7c3764 Deployed Oct 7, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant