python / python/cpython

`asyncio.timeout(0)` swallows a prior task cancellation

未關閉
#134,471 8 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

stdlib topic-asyncio type-bug
主要語言
Python
星號
77.2k
分支
35.9k
PR 合併指標
PR 指標待擷取

描述

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: https://github.com/python/cpython/pull/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
  • gh-134472

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

先從 asyncio.Timeout.aexit 及其 _on_timeout 處理常式開始,然後檢視 PR #134472 的草稿。重現零逾時和正逾時的範例;完成標準是:先前的取消會以 CancelledError 傳播,而真正的逾時處理仍會引發 TimeoutError,並包含回歸測試涵蓋。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
python
領域
backend
Issue 類型
缺陷
難度
4/5
預估耗時
3-5 天
活躍度
停滯
描述清晰度
描述清楚
新手友好度
30/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。