You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
CancelledError leaks from from_thread.check_cancelled on Asyncio backend #1113
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:
importthreadingimportanyioimportpytestpytestmark=pytest.mark.anyioasyncdeftest_anyio_cancel_thread():
tev=threading.Event()
ev=anyio.Event()
asyncdefcancel_detector() ->None:
try:
awaitev.wait()
exceptanyio.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_syncdefget_cancelled():
tev.wait(10) # fake interruptible work for testiftev.is_set:
from_thread.check_cancelled()
# in application, return some computed/retrieved value# return precious_retvalasyncdefdo_cancel():
awaitanyio.sleep(0.01)
g.cancel_scope.cancel()
asyncwithanyio.create_task_group() asg:
g.start_soon(cancel_detector)
g.start_soon(do_cancel)
precious_retval=awaitanyio.to_thread.run_sync(get_cancelled)
ev.set()
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.
Activity
agronholm commentedon Apr 12, 2026
This has to be the dumbest AnyIO bug in a long time. The reason it occurs is because
check_cancelled()raises aCancelledErrorwith a slightly outdated cancel message and thusis_anyio_cancellation()returnsFalsefor theCancelledError.Updated the cancel message in check_cancelled()