TaskGroup: tg.cancel() shouldn't block create_task() allow cooperative cancellation
Nobody has claimed this yet.
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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