Skip to content

asyncio.timeout(0) swallows a prior task cancellation #134471

Open

Description

@okhaliavka

Bug report

Bug description:

async with asyncio.timeout(0) will catch and process a prior unrelated cancellation of the enclosing task.

import asyncio

async def test(timeout):
    task = asyncio.current_task()
    task.cancel()

    try:
        async with asyncio.timeout(timeout):
            await asyncio.sleep(1)
    except TimeoutError:
        print("timeout caught")
    except asyncio.CancelledError:
        print("CancelledError caught")
        raise

    await asyncio.sleep(2)
    print("not cancelled")

asyncio.run(test(timeout=0))  # prints "timeout caught" and "not_cancelled"

This code prints timeout caught and not_cancelled, which means that asyncio.timeout(0) swallows the preceding task.cancel(), so the task pretty much ignores cancellation and proceeds.

Notably, that doesn't happen with a positive timeout. In the above example, asyncio.run(test(timeout=0.001)) will only print CancelledError caught, which I believe is the correct behavior.
In this case, asyncio.Timeout's internal timeout handler (_on_timeout) never gets to run, so the context manager doesn't interfere at all - it doesn't cancel/uncancel the task and simply passes CancelledError through.

Possible solution

I believe this behavior was unintentedly introduced in #102815, where the logic in __aexit__ was changed to only consider new cancel requests when deciding if it should raise a TimeoutError. That was necessary for Timeout to work correctly if used while handling a CancelledError, but now it can get confused between "internal" and "external" cancellations that happened on the same loop iteration.

I think we could capture task's _must_cancel flag when entering the context manager. If it was set, it means that CancelledError was supposed to be delivered and Timeout shouldn't mess with that attempt.

Draft PR to illustrate the idea: #134472

Additional context

I've hit this issue in production with redis-py, which uses asyncio.timeout(0) internally in the connection parser:

# reduced for brevity
from redis.asyncio import Redis

async def test(timeout):
    redis: Redis = await get_redis()
    task = asyncio.current_task()
    task.cancel()
    await redis.set("foo", "bar")
    assert False, "not cancelled"

CPython versions tested on:

3.12, 3.13, CPython main branch, 3.14, 3.11

Operating systems tested on:

macOS

Linked PRs

Activity

  1. changed the title [-]asyncio.timeout(0) swallows a prior task cancellation[/-] [+]`asyncio.timeout(0)` swallows a prior task cancellation[/+] on May 21, 2025
  2. okhaliavka commented on Sep 22, 2025

    @okhaliavka
    Author

    Hi! Just circling back on this — I’ve tested the behavior on all current CPython versions (3.11–3.14 and main), and the issue still persists.

    The linked draft PR (#134472) illustrates a potential fix, but I’d appreciate any thoughts on whether the current asyncio.timeout(0) behavior is intended or no and whether the fix is sound.

    Totally understand things get busy — if anyone has time to weigh in, I’m happy to iterate on the fix. @ZeroIntensity i'd really appreciate any help in making this issue seen.

    Thanks!

  3. ZeroIntensity commented on Sep 22, 2025

    @ZeroIntensity
    Member

    Our primary asyncio expert (@kumaraditya303) is currently MIA until the end of the month, but I can take a look at the fix at some point. Feel free to remind me in a few days if I haven't looked at it yet.

  4. okhaliavka commented on Dec 24, 2025

    @okhaliavka
    Author

    @ZeroIntensity @kumaraditya303 just wanted to gently remind you guys about this issue.

  5. okhaliavka commented on Sep 2, 2026

    @okhaliavka
    Author
  6. xingdongzhe commented on Sep 2, 2026

    @xingdongzhe
  7. ZeroIntensity commented on Sep 2, 2026

    @ZeroIntensity
    Member

    @xingdongzhe Please don't paste AI output here.


    I'm not one to make a call on the correct behavior here. I'll retag @kumaraditya303 and see what he thinks.

  8. kumaraditya303 commented on Sep 2, 2026

    @kumaraditya303
    Contributor

    I haven't looked closely at this yet but the asyncio.timeout cannot use _must_cancel private attribute as it needs to support duck type compatible task objects.

  9. xingdongzhe commented on Sep 17, 2026

    @xingdongzhe
  10. msullivan commented on Oct 3, 2026

    @msullivan
    Contributor

    I have some possible fix ideas for this:

    1. Add an await sleep(0) to __aenter__. Then it'll take the cancellation immediately without ever checking timeouts. It's kind of a behavioral change, though, since the CancelledError can happen right away without ever running any code in the with block.
    2. Compute must_cancel in __aenter__ (instead of trying to read it) by doing a sleep(0), catching the CancelledError, and recancelling ourselves. Then we can know whether there's an actual cancellation pending when we enter. It does add another trip through the scheduler every time, though.
    3. Try to read _must_cancel, and only use approach 2 if it doesn't exist
  11. msullivan commented on Oct 19, 2026

    @msullivan
    Contributor
    1. Chain a second callback hop for timeout <= 0, so it takes two call_laters resolving before the timeout fires. This will give the body the opportunity to abort on a pre-existing cancel before the timeout cancels it.
      This is a behavior change, though, because
    async with timeout(0):
        await sleep(0)
    

    would not fail, though anything that actually blocks would fail.

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

    stdlibStandard Library Python modules in the Lib/ directorytopic-asynciotype-bugAn unexpected behavior, bug, or error

    Projects

    • Status
      Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions