Fix: Raise RuntimeError when ClientSession is used without context manager to prevent hangs #1849
+41
−1
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.
Fixes #1564
Summary
This PR adds a runtime check to
ClientSessionto ensure it is being used within an asynchronous context manager (async with). Ifinitialize()is called without entering the context, it now raises a clearRuntimeErrorinstead of hanging indefinitely.Motivation and Context
Currently, if a user attempts to call
await session.initialize()without wrapping the session in anasync withblock, the program hangs indefinitely. This happens because the background receive loop (_receive_loop) is only started inside__aenter__.This behavior leads to a frustrating debugging experience (deadlock) for developers. This change provides immediate feedback by enforcing correct usage of the session, preventing the deadlock.
How Has This Been Tested?
I reproduced the issue using the script provided in #1564.
await session.initialize().RuntimeError: ClientSession must be used within an 'async with' block., as expected.async with) continues to work correctly.Breaking Changes
No. This change is backward compatible for all correct usages. It only affects code that was previously incorrect and hanging.
Types of changes
Checklist
Additional context
I implemented this using a simple state flag (
_entered) to maintain backward compatibility without requiring significant architectural refactoring of the session class.