Fix trio compatibility with owner task pattern for cancel scopes #364
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.
Summary
Problem
The SDK was manually calling
__aenter__and__aexit__on anyio task groups, which violates trio's requirement that cancel scopes must be exited by the same task that entered them. This caused errors like:RuntimeError: Attempted to exit cancel scope in a different task than it was entered in
Solution
Implement the owner task pattern: a dedicated task owns the inner task group for its entire lifetime using proper
async withsemantics. The outer code communicates with this owner task via events:start()spawns the owner task and waits for_owner_started_eventclose()sets_owner_stop_event, signaling the owner to cancel and exit cleanlyThis ensures the inner task group (which does the actual message reading) is always entered and exited by the same task.
Test plan
🤖 Generated with Claude Code