DEV Community

Cover image for Python 3.15's TaskGroup.cancel(): First Valid Answer Wins, the Rest Stop
Gabriel Anhaia
Gabriel Anhaia

Posted on Edited on AI-assisted

Python 3.15's TaskGroup.cancel(): First Valid Answer Wins, the Rest Stop


Your checkout asks three carriers for a shipping price and needs one usable answer. The first reply is good. Two requests are still open, holding connections for a result nobody will read.

Up to Python 3.14, the documented way to end a task group at that point was to raise an exception on purpose and swallow it. Python 3.15, released on October 9, 2026, gives asyncio.TaskGroup a method for it. The docs call cancel() "a non-exceptional, early exit of the task group's lifetime": it cancels every unfinished task plus the group's body, and the async with block exits without raising CancelledError.

The happy path is one line. The paths around it need a small helper.

One port, several carriers

Put the port and its data in quotes.py:

from dataclasses import dataclass
from typing import Protocol

@dataclass(frozen=True)
class Parcel:
    grams: int
    country: str

@dataclass(frozen=True)
class Quote:
    carrier: str
    cents: int
    currency: str

class ShippingQuotes(Protocol):
    name: str

    async def quote(self, parcel: Parcel) -> Quote: ...
Enter fullscreen mode Exit fullscreen mode

The obvious race goes in naive.py:

import asyncio
from collections.abc import Sequence

from quotes import Parcel, Quote, ShippingQuotes

async def first_answer(
    carriers: Sequence[ShippingQuotes], parcel: Parcel
) -> Quote:
    answers: list[Quote] = []

    async def ask(carrier: ShippingQuotes) -> None:
        answers.append(await carrier.quote(parcel))
        tg.cancel()

    async with asyncio.TaskGroup() as tg:
        for carrier in carriers:
            tg.create_task(ask(carrier))
    return answers[0]
Enter fullscreen mode Exit fullscreen mode

Two bugs show up right away. A carrier that answers with a price of zero wins the race. Worse, a carrier that raises before the winner answers ends the race for everyone. cancel() doesn't change the older rule: the first task that fails with anything other than CancelledError cancels its siblings, and the exception comes out in an ExceptionGroup.

Three couriers run toward one counter, and one of them trips over a rope tied to the other two
In a plain task group, one early failure pulls every other task down with it.

Turn failures into values first

The fix is to stop exceptions at the edge of each attempt. Record the failure, let the task finish normally, and the group keeps running. This is first_valid.py, application-layer code that knows nothing about carriers:

import asyncio
from collections.abc import Awaitable, Callable, Mapping

class NoValidAnswer(Exception):
    def __init__(self, failures: dict[str, str]) -> None:
        super().__init__(f"no valid answer: {failures}")
        self.failures = failures

async def first_valid[T](
    sources: Mapping[str, Callable[[], Awaitable[T]]],
    is_valid: Callable[[T], bool],
) -> T:
    winners: list[T] = []
    failures: dict[str, str] = {}

    async def attempt(
        name: str, ask: Callable[[], Awaitable[T]]
    ) -> None:
        try:
            answer = await ask()
        except Exception as exc:
            failures[name] = repr(exc)
            return
        if not is_valid(answer):
            failures[name] = f"invalid: {answer!r}"
        elif not winners:
            winners.append(answer)
            tg.cancel()

    async with asyncio.TaskGroup() as tg:
        for name, ask in sources.items():
            if winners:
                break
            tg.create_task(attempt(name, ask), name=name)

    if not winners:
        raise NoValidAnswer(failures)
    return winners[0]
Enter fullscreen mode Exit fullscreen mode

except Exception is safe around the await because CancelledError has been a subclass of BaseException since Python 3.8, so cancellation passes straight through. Catching BaseException here, or using a bare except:, would swallow it.

is_valid sits outside the try on purpose. A carrier being down is expected. A bug in your own rule should be loud, so it fails the group.

The use case in quote_parcel.py supplies the business rule and the deadline:

import asyncio
from collections.abc import Sequence
from functools import partial

from first_valid import first_valid
from quotes import Parcel, Quote, ShippingQuotes

def is_usable(quote: Quote) -> bool:
    return quote.cents > 0 and quote.currency == "EUR"

class QuoteParcel:
    def __init__(
        self,
        carriers: Sequence[ShippingQuotes],
        deadline: float = 2.0,
    ) -> None:
        self._carriers = carriers
        self._deadline = deadline

    async def __call__(self, parcel: Parcel) -> Quote:
        asks = {
            c.name: partial(c.quote, parcel)
            for c in self._carriers
        }
        async with asyncio.timeout(self._deadline):
            return await first_valid(asks, is_usable)
Enter fullscreen mode Exit fullscreen mode

The result is the first usable price, which may not be the cheapest. If your rule is "cheapest wins", wait for everyone and don't race.

Prove the losers stopped

A correct return value doesn't tell you whether the slow carrier was cancelled. Make the fake keep a log. This one measures time in event-loop turns, so the order is fixed and no test sleeps. ticks=None means "never answers". Both blocks go in test_first_valid.py, in this order:

import asyncio
from dataclasses import dataclass, field

import pytest

from first_valid import NoValidAnswer
from naive import first_answer
from quote_parcel import QuoteParcel
from quotes import Parcel, Quote

PARCEL = Parcel(grams=1200, country="DE")
OK = Quote("fast", 890, "EUR")
FREE = Quote("odd", 0, "EUR")
STOPPED = ["started", "cancelled", "cleaned up"]

@dataclass
class FakeCarrier:
    name: str
    reply: Quote | Exception
    ticks: int | None = 0
    log: list[str] = field(default_factory=list)

    async def quote(self, parcel: Parcel) -> Quote:
        self.log.append("started")
        try:
            if self.ticks is None:
                await asyncio.Event().wait()
            for _ in range(self.ticks or 0):
                await asyncio.sleep(0)
            if isinstance(self.reply, Exception):
                raise self.reply
            return self.reply
        except asyncio.CancelledError:
            self.log.append("cancelled")
            raise
        finally:
            self.log.append("cleaned up")

def race(*carriers: FakeCarrier) -> Quote:
    return asyncio.run(QuoteParcel(carriers, 1.0)(PARCEL))

def down(name: str = "broken") -> FakeCarrier:
    return FakeCarrier(name, ConnectionError("down"))
Enter fullscreen mode Exit fullscreen mode

Of the six tests, the first two check the loser's log and the last one runs the naive race:

def test_loser_is_cancelled_and_cleans_up():
    slow = FakeCarrier("slow", OK, ticks=None)
    assert race(FakeCarrier("fast", OK, ticks=1), slow) == OK
    assert slow.log == STOPPED

def test_tie_has_one_winner():
    other = FakeCarrier("other", OK, ticks=1)
    assert race(FakeCarrier("fast", OK, ticks=1), other) == OK
    assert other.log == STOPPED

def test_early_failure_does_not_end_the_race():
    fast = FakeCarrier("fast", OK, ticks=3)
    assert race(down(), fast) == OK

def test_invalid_answer_does_not_win():
    fast = FakeCarrier("fast", OK, ticks=3)
    assert race(FakeCarrier("odd", FREE), fast) == OK

def test_no_winner_reports_every_failure():
    with pytest.raises(NoValidAnswer) as err:
        race(down(), FakeCarrier("odd", FREE))
    assert set(err.value.failures) == {"broken", "odd"}

def test_naive_race_dies_with_the_first_failure():
    fast = FakeCarrier("fast", OK, ticks=3)
    with pytest.raises(ExceptionGroup):
        asyncio.run(first_answer([down(), fast], PARCEL))
    assert fast.log == STOPPED
Enter fullscreen mode Exit fullscreen mode

With the five files in one folder, uv and pytest are the only tools you need:

uv run --no-project --python 3.15 --with pytest pytest -q
Enter fullscreen mode Exit fullscreen mode

The last test pins the naive behaviour so nobody "simplifies" the helper back into it. The tie test covers the same case as one in CPython's own test suite, test_taskgroup_cancel_one_winner.

Five traps around cancel()

