Skip to content

Commit 532c5aa

Browse files
committed
fix: add timeout to Query.close() to prevent CPU busy-loop
When tasks don't respond to cancellation cleanly, anyio's _deliver_cancellation() enters a busy-loop pegging CPU at 50-100%. Set a 5s deadline on the task group's own cancel scope so it times out instead of spinning indefinitely. Ref: #378
1 parent 876d4db commit 532c5aa

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

src/claude_agent_sdk/_internal/query.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -617,7 +617,11 @@ async def close(self) -> None:
617617
self._closed = True
618618
if self._tg:
619619
self._tg.cancel_scope.cancel()
620-
# Wait for task group to complete cancellation
620+
# Set a deadline to prevent _deliver_cancellation() busy-loop
621+
# when tasks don't respond to cancellation cleanly.
622+
# Uses the task group's own scope (not a nested scope) to avoid
623+
# "not the current cancel scope" errors from anyio.
624+
self._tg.cancel_scope.deadline = anyio.current_time() + 5.0
621625
with suppress(anyio.get_cancelled_exc_class()):
622626
await self._tg.__aexit__(None, None, None)
623627
await self.transport.close()

0 commit comments

Comments
 (0)