When one awaitable in asyncio.gather() raises, gather hands you the exception right away but does not cancel the others, so they keep running and finish their side effects after your except block has already run; if one failed tool call should stop the batch, use asyncio.TaskGroup and catch ExceptionGroup. In my test, a search tool failed at 0.5 s, the caller logged the error, and the email, database write and fetch calls all still completed at 3.0 s.
This story was written with the assistance of an AI writing program. Every number comes from CPython 3.14.4 on Linux 7.0, and each script ran twice with identical output.
Here is the version I now use when an agent fans out tool calls in parallel:
import asyncio
async def run_tools(coros):
try:
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(c) for c in coros]
except ExceptionGroup as eg:
return None, [str(e) for e in eg.exceptions] # siblings already cancelled
return [t.result() for t in tasks], []
The rest of this post is what gather actually does on failure, and two traps on the way to the fix.
The setup
This is the third post in a row about agent tool calls that outlive the error. subprocess.run(timeout=1) left orphan processes. ThreadPoolExecutor.result(timeout=1) left threads running. This time there is no timeout at all, just a plain exception inside asyncio.gather, which is the most common way agent code runs tools in parallel.
The test has four fake tools. search sleeps 0.5 s and raises ValueError. email, db_write and fetch each sleep 3 s and then append their name to a list, which stands in for a side effect. I ran them four ways: plain gather, gather(return_exceptions=True), TaskGroup with except*, and TaskGroup with a plain except ValueError.
What the output says
First run, unedited:
gather: caught ValueError at 0.5s, tasks still pending=3
gather: side effects after the error: ['email', 'db_write', 'fetch'] at [3.0, 3.0, 3.0]
return_exceptions=True: returned at 3.0s with ['ValueError', 'email', 'db_write', 'fetch']
TaskGroup: ExceptionGroup at 0.5s, completed=0
TaskGroup: side effects after 3 more s: 0
plain except ValueError: missed, got ExceptionGroup instead
The gather caller got the exception at 0.5 s, on time. Three tasks were still pending, and nothing cancelled them. Two and a half seconds after my error handler ran, all three side effects happened. If that handler had told the user "the batch failed, nothing was sent", it would have been wrong three times over.
Why gather behaves this way
The docs say it in one sentence: with return_exceptions=False, the first exception is propagated to the awaiting task, and "other awaitables in the aws sequence won't be cancelled and will continue to run." gather was designed before structured concurrency was added to asyncio. It only reports errors and does not own the tasks it started.
return_exceptions=True is not the fix either. It just makes you wait: the call returned at 3.0 s with the ValueError sitting in the result list next to three successes. That is the right tool when you want every result, and the wrong one when a failure should stop the work.
The CLI case hides it
I also ran plain gather in a short script that exits right after catching the error. There, the side-effect list stayed empty:
cli gather: side effects after asyncio.run returned: []
asyncio.run() cancels leftover tasks when it shuts down, so in a one-shot script the bug disappears. Run the same code inside a server or a long-lived agent loop, where the event loop keeps going, and the siblings run to completion. So a test that works in a script tells you nothing about the service.
TaskGroup, and the two traps
asyncio.TaskGroup (Python 3.11+) cancels the remaining tasks as soon as one fails, then raises an ExceptionGroup. In the run above it raised at 0.5 s with zero completed calls, and three seconds later the count was still zero.
Trap one: except ValueError no longer matches. The last line of the output shows the plain except missing and an ExceptionGroup escaping instead. Any existing error handling you move from gather to TaskGroup has to change to except* or except ExceptionGroup.
Trap two: you cannot return from an except* block. My first version of the helper did, and Python refused to compile it:
SyntaxError: 'break', 'continue' and 'return' cannot appear in an except* block
That is why the helper at the top catches ExceptionGroup and returns from there. On the happy path it returned ['search', 'email'] with no errors. On the failure path it returned the error at 0.50 s, and no side effects ever ran.
What cancellation does not cover
Cancellation lands at the next await. A tool that is in the middle of a blocking call, or that has already sent its HTTP request, will not take it back. TaskGroup stops the work that has not happened yet. For writes that must not happen twice or half-way, you still need idempotency keys or a single commit step at the end.
Takeaways
-
asyncio.gatherre-raises the first error and leaves the other tasks running. -
return_exceptions=Truecollects errors, but still waits for every task. - Short scripts hide the bug because
asyncio.runcancels leftovers at exit. -
TaskGroupcancels siblings, but raisesExceptionGroup, soexcept ValueErrorstops matching. -
returninsideexcept*is a SyntaxError. CatchExceptionGroupwhen the handler needs to return.
Top comments (0)