`asyncio.timeout(0)` swallows a prior task cancellation
まだ誰も着手していません。
- 主要言語
- 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
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
asyncio.Timeout.aexit とその _on_timeout ハンドラーから始め、続いて PR #134472 のドラフトを確認します。タイムアウトがゼロの場合と正の値の場合の例を再現します。以前のキャンセルが CancelledError として伝播し、実際のタイムアウト処理では引き続き TimeoutError が発生することを回帰テストでカバーできれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- backend
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- 明確に書かれている
- 初心者へのやさしさ
- 30/100