Bound a whole agent run with `timeout=` and `RunContext.deadline`

Merged
DO
2mo ago
+1488-44

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 as AgentRun.cancel(): streams are closed, tool tasks are drained, and completed work is recorded, including an interrupted partial response.
  • RunTimedOut(RunCancelled, TimeoutError) is raised with the same resumable all_messages(), usage, run_id and so on. If the user cancels before expiry, the run still raises plain RunCancelled.
  • RunContext.deadline is a UTC datetime, or None. RunContext.remaining_time() returns the seconds left, or None.
  • 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 RunTimedOut that reaches the outer run's edge outside a tool is re-stamped with the outer state and keeps its type.
  • FallbackModel doesn't fall back on expiry. Expiry is a CancelledError, not a ModelAPIError. 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 count timeout= from.

Per engine:

  • Temporal: the clock is workflow.now(). Expiry is enforced by loop.call_later, which is a durable workflow timer in a workflow, not execution_timeout, so history is still recorded. RunTimedOut is an AgentRunError, so an uncaught one fails the workflow as a typed error. deadline is 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.
  • DBOS: the start time is recorded as a {name}.run_start_time step, but only when timeout= 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_time task, keyed by flow run plus a per-flow counter, the same pattern as the default run_id.
    • Test: a flow retry keeps the original deadline.
  • Deprecated TemporalAgent / DBOSAgent / PrefectAgent reject timeout= with a UserError that points to the capability, because they have no replay-safe clock. This matches how they treat cancellation_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)

  1. remaining_time() is a method, not a property, because its value changes on every read. gRPC's equivalent is time_remaining().
  2. 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.
  3. 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 to SetWorkflowTimeout and timeout_seconds for bounding the whole workflow or flow.
  4. UI adapters (run_stream_native and friends) don't take timeout= yet. They also don't forward retries= or spec= today.
  5. UsageLimits links to the deadline from the timeouts page's table but isn't otherwise changed, which is the issue's other open question.

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