CancelledError Retry Turned asyncio.timeout(1) Into 6 s
If your async tool wrapper retries on except BaseException (or a bare except:), it catches the CancelledError that asyncio.timeout(1) uses to stop it, retries, and the call comes back with a normal result after 6.01 s in
If your async tool wrapper retries on except BaseException (or a bare except:), it catches the CancelledError that asyncio.timeout(1) uses to stop it, retries, and the call comes back with a normal result after 6.01 s instead of a TimeoutError at 1.00 s. Catch asyncio.CancelledError first and re-raise it, then retry only on Exception, and the same call fails at 1.00 s with nothing executed.
This story was written with the assistance of an AI writing program. Every number below comes from CPython 3.14.4 on Linux, and the main script ran twice with the same results apart from small timing noise.
This is the retry wrapper I use for agent tool calls now:
import asyncio
async def call_tool(fn, *args, attempts=3):
last = None
for _ in range(attempts):
try:
return await fn(*args)
except asyncio.CancelledError:
raise # a timeout or a stop button, never a tool failure
except Exception as e:
last = e
return f"tool failed: {last!r}"
The rest of this post shows what the broad version did, and why the error never reaches the code that set the timeout.
Why a timeout is just a cancellation
In the last few posts I tested agent tools that keep running after the caller gave up: subprocess.run orphans, ThreadPoolExecutor threads, asyncio.gather siblings. This one is pure asyncio, and the bug is a single word in an except clause.
asyncio.timeout() and asyncio.wait_for() do not have their own way to stop a coroutine. When the deadline passes they call task.cancel(), which throws CancelledError into whatever await the task is blocked on. The timeout context manager then turns that CancelledError into TimeoutError on the way out of the block.
Since Python 3.8, CancelledError subclasses BaseException, not Exception. So except Exception lets it through. except BaseException and a bare except: catch it. Agent code tends to use the broad forms on purpose, because "never let a tool crash the loop" sounds like a good rule.
The test
Each wrapper calls a fake tool that sleeps 5 s and then records a side effect, such as a file write or an API call. The caller wraps the call in asyncio.timeout(1) and expects a TimeoutError at about 1 s. There are four wrappers:
-
wrap_bare: bareexcept:, returns the error as a string to the model, which is what most frameworks do with tool exceptions. -
wrap_retry:except BaseException, retries up to 3 times. -
wrap_exc:except Exception, no retry. -
wrap_fixed: thecall_toolpattern from the top.
What came back
timeout(1) wrap_bare: returned 'tool error: CancelledError: ' after 1.00s, side effects=[]
timeout(1) wrap_retry: returned 'wrap_retry#2 done' after 6.01s, side effects=['wrap_retry#2']
timeout(1) wrap_exc: TimeoutError after 1.00s, side effects=[]
timeout(1) wrap_fixed: TimeoutError after 1.00s, side effects=[]
wait_for(1) wrap_retry: returned 'wrap_retry#2 done' after 6.01s, side effects=['wrap_retry#2']
wait_for(1) wrap_fixed: TimeoutError after 1.00s, side effects=[]
The retry wrapper is the bad one. Attempt 1 is cancelled at 1 s, and the wrapper treats that as a failed call and starts attempt 2. Cancellation is a one-shot event, so nothing stops attempt 2. It runs the full 5 s, performs the side effect, and returns success. The caller set a 1 s budget and got a normal return value at 6.01 s. asyncio.timeout raised nothing because the block exited normally. wait_for behaved the same way.
The bare wrapper is quieter but still wrong. It returned at 1.00 s with no side effect, but as a string, 'tool error: CancelledError: ', which is what the model sees. str(CancelledError()) is empty, so the message has no detail. Given a tool error with no explanation, a model usually tries again.
The stop button is broken too
Timeouts are not the only source of cancellation. When a user presses Stop in an agent UI, the framework usually calls task.cancel() on the running turn. I cancelled each wrapper's task at 0.5 s:
[email protected] wrap_bare: returned 'tool error: CancelledError: ' after 0.50s, cancelled()=False, cancelling()=1, side effects=[]
[email protected] wrap_fixed: CancelledError after 0.50s, cancelled()=True, cancelling()=1, side effects=[]
With the bare wrapper, await task returned a value and task.cancelled() was False. Code that checks cancelled() to decide whether to write "stopped by user" to the transcript would record a finished tool call instead. The leftover cancelling()=1 means the task is still flagged as being cancelled. Python's docs say code that suppresses a cancellation should call uncancel(), and these wrappers never do.
Where it did not break
Two checks came out fine, and they set the scope of the problem:
-
except Exceptionalone was correct in every case. Narrowing the clause is enough; the explicitexcept CancelledError: raisejust makes the intent obvious to the next reader. - Inside a
TaskGroup, a sibling raisingValueErrorat 0.5 s cancelled the bare-excepttool along with the others, and none of them got to their side effect. The bare wrapper swallowed the cancel and returned a string that nobody read, so the group still finished at 0.50 s.
I also checked what happens to later timeouts in the same task after one was swallowed inside an async with asyncio.timeout(0.2) block. In 3.14.4, the next asyncio.timeout(0.2) still raised TimeoutError after 0.20 s, so the damage stays with the call that ate the cancel. I did not test Python 3.10 or older, where asyncio.timeout does not exist.
How I check a codebase for this
Search for the broad clauses near an await:
grep -rnE "except( BaseException)?( as [a-z_]+)?:" --include=*.py .
Every hit inside a coroutine is a candidate. The review question is simple: if this await is cancelled, does the CancelledError leave the function? If the answer is "it gets logged and retried" or "it becomes a tool error string", that is the bug. Libraries that wrap tools for you, including retry decorators, are worth the same check: look at which exception types they retry on by default.
Takeaways
-
asyncio.timeout()andwait_for()stop work by raisingCancelledErrorinside it; any clause that catches it turns the timeout into a no-op. - A retry loop on
BaseExceptionturned a 1 s budget into 6.01 s and still performed the side effect it was meant to prevent. - A bare
except:that returns an error string hides user cancellation:cancelled()wasFalse. - Retry on
Exception, and putexcept asyncio.CancelledError: raisefirst so the next reader does not "simplify" it back.
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.