{"slug": "cancellederror-retry-turned-asyncio-timeout-1-into-6-s", "title": "CancelledError Retry Turned asyncio.timeout(1) Into 6 s", "summary": "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.", "body_md": "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.\n\nThis 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.\n\nThis is the retry wrapper I use for agent tool calls now:\n\n``` python\nimport asyncio\nasync def call_tool(fn, *args, attempts=3):\n    last = None\n    for _ in range(attempts):\n        try:\n            return await fn(*args)\n        except asyncio.CancelledError:\n            raise  # a timeout or a stop button, never a tool failure\n        except Exception as e:\n            last = e\n    return f\"tool failed: {last!r}\"\n```\n\nThe rest of this post shows what the broad version did, and why the error never reaches the code that set the timeout.\n\nIn 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.\n\n`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.\n\nSince 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.\n\nEach 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:\n\n`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.\n\n```\ntimeout(1) wrap_bare: returned 'tool error: CancelledError: ' after 1.00s, side effects=[]\ntimeout(1) wrap_retry: returned 'wrap_retry#2 done' after 6.01s, side effects=['wrap_retry#2']\ntimeout(1) wrap_exc: TimeoutError after 1.00s, side effects=[]\ntimeout(1) wrap_fixed: TimeoutError after 1.00s, side effects=[]\nwait_for(1) wrap_retry: returned 'wrap_retry#2 done' after 6.01s, side effects=['wrap_retry#2']\nwait_for(1) wrap_fixed: TimeoutError after 1.00s, side effects=[]\n```\n\nThe 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.\n\nThe 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.\n\nTimeouts 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:\n\n```\ncancel@0.5 wrap_bare: returned 'tool error: CancelledError: ' after 0.50s, cancelled()=False, cancelling()=1, side effects=[]\ncancel@0.5 wrap_fixed: CancelledError after 0.50s, cancelled()=True, cancelling()=1, side effects=[]\n```\n\nWith 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.\n\nTwo checks came out fine, and they set the scope of the problem:\n\n`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.\nI 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.\n\nSearch for the broad clauses near an `await`:\n\n```\ngrep -rnE \"except( BaseException)?( as [a-z_]+)?:\" --include=*.py .\n```\n\nEvery 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.\n\n`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.", "url": "https://wpnews.pro/news/cancellederror-retry-turned-asyncio-timeout-1-into-6-s", "canonical_source": "https://dev.to/acemeridian/cancellederror-retry-turned-asynciotimeout1-into-6-s-e84", "published_at": "2026-11-25 05:04:38+00:00", "updated_at": "2026-11-25 05:14:51.909126+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools"], "entities": ["CPython", "asyncio", "Python"], "also_reported_by": [], "takeaway": "Catch asyncio.CancelledError and re-raise it before retrying on Exception, otherwise a retry wrapper turns asyncio.timeout(1) into a 6.01-second success with the tool's side effect executed.", "recommendation": {"advice": "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.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/cancellederror-retry-turned-asyncio-timeout-1-into-6-s", "markdown": "https://wpnews.pro/news/cancellederror-retry-turned-asyncio-timeout-1-into-6-s.md", "text": "https://wpnews.pro/news/cancellederror-retry-turned-asyncio-timeout-1-into-6-s.txt", "jsonld": "https://wpnews.pro/news/cancellederror-retry-turned-asyncio-timeout-1-into-6-s.jsonld"}}