python / python/cpython

TaskGroup: tg.cancel() shouldn't block create_task() allow cooperative cancellation

未關閉
#150,355 6 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

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

描述

Currently, when a TaskGroup is explicitly cancelled via tg.cancel(), any subsequent call to tg.create_task() raises:

RuntimeError: TaskGroup <TaskGroup cancelling> is shutting down

This contradicts the TODO in the test test_taskgroup_cancel_before_create_task, which states:

This behavior is not ideal. We'd rather have no exception raised, and the child task run until the first await.

Proposed change:
After an explicit tg.cancel() (not after a failure-induced abort), create_task() should succeed. The new task should run its synchronous code up to the first await, then receive CancelledError

For failure-driven aborts (e.g., an exception in another task), the existing RuntimeError is preserved to prevent unsafe task creation during error cleanup.

A PR implementing this change (with a new _explicitly_cancelled flag) is ready and passes all existing tests.

This resolves the TODO and makes TaskGroup behavior more intuitive when voluntarily cancelled.

Linked PRs
  • gh-150357

貢獻指南

開啟貢獻指南

從這裡開始

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

研究方向

從 test_taskgroup_cancel_before_create_task TODO 以及 issue 中描述的 TaskGroup cancel/create_task 入口開始。比較明確的 tg.cancel() 與由失敗驅動的中止行為。完成標準是:明確取消後建立的工作在接收 CancelledError 之前會執行其同步程式碼,而由失敗驅動的中止仍會引發 RuntimeError。

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

評估

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

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

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