Skip to content

CancelledError leaks from from_thread.check_cancelled on Asyncio backend #1113

Closed

Description

@richardsheridan

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 (after #1092)

Python version

3.10

What happened?

In a slightly contrived setting, the CancelledError from from_thread.check_cancelled escapes the relevant cancel scope on asyncio backend.

How can we reproduce the bug?

This test passes on trio but not asyncio:

import threading
import anyio
import pytest

pytestmark = pytest.mark.anyio


async def test_anyio_cancel_thread():
    tev = threading.Event()
    ev = anyio.Event()

    async def cancel_detector() -> None:
        try:
            await ev.wait()
        except anyio.get_cancelled_exc_class():
            tev.set()
            # we do NOT re-raise the cancellation so that the task group
            # does not swallow our retval. If a Cancelled is to propagate,
            # it should come out of to_thread.run_sync

    def get_cancelled():
        tev.wait(10)  # fake interruptible work for test
        if tev.is_set:
            from_thread.check_cancelled()
        # in application, return some computed/retrieved value
        # return precious_retval

    async def do_cancel():
        await anyio.sleep(0.01)
        g.cancel_scope.cancel()

    async with anyio.create_task_group() as g:
        g.start_soon(cancel_detector)
        g.start_soon(do_cancel)
        precious_retval = await anyio.to_thread.run_sync(get_cancelled)
        ev.set()

Activity

  1. added
    bug
    on Apr 12, 2026
  2. agronholm commented on Apr 12, 2026

    @agronholm
    Owner

    This has to be the dumbest AnyIO bug in a long time. The reason it occurs is because check_cancelled() raises a CancelledError with a slightly outdated cancel message and thus is_anyio_cancellation() returns False for the CancelledError.

  3. added a commit that references this issue on Apr 12, 2026
    db962c3
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