Reviewer · Concurrency
Async cancellation correctness
Async drivers and fan-out helpers must respect cancellation semantics instead of masking or outliving them. Two concrete rules: 1. In any loop that drives a generator/coroutine and needs to catch failures to re-raise them inside the driven code, catch `Exception`, never `BaseException`. Catching `BaseException` swallows `asyncio.CancelledError` (and...
Async drivers and fan-out helpers must respect cancellation semantics instead of masking or outliving them. Two concrete rules:
-
In any loop that drives a generator/coroutine and needs to catch failures to re-raise them inside the driven code, catch
Exception, neverBaseException. CatchingBaseExceptionswallowsasyncio.CancelledError(andKeyboardInterrupt/SystemExit), so a cancelled task gets silently converted into a normal value or a different exception by downstreamexcept Exception/bareexcept:handlers. This breaks timeouts (asyncio.wait_for) and any caller relying on prompt cancellation. -
When fanning out multiple coroutines with
asyncio.ensure_future/asyncio.gather, always cancel and await the spawned tasks in afinallyblock. If thegatheritself is cancelled (e.g., by a timeout), the individual tasks are not automatically awaited to completion — they can keep running after the function returns and mutate shared state (conversation history, agent memory, etc.) that the caller has already moved on from.
runs = [asyncio.ensure_future(run_agent(agent)) for agent in self.agents]
try:
await asyncio.gather(*runs, return_exceptions=True)
for run, agent in zip(runs, self.agents):
self._record(agent, run.result())
finally:
for run in runs:
if not run.done():
run.cancel()
await asyncio.gather(*runs, return_exceptions=True)
self.workspace.save_conversation()
Additionally, when custom dispatch logic decides whether a call is awaited directly or run in a thread (e.g., identity checks like work.func.__func__ is Agent.call_llm), add explicit test coverage for every dispatch branch, including subclass overrides and instance-level attribute overrides. Silent fallback to the wrong branch degrades concurrency behavior without failing any test, so the dispatch contract must be verified directly rather than inferred from end-to-end behavior.