Query.close() can hang indefinitely causing 100% CPU usage due to missing timeout on task group cleanup
Bug Description
The Query.close() method in _internal/query.py can hang indefinitely
if tasks in the anyio task group don't properly respond to cancellation.
This causes anyio's _deliver_cancellation() to spin at 100% CPU.
Affected Code
src/claude_code_sdk/_internal/query.py lines 550-558 (v0.1.10):
async def close(self) -> None:
"""Close the query and transport."""
self._closed = True
if self._tg:
self._tg.cancel_scope.cancel()
# Wait for task group to complete cancellation
with suppress(anyio.get_cancelled_exc_class()):
await self._tg.__aexit__(None, None, None) # ⚠️ NO TIMEOUT
await self.transport.close()
Root Cause
Line 557 await self._tg.__aexit__(None, None, None) has no timeout. If any
task in the task group doesn't properly respond to cancellation (e.g.,
stuck in I/O, waiting on external resource), this call will hang
indefinitely.
When this happens:
1. anyio's _deliver_cancellation() runs in a busy loop trying to deliver
the cancellation
2. This consumes 100%+ CPU indefinitely
3. The caller's event loop becomes unresponsive
How We Discovered This
We're using ClaudeSDKClient in a JupyterLab extension. After calling
client.disconnect() (which calls Query.close()), the Python process would
sometimes spike to 100-150% CPU usage.
Using py-spy profiling, we found:
- _deliver_cancellation from anyio/_backends/_asyncio.py consuming 66% of
CPU
- current_task from asyncio/tasks.py consuming 35% of CPU
Suggested Fix
Add a timeout to the task group cleanup:
async def close(self) -> None:
"""Close the query and transport."""
self._closed = True
if self._tg:
self._tg.cancel_scope.cancel()
with suppress(anyio.get_cancelled_exc_class()):
try:
# Add timeout to prevent indefinite hang
with anyio.fail_after(5.0):
await self._tg.__aexit__(None, None, None)
except TimeoutError:
logger.warning("Task group cleanup timed out after 5s")
await self.transport.close()
Workaround
Callers can wrap disconnect() with a timeout:
try:
await asyncio.wait_for(client.disconnect(), timeout=5.0)
except asyncio.TimeoutError:
logger.warning("Client disconnect timed out")
finally:
client = None
Environment
- claude-agent-sdk version: 0.1.10
- anyio version: 4.11.0
- Python: 3.11.4
- Platform: Linux (Amazon ECS/Fargate)
---
We're hitting this same issue in production - SSE streaming with FastAPI on ECS (Python 3.13).
What happens: When a user refreshes or closes their browser mid-stream, CPU immediately spikes to 100% and stays there until we kill the container. py-spy shows _deliver_cancellation eating 24%+ of cycles in a tight loop.
Our setup:
- claude-agent-sdk 0.1.11
- FastAPI/Starlette SSE
- AWS ECS Fargate, Python 3.13
py-spy sample:
PID: 30 - 98.00% CPU
24.00%: _deliver_cancellation (anyio/_backends/_asyncio.py)
22.00%: cancel_shielded_checkpoint (anyio/_backends/_asyncio.py)
Our app cleanup finishes in ~1ms (we added logging), but the SDK hangs indefinitely in __aexit__. Logs show claude_agent_sdk._internal.query - DEBUG - Read task cancelled right before it gets stuck.
We've applied the timeout workaround and it fixes the CPU issue. This is a production-critical issue for anyone using the SDK with SSE/streaming where clients can disconnect unexpectedly.
Additional reproduction scenario: OOM-killed subprocess (we tried to run on servers with low memory)
We're seeing the same _deliver_cancellation CPU spin in a different context that might help with debugging.
Environment
- claude-agent-sdk: 0.1.18
- Python: 3.12
- Platform: Ubuntu 24.04, low-memory server (933MB RAM)
- Use case: Long-running daemon with session pooling, serving WebSocket clients
Trigger mechanism
- Claude subprocess is OOM-killed by kernel (exit code -9 / SIGKILL)
- Daemon detects error and calls
client.disconnect() - CPU spikes to 100% in
_deliver_cancellation
This differs from the client-disconnect scenario—here the subprocess dies unexpectedly while the SDK is waiting on its stdout.
py-spy output (matches your reports)
anyio._deliver_cancellation (dominant) asyncio._run_once / call_soon
Important finding: asyncio.wait_for() workaround doesn't fully help
We tried the suggested workaround:
await asyncio.wait_for(client.disconnect(), timeout=10.0)
Result: The asyncio timeout fires after 10 seconds, but the CPU spin continues. The anyio task group (Query._tg) keeps spinning independently because asyncio cancellation doesn't propagate into anyio's internal cancel scope.
The Python process continues pegging CPU even after the asyncio wrapper times out and control returns to the caller. We could be killing it via os.kill or something but obviously is far from optimal approach
Hope this additional context helps with the fix!
We’re hitting this in production when an exception is raised from client.receive_response() and client.disconnect() hangs indefinitely. Adding a timeout inside Query.close() hopefully fixes for us.
This is fixed by #746 (merged to main, will be in the next release after v0.1.50).
Root cause: All three reports here traced the 100% CPU spin to anyio._backends._asyncio._deliver_cancellation being called in a tight loop when Query.close() tried to exit the anyio task group via await self._tg.__aexit__(None, None, None). When the task group was exited from a different task context than it was entered (which happens during async generator cleanup, SSE client disconnects, or subprocess OOM-kills), anyio's cancel scope would fail to deliver the cancellation and retry indefinitely.
Fix: #746 replaced the anyio TaskGroup entirely with plain asyncio.create_task() for background task management. The new close() implementation does:
async def close(self) -> None:
self._closed = True
for task in list(self._child_tasks):
task.cancel()
if self._read_task is not None and not self._read_task.done():
self._read_task.cancel()
with suppress(asyncio.CancelledError):
await self._read_task
self._read_task = None
await self.transport.close()
No more anyio cancel scope, so _deliver_cancellation can no longer spin. This also fixes the related #454 (RuntimeError on cross-task cleanup).
Verified: Ran a live SDK test that breaks out of query() early — generator cleanup completed in 1.48s with no CPU spin and no error.
If you're still seeing this on versions after the fix lands, please reopen with a fresh py-spy trace.
Generated by Claude Code
This is fixed by #746 (merged to main, will be in the next release after v0.1.50).
Root cause: All three reports here traced the 100% CPU spin to
anyio._backends._asyncio._deliver_cancellationbeing called in a tight loop whenQuery.close()tried to exit the anyio task group viaawait self._tg.__aexit__(None, None, None). When the task group was exited from a different task context than it was entered (which happens during async generator cleanup, SSE client disconnects, or subprocess OOM-kills), anyio's cancel scope would fail to deliver the cancellation and retry indefinitely.Fix: #746 replaced the anyio
TaskGroupentirely with plainasyncio.create_task()for background task management. The newclose()implementation does:async def close(self) -> None: self._closed = True for task in list(self._child_tasks): task.cancel() if self._read_task is not None and not self._read_task.done(): self._read_task.cancel() with suppress(asyncio.CancelledError): await self._read_task self._read_task = None await self.transport.close() No more anyio cancel scope, so
_deliver_cancellationcan no longer spin. This also fixes the related #454 (RuntimeError on cross-task cleanup).Verified: Ran a live SDK test that breaks out of
query()early — generator cleanup completed in 1.48s with no CPU spin and no error.If you're still seeing this on versions after the fix lands, please reopen with a fresh py-spy trace.
Generated by Claude Code
hi @dicksontsai , you have done a great work! However, here is a problematic case, with v0.1.66 version which in range of fix-land versions, I still see this issue. Could you please have a look on this?
here is the py-spy trace below:
$sudo py-spy dump --pid 2281020 Process 2281020: /home/admin/multi_agent/mc_agent/.venv/bin/python -m uvicorn mc_agent.app:create_app --factory --host 0.0.0.0 --port 8080 Python v3.11.13 (/usr/bin/python3.11)
Thread 2281020 (idle): "MainThread"
run (asyncio/runners.py:118)
run (asyncio/runners.py:190)
run (uvicorn/server.py:66)
run (uvicorn/main.py:580)
main (uvicorn/main.py:460)
invoke (click/core.py:824)
invoke (click/core.py:1269)
main (click/core.py:1406)
call (click/core.py:1485)