Skip to content

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

@azibom

Description

@azibom

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions