To test Python TaskGroup cancellation in an agent-written patch, force one child to fail after its sibling has started, then assert that the sibling is cancelled and its cleanup finishes before the group exits. Separately cancel the calling task and require CancelledError to reach that caller. A successful return value alone cannot establish either property.

Use TaskGroup when the children belong to one operation and should stop together after a failure. Keep their lifetime inside the group’s context, put cleanup in finally, and coordinate tests with events rather than guessed delays. The runnable example below checks success, sibling failure, and caller cancellation without network services or third-party packages.

Last reviewed: 2026-11-19 (Asia/Shanghai). Official references checked on 2026-11-18 UTC, the same local publication day.

Decide which work must stop together

Consider a handler that needs two asynchronous reads to build one response. If either required read fails, the other result has no consumer. The handler should wait for its owned children to finish cleanup before reporting failure. Write that ownership rule beside the patch before choosing the concurrency helper.

The Python Coroutines and Tasks reference documents a material difference: default gather() propagates the first raised exception while other submitted awaitables continue running. A TaskGroup cancels its remaining children when one fails with an exception other than CancelledError, waits for them, and raises the collected failures as an exception group. Replacing one helper with the other therefore changes error behavior.

SituationDocumented behavior to account forReview assertion
Every child succeedsGroup exit waits for its childrenRead every required result after exit
One child raises ValueErrorRemaining group children are cancelled; failures are groupedSibling finished cleanup; expected failure is visible
Caller cancels the owning operationCancellation must remain observable while children unwindAwaiting the parent raises CancelledError; owned children are done
A child ends with CancelledError aloneThat cancellation does not trigger the group’s ordinary failure ruleExplicitly define whether a missing result invalidates the operation

Independent jobs may legitimately continue after another job fails. Preserve that contract deliberately, including who eventually awaits their results. Do not mechanically convert every gather() call into a task group. Likewise, return_exceptions=True makes exceptions part of gather()’s result list; a caller must inspect those results rather than mistake them for successful application values.

Preserve cancellation through cleanup

Python’s asyncio exceptions reference states that CancelledError subclasses BaseException, and almost always must be re-raised if caught. An ordinary except Exception does not catch it. Inspect explicit except asyncio.CancelledError, bare except, except BaseException, and suppression helpers when an agent changes error handling.

For ordinary resource cleanup, prefer try/finally or the resource’s asynchronous context manager. If cancellation needs a dedicated handler to record a metric, re-raise after that work. Returning a fallback value from the cancellation handler changes the caller’s outcome and can interfere with structured concurrency. Python documents that TaskGroup and asyncio.timeout() use cancellation internally and can misbehave when a coroutine swallows it.

Keep the ownership boundary equally explicit. Create group-owned children with group.create_task(). A separate asyncio.create_task() elsewhere in a worker is not automatically registered with this group. Review nested helpers for such detached work, and give any deliberately longer-lived task a separate owner and shutdown policy.

Cancellation also does not establish that an external side effect was reversed. If a child submitted a write before cancellation, the application still needs to determine that write’s outcome. The tests here establish task lifetime and exception behavior; they make no rollback claim.

Reproduce the lifecycle with events

Save the following as test_taskgroup_lifecycle.py. It uses APIs available in Python 3.11 and newer. Run it with the repository’s actual supported interpreter; the local verification for this article used CPython 3.12.3.

The Synchronization Primitives reference documents Event.wait() and Event.set(): a waiter blocks until the flag is set, and setting it wakes waiters. These events coordinate tasks on one event loop. They are not thread synchronization primitives.

Here, started proves the worker reached its wait, release allows success, and closed marks the worker’s finally path. The failing peer waits for started before raising, so the test cannot pass merely because cancellation prevented the worker from starting.

import asyncio
import unittest


async def run_pair(started, release, closed, owned, *, fail=False):
    async def worker():
        try:
            started.set()
            await release.wait()
            return "ok"
        finally:
            closed.set()

    async def peer():
        await started.wait()
        if fail:
            raise ValueError("injected failure")
        return "peer"

    async with asyncio.TaskGroup() as group:
        owned["worker"] = group.create_task(worker())
        owned["peer"] = group.create_task(peer())
    return owned["worker"].result(), owned["peer"].result()


class LifecycleTests(unittest.IsolatedAsyncioTestCase):
    def state(self):
        return asyncio.Event(), asyncio.Event(), asyncio.Event(), {}

    def assert_closed(self, closed, owned):
        self.assertEqual(set(owned), {"worker", "peer"})
        self.assertTrue(closed.is_set())
        self.assertTrue(all(task.done() for task in owned.values()))

    async def settle(self, parent):
        if not parent.done():
            parent.cancel()
        await asyncio.gather(parent, return_exceptions=True)

    async def test_success(self):
        started, release, closed, owned = self.state()
        async with asyncio.timeout(2) as watchdog:
            parent = asyncio.create_task(run_pair(started, release, closed, owned))
            try:
                await started.wait()
                self.assertFalse(closed.is_set())
                release.set()
                self.assertEqual(await parent, ("ok", "peer"))
                self.assert_closed(closed, owned)
            finally:
                await self.settle(parent)
        self.assertFalse(watchdog.expired())

    async def test_peer_failure(self):
        started, release, closed, owned = self.state()
        async with asyncio.timeout(2) as watchdog:
            with self.assertRaises(ExceptionGroup) as caught:
                await run_pair(started, release, closed, owned, fail=True)
            self.assertEqual(
                [type(error) for error in caught.exception.exceptions],
                [ValueError],
            )
            self.assertTrue(owned["worker"].cancelled())
            self.assert_closed(closed, owned)
        self.assertFalse(watchdog.expired())

    async def test_caller_cancellation(self):
        started, release, closed, owned = self.state()
        async with asyncio.timeout(2) as watchdog:
            parent = asyncio.create_task(run_pair(started, release, closed, owned))
            try:
                await started.wait()
                self.assertFalse(closed.is_set())
                parent.cancel()
                with self.assertRaises(asyncio.CancelledError):
                    await parent
                self.assertTrue(parent.cancelled())
                self.assertTrue(owned["worker"].cancelled())
                self.assert_closed(closed, owned)
            finally:
                await self.settle(parent)
        self.assertFalse(watchdog.expired())


if __name__ == "__main__":
    unittest.main(verbosity=2)

Run the focused check:

python3 -m unittest -v test_taskgroup_lifecycle

The expected result is three passing tests and OK. That result was observed for this exact example on CPython 3.12.3. It is evidence about the demonstration, not a test of your application’s clients, resources, or deployment.

The two-second asyncio.timeout() is a cooperative test watchdog, not an exact latency assertion or a hard process limit. The task reference explains that the context cancels the current task and translates its cancellation into TimeoutError outside the context. The final expired() assertion also rejects a run where an expected-cancellation assertion consumes the watchdog’s cancellation. Cancellation-resistant code can delay termination. Keep a separate CI process timeout for a broken test that stops yielding or refuses cancellation.

Make each assertion fail for the right defect

The success case checks both result values and completed children. The failure case checks the exact singleton ValueError group, confirms that the worker ended through cancellation, and checks its cleanup marker before returning. The caller case checks that cancellation reaches the parent rather than becoming an apparently successful fallback.

closed.set() is only a stand-in for cleanup. When adapting this fixture, place the marker after the actual close operation succeeds, or assert a fake resource’s close result and call count. A marker placed before an awaited close can pass while cleanup remains incomplete. Keep assertions inside the test’s operation boundary; later teardown should not supply the cleanup that the operation was meant to finish itself.

The helper settle() consumes the parent during test cleanup. Its return_exceptions=True is confined to that harness role; it does not replace the outcome assertions above it. In production code, preserve the failure or cancellation that the caller’s contract requires.

For a useful negative control, change only the fixture worker to catch CancelledError and return "ignored", keeping its finally block. The failure and caller-cancellation tests should then fail their worker.cancelled() assertions even though closed is set. Restore the worker afterward. This demonstrates why a cleanup marker alone cannot detect swallowed cancellation.

This fixture has one direct injected failure. Real nested task groups can produce nested exception groups and multiple failures. Match the intended exception types at the application boundary, and preserve unexpected failures; do not depend on one fixed error ordering or catch every group merely to return success.

Extend the check at the changed boundary

After the three basic cases pass, add the scenario the patch actually changes. If it alters timeout handling, expire the enclosing timeout and assert the caller-visible timeout after cleanup. If it changes resource release, inject a close failure and verify that the failure remains visible. If it cancels individual children, specify how callers handle a cancelled child’s missing result.

Test overlapping caller cancellation and child failure when that race matters to the component. Python’s task reference records improvements to simultaneous internal and external cancellation handling in Python 3.13. Record the exact interpreter patch version and run on the minimum supported version as well as the deployed one; the demonstration’s three passing cases do not establish that more complex race behavior across releases.

Use the site’s race-condition testing guide when the changed code also shares mutable state. The event handshakes here force particular lifecycle checkpoints; they do not explore every possible interleaving.

Hand the agent an ownership defect to repair

Give the coding agent the failing lifecycle case, exact interpreter version, expected caller outcome, and the child handles whose state is wrong. Require it to repair task ownership, exception propagation, or resource cleanup while preserving the assertions. Raising the watchdog or removing cancelled() checks does not satisfy that task.

Run the adapted test against the base revision and the proposed revision with identical settings. After repair, rerun the original failing case and the containing component suite. Attach commands, exit results, exception classes, and cleanup assertions to the review; include application payloads only when they are necessary and sanitized.

For broader memory or handle retention, continue with the resource-leak testing guide . Start this review by adapting one real fan-out operation to the three lifecycle cases, then inspect every task-creation site that can escape its owner.

Sources checked

These are stable official technical references, checked for the documented behavior used here rather than treated as a release announcement. The example uses the common Python 3.11+ APIs; version-specific cancellation behavior still needs the runtime checks described above.