Repository navigation
Description
Things to check first
-
I have searched the existing issues and didn't find my bug already reported there
-
I have checked that my bug is still present in the latest release
AnyIO version
master
Python version
python 3.13
What happened?
There is a bug in the asyncio backend where _deliver_cancellation can enter an infinite loop, causing 100% CPU usage.
The root cause is that _deliver_cancellation lacks a task.done() check. If a completed task remains in CancelScope._tasks for any reason, it triggers an infinite spin.
The Spin Mechanism
- A done task is left in
CancelScope._tasks. _deliver_cancellationiterates over it and callstask.cancel()(a no-op for completed tasks in asyncio).- Because the task is already done, the internal state (
_must_cancel) never resolves. - The method sets
should_retry = Trueand reschedules itself viacall_soonforever, locking the event loop.
While leaving a completed task in _tasks usually implies a user misuse, we think a 100% CPU lockup is a mode that should be prevented.
Proposed Fix
Skip completed tasks in _deliver_cancellation:
# anyio/_backends/_asyncio.py -> CancelScope._deliver_cancellation
for task in self._tasks:
if task.done():
continue
should_retry = True
...We can submit a PR with this fix and a test case if the maintainers agree with this approach.
How can we reproduce the bug?
from __future__ import annotations
import asyncio
import gc
from collections.abc import AsyncGenerator
from contextlib import AsyncExitStack
from contextlib import asynccontextmanager
import anyio
from anyio._backends._asyncio import CancelScope
_deliver_call_count: int = 0
_original_deliver_cancellation = CancelScope._deliver_cancellation
def _counting_deliver_cancellation(
self: CancelScope,
origin: CancelScope,
) -> bool:
global _deliver_call_count
_deliver_call_count += 1
return _original_deliver_cancellation(self, origin)
CancelScope._deliver_cancellation = _counting_deliver_cancellation # type: ignore[assignment]
@asynccontextmanager
async def open_connection() -> AsyncGenerator[str, None]:
"""Open a connection backed by an anyio TaskGroup."""
async with anyio.create_task_group() as tg:
async def _reader() -> None:
try:
await asyncio.Event().wait()
except asyncio.CancelledError:
pass
tg.start_soon(_reader)
try:
yield "connection"
finally:
tg.cancel_scope.cancel()
async def create_client() -> str:
"""Open a connection and perform a handshake.
If the handshake fails, the ``AsyncExitStack`` is never closed and
the ``open_connection`` generator is abandoned.
"""
stack = AsyncExitStack()
await stack.enter_async_context(open_connection())
# Handshake fails — e.g. server returns 401 Unauthorized.
# stack.aclose() is never called.
raise RuntimeError("handshake failed")
_SPIN_THRESHOLD = 50
async def main() -> None:
global _deliver_call_count
async def _worker() -> None:
try:
await create_client()
except Exception:
pass # error logged; move on
task = asyncio.create_task(_worker())
await task
# task is done. Force GC — the abandoned generator's finalizer
# will run in a *new* asyncio.Task (cross-task CancelScope exit).
del task
gc.collect()
# Give the finalizer task a chance to run and the initial (legitimate)
# cancellation deliveries to complete.
await asyncio.sleep(0.1)
# Reset counter and measure over a short idle window.
_deliver_call_count = 0
await asyncio.sleep(0.5)
count = _deliver_call_count
print(f"_deliver_cancellation called {count} times during 0.5 s idle window")
if count > _SPIN_THRESHOLD:
print("BUG: _deliver_cancellation is spinning!")
raise SystemExit(1)
else:
print("OK: _deliver_cancellation is not spinning.")
if __name__ == "__main__":
asyncio.run(main())
Activity
asyncio: skip done tasks in _deliver_cancellation to prevent CPU spin
agronholm commentedon Apr 12, 2026
Is all of this code truly necessary to reproduce the issue? I.e. a connection must be made or the bug won't be hit?
kkpattern commentedon Apr 12, 2026
No, that’s not necessary. It will trigger as long as a completed task remains in
CancelScope._tasks. The above example is abstracted from our actual production code.agronholm commentedon Apr 17, 2026
It's possible that completed tasks remain in
CancelScope._tasks, but those would be cleared on the next iteration. Thus I'm maybe not understanding the 100% CPU spin claim.The snippet you provided results in
RuntimeError: Attempted to exit cancel scope in a different task than it was entered in. Does reproducing the problem require the misuse of cancel scopes?kkpattern commentedon Apr 18, 2026
Yes. I believe this issue only occurs when a cancel scope is misused. But I think it would be better if we could still try to prevent CPU spinning even in cases of misuse.
m-u-xyz commentedon May 11, 2026
Frankly this example doesn't just abuse cancel scopes, it also misuses the async exit stack. Python really should raise an exception when you add a context to a stack whose context hasn't been entered.
I have no idea how to fix that correctly, but silently skipping done tasks masks the error instead of alerting the programmer that something's seriously wrong.
m-u-xyz commentedon May 11, 2026
https://discuss.python.org/t/raise-an-error-when-entering-an-asyncexitstack-without-a-context/107321
agronholm commentedon May 11, 2026
I'm leaning towards closing this as this never happens with legit use, and even when misused it doesn't hang the process.
kkpattern commentedon May 12, 2026
I agree. Maybe we can assert task shouldn't be done in the
_deliver_cancellation, so developer can quickly know they misused the cancel scope?agronholm commentedon May 17, 2026
As I understand, not skipping done tasks just makes the CPU spin its wheels for a while but eventually does raise the appropriate exception, right? If this is a case, then I feel it's pointless to fix this as it's a non-issue.
Skip done tasks in asyncio _deliver_cancellation
eric-distyl-ai commentedon Jun 9, 2026
My team is having a serious problem that basically forces us to monkeypatch this.
We are running multiple instances of the Claude Agent SDK in a single process, and a bug in that SDK is causing this spin to be triggered. This causes the process to become degraded (100% CPU spin) in a hard-to-debug way.
It would be greatly preferable if this error state either failed fast or was gracefully tolerated. (Failing fast might be disruptive, though, since the Claude Agent SDK is very widely used.)
agronholm commentedon Jun 9, 2026
Well, this is the first acceptable rationale I've heard for adding this mitigation. Given that it's only two lines of code, I'm favorable to this now.
agronholm commentedon Jun 9, 2026
@eric-distyl-ai Is there a downstream issue you could link to?
tapetersen commentedon Jun 9, 2026
@eric-distyl-ai I've been looking into the issues in the SDK and anthropics/claude-agent-sdk-python#378 Is the main issue reporting 100% cpu. The original error really is that generators don't play nice with contextmanagers that depends on correct nesting (anyio's TaskGroups and CancelScopes are a common example but it's more general) and the general approach of avoiding TaskGroups and suppressing errors as they seem to do very easily leads to situations where a task is repeatably cancelled but ignores it and therefore never gets marked as done at all.
Are you seeing this specific behavior of spinning due to done tasks being cancelled or just a general 100% cpu traced to deliver_cancellation?
What are you monkeypatching that helps you? Is it applying this exact fix or some other change?
agronholm commentedon Jun 24, 2026
So here's where I stand on this right now. There are a couple (AI-generated) PRs for this, but the tests are horribly hacky and thus unacceptable. I need a fairly simple regression test for this in order to get the fix in.
Fixed 100% CPU spin on cancel scope misuse (agronholm#1217)
ef-mcpo-anyio: inventory rows name openbrain-mcpo:local (mcpo digest …
Merge work/eng-followups (part 2): mcpo CPU-spin fix + guard