The winner cancels itself. cancel() hits every task that isn't done, and the task calling it isn't done. If the coroutine then returns a value, asyncio marks the task cancelled and drops the value: the task source has a branch commented "Task is cancelled right before coro stops". Calling task.result() on the winner raises CancelledError. Store the answer before you cancel, and don't await anything afterwards in that task.

An eager winner closes the group early. Under asyncio.eager_task_factory, an adapter with a cached quote can finish inside create_task(). The group is then shutting down, and the next create_task() raises RuntimeError. That is what if winners: break is for. CPython's test for creating a task after cancel() carries a TODO saying the behaviour "is not ideal".

The exit waits for the slowest cleanup. async with returns only when every task has finished, including its finally block. A loser that takes three seconds to close a connection delays a winner that answered in 50 milliseconds. With the two-second deadline above, it turns a won race into a TimeoutError, because cancellation from outside still counts after cancel(). (A bug that swallowed it was fixed on the 3.15 branch in September, before the final release.) Keep cleanup short, or give it a timeout inside the adapter.

A loser can still raise. If a child throws from its finally after cancel(), a plain group raises ExceptionGroup (CPython tests for it in test_taskgroup_cancel_before_exception) and you lose a perfectly good answer. In first_valid() the except Exception in attempt catches that too.

Threads and remote servers don't stop. If an adapter wraps a blocking client in asyncio.to_thread(), cancelling the task ends your wait and the thread keeps running. An executor call that is already being executed can't be cancelled. The carrier's server may also finish a request you walked away from. Race reads such as price quotes. Never race a call that buys a label.

A courier rests at a finish line while a heavy door behind waits for a second courier who is slowly packing boxes
The race has a winner, and the block still waits for the last loser to clean up.

The same helper on 3.11 to 3.14

The 3.14 docs say termination is "not natively supported by the standard library" and give a recipe: add a task that raises a private exception, then ignore it with except*. This is the "unintuitive boilerplate" that What's New in 3.15 says the method replaces. In first_valid() the winning task can raise it directly. Add the class to first_valid.py:

class _Won(Exception):
    """Ends the group once an answer is stored."""
Enter fullscreen mode Exit fullscreen mode

Then replace tg.cancel() with raise _Won, and wrap the group:

    try:
        async with asyncio.TaskGroup() as tg:
            for name, ask in sources.items():
                if winners:
                    break
                tg.create_task(attempt(name, ask), name=name)
    except* _Won:
        pass
Enter fullscreen mode Exit fullscreen mode

Callers keep the same code, because the mechanism lives in one function. Two behaviours differ.

The first is the deadline from the third trap. On 3.14, if it expires while a loser is still cleaning up, the group raises its ExceptionGroup instead of the cancellation. except* swallows that group, so asyncio.timeout() sees no exception to convert. You get the answer late, with no TimeoutError.

The second is the tie. tg.cancel() cancels the siblings on the spot, while a raised exception reaches the group through a done callback, on a later turn of the event loop. In the tie test, the other carrier gets to finish in that gap: the elif not winners check still rejects its answer, but its log has no "cancelled" entry. On 3.14 and earlier, drop the last assert from test_tie_has_one_winner.

The [T] syntax needs Python 3.12, so on 3.11 declare a TypeVar instead.

One thing to avoid on any version is swapping the group for asyncio.wait(..., return_when=FIRST_COMPLETED) and returning. "Completed" includes failed, and wait() hands back the pending set without cancelling it. Those tasks keep running unless you cancel and await them yourself.


If this was useful

The race could change from an exception trick to cancel() without touching a carrier because the adapters sit behind a port and the policy sits in the application layer. That separation is what Hexagonal Architecture in Python is about: my book builds an async FastAPI and SQLAlchemy 2 service with ports and adapters, then builds the same feature five ways (Hexagonal, Clean, Onion, layered and vertical slice) and measures the results. Every listing that names a repo path is quoted from the free companion repo. The repo targets Python 3.14, so use the except* version if you try this helper there.

Hexagonal Architecture in Python by Gabriel Anhaia

Top comments (0)