python / python/cpython

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

Open
#150,355 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stdlib topic-asyncio type-feature
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the test_taskgroup_cancel_before_create_task TODO and the TaskGroup cancel/create_task entry points described in the issue. Compare explicit tg.cancel() with failure-driven abort behavior. Done means a task created after explicit cancellation runs through its synchronous code before receiving CancelledError, while failure-driven aborts still raise RuntimeError.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.