Sub topic 13
Handling failures, retries, and timeouts
This chapter assumes you can read basic Python, know Git branches, and have seen the orchestrator-worker pattern from earlier chapters. Subagents fail in ordinary ways: a tool call errors, a model call hangs, or the agent finishes but did not do the work. The orchestrator must expect all three.
Kinds of failure
| Failure | Typical sign | Usual response |
|---|---|---|
| Crash or exception | The worker raises an error | Record it, retry if the cause is temporary |
| Hang | No result after a long time | Cancel at a timeout, then retry or report |
| Wrong result | Status is "ok" but the check fails | Re-run with feedback, or escalate |
| Bad brief | Worker asks for missing context or goes out of scope | Fix the brief, do not just retry |
Only the first two are transient in many cases. A wrong result or a bad brief will fail the same way again, so retrying them unchanged wastes cost.
Isolate failures from each other
In the orchestration example, asyncio.gather is called with return_exceptions=True. Without it, the first exception propagates to the caller, and the other subagents' results are lost to the orchestrator. With it, every task returns either a result or an exception, and the orchestrator marks the failed ones and keeps the rest.
Add a timeout and a bounded retry
A subagent can run for a long time without failing. Wrap each call in asyncio.wait_for so a hang becomes an error you can handle. Retry a small, fixed number of times, with a growing delay between attempts.
import asyncio
import random
async def run_subagent(name: str, attempt: int) -> dict:
# Placeholder for a real agent call. Fails on the first attempt to show a retry.
await asyncio.sleep(0.1)
if attempt == 0:
raise ConnectionError("model API unavailable")
return {"name": name, "status": "ok", "summary": f"finished {name}"}
async def run_with_retry(name: str, retries: int = 2, timeout: float = 5.0) -> dict:
last_error = "unknown"
for attempt in range(retries + 1):
try:
return await asyncio.wait_for(run_subagent(name, attempt), timeout)
except (asyncio.TimeoutError, ConnectionError) as exc:
last_error = repr(exc)
if attempt < retries:
await asyncio.sleep(2 ** attempt + random.random())
return {"name": name, "status": "failed", "summary": last_error}
async def main() -> None:
results = await asyncio.gather(
run_with_retry("update-docs"), run_with_retry("add-tests")
)
for result in results:
print(result)
if __name__ == "__main__":
asyncio.run(main())The loop retries only the errors listed in the except clause. Other exceptions, such as a bug in your own code, propagate instead of being retried silently. The random part of the delay stops many workers from retrying at the same moment.
Decide what a failure means for the whole run
Choose a policy before the run starts:
- Independent tasks: accept partial success and list the failed tasks clearly.
- Dependent tasks: stop the tasks that depend on the failed one, because they would build on missing work.
- Critical tasks: fail the whole run and keep the workspaces for inspection.
When you re-run after a failed check, put the failing command output in the new brief. A retry with the same brief usually gives the same result.
Exercise
A subagent returns status "ok", but pytest tests/test_cli.py fails. Should the orchestrator retry the same brief unchanged? Explain what to do instead.
Show answer
No. This is a wrong result, not a transient error, so an unchanged retry will likely fail the same way. Re-run the subagent with a brief that includes the failing pytest output, in a clean workspace, and limit the number of attempts. If it still fails, mark the task failed and report it.