Make `wrap_*` hooks enclose complete stage lifecycles

Merged
AD
2mo ago
+4610-1919

Every stage of a run (the run itself, each node, model request, tool call, and output) now has one hook lifecycle, with wrap_* outermost:

wrap_* enter → before_* → operation (on_*_error if it fails) → after_* → wrap_* exit

Before this PR, wrap_* sat between before_* and after_*, so a wrapper couldn't see or control what the before_*/after_* hooks did, and gen_ai.input.messages missed changes a wrapper made (#7441).

[!WARNING]
Compatibility impact: Capabilities that depend on the old relative order of wrap_* and before_*/after_*/on_*_error hooks can behave differently, even though every hook signature is unchanged and existing code still imports and type-checks. The changes users can hit are listed below.

Why this can ship in a minor release: the relative order of the hook families was never a documented guarantee beyond "wraps nest as middleware", the old order made wrap_* unable to enclose a stage, and every public signature is unchanged. OpenTelemetry span changes are explicitly permitted by the version policy.

Migration: put policy that must always run (authorization, mandatory redaction) in an outer wrap_* hook rather than in before_*, since a wrapper that returns without calling its handler now skips the inner hooks. Raise an exception other than ModelRetry from before_model_request to abort a run. Add messages to persistent history through ctx.messages, not by appending to request_context.messages.

What changes:

  1. Hook order. wrap_* encloses before_*, the operation with on_*_error recovery, and after_*:
    • A wrapper that returns without calling its handler skips before_* and after_*, including request-time delivery of enqueued messages.
    • on_*_error recovers before the wrapper sees the failure.
    • Exceptions from before_*/after_* reach the wrapper.
    • Calling a non-model handler again repeats the inner hooks.
  2. wrap_model_request may call its handler only once. A second call raises UserError.
  3. Request messages are request-only. Assigning or mutating request_context.messages changes only the current request; ctx.messages is persistent history. Appending to request_context.messages in before_model_request still reaches history but emits a PydanticAIDeprecationWarning.
  4. ModelRetry from before_model_request retries the request with a retry prompt, drawing on the output retry budget. It used to propagate out of the run.
  5. run_stream() counts requests like run(). usage.requests counts a step once, when core commits the response the agent acts on. That response can come from the provider, a recovery, a wrapper's cached response or SkipModelRequest, or the partial of an interrupted stream. A model call that fails without recovery doesn't count; any usage it reported does. This was already run()'s behaviour; run_stream() used to count a call when its lazy stream was opened, before anything was sent. While a step streams, AgentStream.usage already includes it, but AgentRun.usage counts it only once the response is committed. request_limit is checked at the start of each step, before wrap_model_request, so steps a wrapper answers from a cache are bounded too.
  6. Context variables.
    • Values set in after_run no longer reach the caller after agent.run() returns (never documented).
    • on_run_error now sees values set during the run.
    • In run_stream(), values set by before_model_request reach later tool, output and run hooks, but values set later in the model request may not.
  7. Durable execution. before_model_request sees the durable model, so model calls made from it dispatch durably.
  8. Cancellation.
    • on_run_error and then wrap_run both observe a CancelledError.
    • A result on_run_error returns for it is discarded, as before.
    • The run still ends cancelled.
  9. Spans (OpenTelemetry; permitted by the version policy):
    • Span attributes are set after the handler call (#7441).
    • Spans include time spent in before_*/after_* hooks.
    • An after_tool_execute transformation is what the tool span records as the result.
    • A request recovered by on_model_request_error is recorded as a success, and an after_* failure marks the span as an error.
    • Request spans capture the request as prepared.
    • Usage metrics use the provider's billed response even if a hook substitutes another.
    • A skipped provider call has no provider model attributes or metrics.
  10. Harness.
    • SpendLimits now counts every response the provider billed, including one that a capability nested inside it rejects, so SpendCompositionWarning is no longer emitted. It is deprecated, and importing it warns.
    • Compaction capabilities update persistent history and the current request together, so list Memory after compaction (documented; whether core should support request-only injected blocks natively is being decided separately).

New public surface: none. Core keeps a private record of the responses the provider billed during a model request (ModelRequestContext._usage_responses). The Instrumentation capability and the Harness's SpendLimits read it; whether to make it public waits for the per-attempt model-request work in #9348.

Related and follow-ups:

  • #7212 (on_run_error bypassed when before_run raises) is by design under this contract: on_*_error covers only the stage's core operation.
  • on_model_request_error for streams that fail to open, raised in review here, lands in #9348, which primes stream opening for agents that define the hook.
  • The partial response of an interrupted stream counts in usage and history but isn't in the billed-response record SpendLimits reads, as on main: #9601.

Verification: lifecycle, message-persistence, streaming, cancellation, Logfire, durable and Harness suites in CI. New counting tests in tests/test_capability_hooks.py:

  • test_failed_model_request_is_not_counted_as_a_request
  • test_skipped_model_request_is_counted_as_a_request
  • test_request_limit_bounds_responses_a_wrapper_returns_without_the_model

Each runs in both run modes. Cancellation is covered by tests/test_run_cancellation.py::test_run_capabilities_cannot_recover_cancellation, and the deprecated alias by tests/harness/spend/test_spend.py::test_spend_composition_warning_is_a_deprecated_alias.

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