Skip to content

100% CPU spin in asyncio _deliver_cancellation due to missing task.done() check #1111

Closed

Description

@kkpattern

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

  1. A done task is left in CancelScope._tasks.
  2. _deliver_cancellation iterates over it and calls task.cancel() (a no-op for completed tasks in asyncio).
  3. Because the task is already done, the internal state (_must_cancel) never resolves.
  4. The method sets should_retry = True and reschedules itself via call_soon forever, 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

  1. added
    bug
    on Apr 9, 2026
  2. added a commit that references this issue on Apr 10, 2026
    b1616e4
  3. agronholm commented on Apr 12, 2026

    @agronholm
    Owner

    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?

  4. kkpattern commented on Apr 12, 2026

    @kkpattern
    Author

    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?

    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.

  5. agronholm commented on Apr 17, 2026

    @agronholm
    Owner

    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?

  6. kkpattern commented on Apr 18, 2026

    @kkpattern
    Author

    Does reproducing the problem require the misuse of cancel scopes?

    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.

  7. m-u-xyz commented on May 11, 2026

    @m-u-xyz
    Collaborator

    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.

  8. agronholm commented on May 11, 2026

    @agronholm
    Owner

    I'm leaning towards closing this as this never happens with legit use, and even when misused it doesn't hang the process.

  9. kkpattern commented on May 12, 2026

    @kkpattern
    Author

    silently skipping done tasks masks the error instead of alerting the programmer that something's seriously wrong.

    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?

  10. agronholm commented on May 17, 2026

    @agronholm
    Owner

    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.

  11. added a commit that references this issue on May 27, 2026
    6dac368
  12. eric-distyl-ai commented on Jun 9, 2026

    @eric-distyl-ai

    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.)

  13. agronholm commented on Jun 9, 2026

    @agronholm
    Owner

    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.

  14. agronholm commented on Jun 9, 2026

    @agronholm
    Owner

    @eric-distyl-ai Is there a downstream issue you could link to?

  15. tapetersen commented on Jun 9, 2026

    @tapetersen
    Collaborator

    @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?

  16. agronholm commented on Jun 24, 2026

    @agronholm
    Owner

    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.

  17. added a commit that references this issue on Jul 12, 2026
    dbba29d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions