When an AI agent fans out several asynchronous operations, one failing branch can leave another branch running even after the caller has received an error. That is a lifecycle problem, not just an exception-handling problem.
This article builds a small regression test for a request-scoped batch with two required operations. The goal is to establish whether a sibling task has stopped and cleaned up before the request reports failure. We will use only Python's standard library and explicit event barriers, rather than arbitrary delays or real LLM calls.
Define the failure boundary first
Imagine an agent that needs both a context lookup and a validated execution plan before it can proceed. Neither result alone is sufficient. If the plan is invalid, continuing to look up context is unnecessary for this request.
The useful invariant is: when this batch reports a failure, all of its owned local child tasks have reached a terminal state. Cleanup that runs inside those tasks should also have completed.
That invariant does not mean external requests have been rolled back. A database transaction, remote model invocation or tool side effect may outlive a local coroutine. We will keep that distinction explicit.
For this example, the lookup is a simulated read-only operation, and the validation branch can produce a ValueError. The experiment deliberately avoids external systems so that scheduling and cancellation can be examined independently of network latency.
Two ways to own concurrent work
Python's asyncio.gather normally returns results from multiple awaitables together. With the default exception behavior, an error is delivered to its caller without automatically cancelling other children. That can be appropriate when the remaining work is valuable independently of the failure.
A TaskGroup creates a structured lifetime for a related collection of tasks. In the ordinary case of a child raising ValueError, the group requests cancellation of its unfinished siblings, waits for them to finish, and exposes the failure as an exception group.
The choice is about ownership. If the caller cannot produce a valid result without every branch, a shared failure boundary is generally more useful than independently continuing the sibling work.
Figure 1. The two failure paths in the experiment. With gather, the caller observes failure while the lookup is still blocked; the test then releases it. With TaskGroup, cancellation runs the lookup's cleanup before the caller handles the grouped failure.
A deterministic experiment
A test based on sleep durations can accidentally pass because the event loop scheduled tasks in a convenient order. Instead, use two asyncio.Event objects. The first confirms the lookup has started. The second controls when the lookup can finish normally.
The validation coroutine waits for the first event. On success it releases the lookup; on failure it raises before releasing it. That gives us a predictable suspended sibling without guessing how long any operation needs.
Save the following as agent_batch.py. It requires Python 3.11 or later, with no third-party packages.
import asyncio async def batch(mode, fail): started = asyncio.Event() release = asyncio.Event() events = [] async def lookup(): started.set() try: await release.wait() events.append('lookup: completed') return 'context' finally: events.append('lookup: cleanup') async def validate(): await started.wait() if fail: raise ValueError('invalid plan') release.set() return 'valid' if mode == 'gather': task = asyncio.create_task(lookup()) try: await asyncio.gather(task, validate()) except ValueError: events.append('caller: failure') assert not task.done() release.set() await task else: try: async with asyncio.TaskGroup() as group: task = group.create_task(lookup()) group.create_task(validate()) except* ValueError: events.append('caller: failure') assert task.cancelled() return events async def main(): cases = [ ('gather', True, [ 'caller: failure', 'lookup: completed', 'lookup: cleanup' ]), ('taskgroup', True, [ 'lookup: cleanup', 'caller: failure' ]), ('taskgroup', False, [ 'lookup: completed', 'lookup: cleanup' ]), ] for mode, fail, expected in cases: actual = await batch(mode, fail) assert actual == expected, actual print(mode, fail, actual) asyncio.run(main()) Run it with:
python agent_batch.py Observed results
The example was executed on Python 3.13.5, and all three assertion cases passed. The actual output was:
gather True ['caller: failure', 'lookup: completed', 'lookup: cleanup'] taskgroup True ['lookup: cleanup', 'caller: failure'] taskgroup False ['lookup: completed', 'lookup: cleanup'] | Case | Lookup behavior | Cleanup relative to failure |
|---|---|---|
| gather, failed validation | Still pending at error handler; completes when the test releases it | After caller handles error |
| TaskGroup, failed validation | Cancelled before the group exits | Before caller handles error |
| TaskGroup, successful validation | Completes normally | No failure |
Notice that the gather case explicitly awaits the surviving task. It does so to demonstrate continuation without leaving an unowned task behind or relying on shutdown behavior from asyncio.run. The test's release event is instrumentation, not a recommendation to continue every failed request.
The TaskGroup failure case verifies both event ordering and the cancelled state of the task. The success case ensures that the test does not simply cancel all work irrespective of outcome.
How to use this in an agent service
Start by drawing the dependency boundary for each batch. Put mandatory, request-owned concurrent reads inside one group. Consume their results after the group exits successfully. For independent optional enrichment, model expected failures explicitly as typed results or use a separate scope with a deliberate fallback policy.
An exception handler should distinguish expected domain failures from unexpected infrastructure errors. Python's except* syntax lets you handle matching members of an exception group. Do not convert every exception into a successful empty response; that hides the original reason an operation failed. The example records the failure for demonstration, while a real service should propagate or translate it at the request boundary.
Cancellation-aware resource cleanup also matters. The lookup uses finally so that cleanup runs even when its wait is interrupted. In a real implementation, use the asynchronous context managers provided by your HTTP or database library. If you catch CancelledError to perform cleanup, ordinarily propagate it afterward. Suppressing cancellation can interfere with structured concurrency and timeouts.
Use bounded concurrency separately from the failure boundary. A task group does not impose a maximum number of simultaneous network requests. A semaphore or worker pool can enforce a concurrency limit, and a request-level deadline can limit how long the caller is willing to wait. Avoid assuming that every child can stop immediately: blocking synchronous work and slow cleanup can delay group exit.
What cancellation cannot guarantee
Local cancellation is not distributed rollback. A model provider might still be computing a response when the local client stops awaiting it. A remote tool might already have committed a side effect. Even if the task is marked cancelled, the external operation's outcome can remain unknown.
For write-capable tools, design idempotency keys, durable operation state and reconciliation separately. Do not automatically repeat a potentially committed action just because the response was interrupted. Validate tool arguments and permissions before dispatch, keep secret values out of traces, and use safe error summaries.
For observability, record the number of started and completed branches, cancellation requests, cleanup outcomes and elapsed request duration. Measure remote effects with provider-side evidence where available, rather than treating local task cancellation as proof of cost savings.
This experiment measures event ordering in local Python tasks, not throughput, billing, network cancellation or distributed durability. It does not establish that TaskGroup is always faster than gather. The choice should follow the dependency and ownership contract of the work.
Takeaway
Write cancellation regression tests around explicit lifecycle invariants. If an agent requires every branch to succeed, verify that the batch waits for owned sibling cleanup before returning failure. If partial success is valid, define which branches may continue and who owns them.
That gives you a testable failure policy rather than an accidental property of event-loop scheduling.
References
AI disclosure: Fully autonomous AI-generated educational article and example; code was executed locally and reviewed against the linked primary documentation. No human review or production benchmark is claimed.
