Skip to content

fix: shield Query.close() wait against cross-task cancel scope error#1042

Open
ashishpatel26 wants to merge 1 commit into
anthropics:mainfrom
ashishpatel26:fix/issue-983-query-close-cancel-scope
Open

fix: shield Query.close() wait against cross-task cancel scope error#1042
ashishpatel26 wants to merge 1 commit into
anthropics:mainfrom
ashishpatel26:fix/issue-983-query-close-cancel-scope

Conversation

@ashishpatel26

Copy link
Copy Markdown

Summary

Resolves #983

Query.close() raised 'Attempted to exit cancel scope in a different task' when invoked during async-generator teardown (aclose()). The read task was spawned in one task context but cancelled+awaited from another, violating anyio/trio's cancel-scope invariant.

Root Cause

close() called await self._read_task.wait() from a different task than the one that created the read task. Under trio, cancel scopes must be entered and exited in the same task.

Fix

Wrap the wait() call in anyio.CancelScope(shield=True) so the wait completes cleanly even when the calling task is itself being cancelled.

Changes Made

  • src/claude_agent_sdk/_internal/query.py: shield the read-task wait() in close() with anyio.CancelScope(shield=True)
  • tests/test_query.py: regression test for close() called from async-generator teardown

Testing

  • Regression test added
  • All existing tests pass (39/39)

Related Issue

Closes #983

…nthropics#983)

Query.close() raised 'Attempted to exit cancel scope in a different
task' when called during async-generator teardown (aclose()). Shield
the read-task wait so it completes cleanly regardless of the calling
task's cancellation state.
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.

Query.close() raises 'Attempted to exit cancel scope in a different task' during async-generator teardown

1 participant