Conversation
When a client disconnects mid-stream, the WSGI server abandons the body iterator. The generator is finalized by the garbage collector, often on a different thread than the one that pushed the context. ctx.pop() raises RuntimeError because the context is not active on the GC thread, leaving the context stuck on the original thread. Replace `with ctx:` with manual push()/pop() in the generator, and catch the RuntimeError from cross-thread pop() to properly reset the context state (_push_count and _cv_token). Fixes pallets#6123
Member
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
When a client disconnects mid-stream, the WSGI server abandons the body
iterator. The generator is later finalized by the garbage collector, often
on a different thread than the one that pushed the context.
ctx.pop()raisesRuntimeErrorbecause_cv_app.get(None)returnsNoneon the GC thread. The context stays "stuck" on the original worker thread,
and
teardown_appcontextnever fires for subsequent requests on that thread.Fix
Replace
with ctx:with manualctx.push()/ctx.pop()in thestream_with_contextgenerator. Wrappop()in a try/except that catchesRuntimeErrorand resets the context state (_push_countand_cv_token)to prevent thread pool poisoning.
Related
stream_with_contextdoes not work with async routes #5774 fixed the same cross-context token failure for async viewsstream_with_contexttriggersteardown_request()calls before response generation #5804 covers teardown ordering in the 3.1.2 rewriteCloses #6123