Bound a whole agent run with `timeout=` and `RunContext.deadline`
Merged
DO
2mo ago+1488+1488+0123456789012345678901234567890123456789-44-44-01234567890123456789
Adds timeout= (seconds) to run, run_sync, run_stream, run_stream_sync, run_stream_events and iter. It bounds the whole run: model requests, tool calls, hooks, and for the streaming methods the time spent consuming the stream. This follows the design in #9332.
- Expiry reuses first-party cancellation. At run start the timeout becomes an absolute deadline. A timer calls the run's own
RunCancellation.expire(), so teardown is the same asAgentRun.cancel(): streams are closed, tool tasks are drained, and completed work is recorded, including aninterruptedpartial response. RunTimedOut(RunCancelled, TimeoutError)is raised with the same resumableall_messages(),usage,run_idand so on. If the user cancels before expiry, the run still raises plainRunCancelled.RunContext.deadlineis a UTCdatetime, orNone.RunContext.remaining_time()returns the seconds left, orNone.- Runs started inside a run inherit its deadline, through a context variable. A sub-agent's own
timeout=can shorten the deadline but not extend it (min).- When the shared deadline passes, the parent raises
RunTimedOut. - A sub-agent's own shorter timeout follows the existing nested-cancellation semantics (#7199): the delegate tool fails and the parent continues.
- A nested
RunTimedOutthat reaches the outer run's edge outside a tool is re-stamped with the outer state and keeps its type.
- When the shared deadline passes, the parent raises
FallbackModeldoesn't fall back on expiry. Expiry is aCancelledError, not aModelAPIError. There's a test for it.- Behavior is unchanged without
timeout=. The only new per-run work is a no-op clock hook lookup. A run inherits a deadline only from an enclosing run that set one.
Durable execution
The deadline is stored as wall-clock time. Two new private capability hooks supply replay-safe values:
_run_clock()gives the clock that remaining time is measured against._run_start_time()gives a recorded start to counttimeout=from.
Per engine:
- Temporal: the clock is
workflow.now(). Expiry is enforced byloop.call_later, which is a durable workflow timer in a workflow, notexecution_timeout, so history is still recorded.RunTimedOutis anAgentRunError, so an uncaught one fails the workflow as a typed error.deadlineis serialized into activities, defaulted rather than guarded for older workers and custom serializers, so an agent run by a tool inside an activity inherits it.- Tests: replay keeps the deadline (
max_cached_workflows=0, two tool activities plus a sub-agent in each), expiry fires a workflow timer, and the history replays.
- Tests: replay keeps the deadline (
- DBOS: the start time is recorded as a
{name}.run_start_timestep, but only whentimeout=is passed, so existing workflows' step sequences are unchanged.- Test: a recovered workflow keeps the original deadline.
- Prefect: the start time comes from a cached
{name}__run_start_timetask, keyed by flow run plus a per-flow counter, the same pattern as the defaultrun_id.- Test: a flow retry keeps the original deadline.
- Deprecated
TemporalAgent/DBOSAgent/PrefectAgentrejecttimeout=with aUserErrorthat points to the capability, because they have no replay-safe clock. This matches how they treatcancellation_token.
Integration point for #9333 (ModelSettings['request_timeout'])
#9333 can clip its request deadline with min(request_timeout, ctx.remaining_time()), where remaining_time() is None when there's no run deadline. This PR doesn't depend on #9333's code. On Temporal, remaining_time() already reads workflow.now() in workflow code, which suits clipping the activity's schedule_to_close_timeout.
Design choices to confirm (not settled in the issue)
remaining_time()is a method, not a property, because its value changes on every read. gRPC's equivalent istime_remaining().- No sub-agent opt-out of inheritance yet, which is the issue's open question. To detach a background delegate, start it outside the run's context (for example
asyncio.create_task(..., context=contextvars.Context())). A dedicated opt-out can be added later without changing defaults. - DBOS and Prefect native timeouts aren't mapped. With the capabilities, the user owns the workflow or flow, so pydantic-ai never starts one it could set a timeout on. Only the deprecated wrappers start one, and those now reject
timeout=. The docs point toSetWorkflowTimeoutandtimeout_secondsfor bounding the whole workflow or flow. - UI adapters (
run_stream_nativeand friends) don't taketimeout=yet. They also don't forwardretries=orspec=today. UsageLimitslinks to the deadline from the timeouts page's table but isn't otherwise changed, which is the issue's other open question.
- Closes #9332
Checklist
- No breaking changes in accordance with the version policy.
- Any permitted compatibility impact has a label, warning, migration, release note, and exact API-check waiver.
- PR title is fit for the release changelog.
🤖 Generated with Claude Code