cd /news/ai-agents/cancellederror-retry-turned-asyncio-… · home › topics › ai-agents › article
[ARTICLE · art-175878] src=dev.to ↗ pub= topic=ai-agents verified=true sentiment=· neutral

CancelledError Retry Turned asyncio.timeout(1) Into 6 s

A developer demonstrated that an async tool-call retry wrapper catching BaseException (or using a bare except) swallows the CancelledError that asyncio.timeout(1) uses to abort a call, causing a 5-second tool to complete and return normally at 6.01 seconds instead of raising TimeoutError at 1.00 second. Testing on CPython 3.14.4, the developer found that re-raising asyncio.CancelledError before retrying on Exception restores the expected 1.00-second TimeoutError with no side effects, and that asyncio.wait_for behaves the same way.

recommendation

In agent tool-call retry wrappers, re-raise asyncio.CancelledError first and retry only on Exception so timeouts and Stop cancels propagate instead of being retried.

more in playbook: Designing agent systems
by read5 min views1 publishedNov 25, 2026

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.

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.

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: bare except:, 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: the call_tool pattern from the top.

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.

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:

cancel@0.5 wrap_bare: returned 'tool error: CancelledError: ' after 0.50s, cancelled()=False, cancelling()=1, side effects=[]
cancel@0.5 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.

Two checks came out fine, and they set the scope of the problem:

except CancelledError: raise just makes the intent obvious to the next reader.TaskGroup, a sibling raising ValueError at 0.5 s cancelled the bare-except tool 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.

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.

asyncio.timeout() and wait_for() stop work by raising CancelledError inside it; any clause that catches it turns the timeout into a no-op.BaseException turned a 1 s budget into 6.01 s and still performed the side effect it was meant to prevent.cancelled() was False. Exception, and put except asyncio.CancelledError: raise first so the next reader does not "simplify" it back.

── more in #ai-agents 4 stories · sorted by recency
── more on @cpython 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/cancellederror-retry…] indexed:0 read:5min 2026-11-25 · —