Keep the response that crosses a token or cost limit in `capture_run_messages`

Merged
DO
1mo ago
+262-33

Posted by Claude Code on Douwe's behalf.

Closes #11397

Why we make these changes

Token and cost limits are checked after a response has been billed, but UsageLimitExceeded was raised before that response was committed to history. So capture_run_messages lacked it, and a run resumed from the captured messages with no new prompt requested (and paid for) it again. The response is now committed first, marked state='interrupted' since the run stops before acting on it, then the limits are enforced. Reported by a user.

New public surface

None.

User-visible behavior

 pydantic_ai/agent/__init__.py :: Agent.run(usage_limits=UsageLimits(cost_limit=...))
  └─ … unchanged machinery …
     └─ pydantic_ai/_agent_graph.py :: ModelRequestNode._make_request() / ModelRequestNode.stream()
-       ├─ ModelRequestNode._enforce_usage_limits()  → UsageLimitExceeded, response dropped
        └─ ModelRequestNode._finish_handling()
+          ├─ ModelRequestNode._append_response()  → response in history, counted in usage.requests
+          └─ ModelRequestNode._enforce_usage_limits()  → UsageLimitExceeded, history copy marked state='interrupted'

Unchanged on purpose: a response a hook rejects with ModelRetry while crossing a limit isn't kept (keeping it last would make a resume act on rejected output); limits crossed during Anthropic pause_turn / OpenAI background continuations or by FallbackModel-rejected responses still raise with no response in history; a streamed response a token limit cuts short is still kept as state='interrupted'. The "Recovering a failed run's messages" section #11406 added, and its skill counterpart, now describe the new behavior.

Verification

  • test_response_over_limit_is_kept_in_captured_messages (input-token limit, cost limit, streamed cost limit × no-prompt resume, new prompt) fails on main and passes here: captured messages snapshot with state='interrupted', usage.requests == 1, the model's own response object left complete, a no-prompt resume runs the tool call, and a new prompt closes it out; each continuation makes one model request, not two.
  • test_recovered_response_rejected_with_model_retry_counts_its_usage covers the ModelRetry branch that still records a recovered response's usage when it commits it.
  • Local runs of every test module touching usage limits or capture_run_messages pass (apart from Bedrock-credential and Prefect/DBOS failures that also fail on main locally).

What changes for existing users

Runs stopped by a token or cost limit now keep the over-limit response in their messages as state='interrupted' (so UIs and persistence layers that show interrupted as partial will show it that way) and count its step in usage.requests; continuing from those messages, with or without a new prompt, no longer pays for it again; other runs are unchanged.

Open decisions

None. Settled by Douwe:

  • Merge #11406 first; this PR then merges origin/main and rewrites #11406's "billed but not captured" sentences in the docs/agent.md recovery section and the skill's references/TESTING-AND-DEBUGGING.md (decision). Done: #11406 merged and both are rewritten.
  • The over-limit response is marked state='interrupted' (decision).
  • Its step keeps counting in usage.requests, and the uncovered paths (ModelRetry rejection, pause_turn/background continuations, FallbackModel-rejected responses) are tracked in #11425 (decision).
PR decisions

2026-10-26 · Over-limit response is committed as an ordinary complete response · iter -

  • Decision: Append the billed response with state='complete' before enforcing token/cost limits; no 'interrupted' marker
  • Why: It arrived in full; resuming with no prompt then acts on it (runs its tool calls / returns its output) instead of re-requesting, while an interrupted marker would trigger history repair and re-request
  • Source: https://github.com/pydantic/pydantic-ai/issues/11397

2026-10-26 · new_messages() semantics for the over-limit response · iter -

  • Decision: It belongs to the failed run (its run_id), so AgentRun.new_messages()/capture_run_messages include it, and a resumed run's new_messages() does not
  • Why: Same as every other message the failed run produced; no special casing needed
  • Source: https://github.com/pydantic/pydantic-ai/issues/11397

2026-10-26 · ModelRetry paths keep enforcing limits before appending · iter -

  • Decision: Leave the ModelRetry branches (hook rejected the response) unchanged
  • Why: Committing a hook-rejected response last in history would make a no-prompt resume act on output the hook rejected; out of the issue's reproduced scope
  • Source: https://github.com/pydantic/pydantic-ai/issues/11397

2026-10-26 · Recovery docs section left to #11376 · iter -

  • Decision: Only add sentences to docs/agent.md (capture section) and docs/production.md (cost section); don't write the #11376 'Recovering a failed run's messages' section
  • Why: #11376 is an open, separate docs issue; the section it would update doesn't exist yet
  • Source: https://github.com/pydantic/pydantic-ai/issues/11376

2026-10-26 · pre-push review 1 of 3 at 311849f9679ddb11478c9bd3fc8266801907cf12 · iter -

2026-10-26 · pre-push review 1 of 3 at 311849f9679ddb11478c9bd3fc8266801907cf12 · iter -

2026-10-26 · pre-push review 2 of 3 at 311849f9679ddb11478c9bd3fc8266801907cf12 · iter -

2026-10-26 · pre-push review 2 of 3 at 311849f9679ddb11478c9bd3fc8266801907cf12 · iter -

2026-10-26 · Over-limit step now counts in usage.requests · iter -

  • Decision: Keep: committing the response via _append_response counts its step (requests=1 where main left 0 on the handler-recorded path)
  • Why: requests counts committed responses; the resumed run makes no request for it, so not counting here would leave it uncounted forever; matches the record_usage=True path and interrupted-stream commits
  • Source: https://github.com/pydantic/pydantic-ai/issues/11397

2026-10-26 · pre-push review 3 of 3 at 423390061950f705e6bab8f319086823e416f292 · iter -

2026-10-26 · pre-push review 3 of 3 at 423390061950f705e6bab8f319086823e416f292 · iter -

2026-10-26 · Over-limit docs live in Usage Limits · iter -

2026-10-26 · exempt delta: coverage test at 6dacb847836cbcd1ac6c2ad243f4ba4003ae910a · iter -

  • Decision: Pushed without review: test-only delta (tests/test_capability_hooks.py) closing CI coverage gap at _agent_graph.py 2443-2444 (_append_response record_usage=True branch, now reached only from ModelRetry branches)
  • Why: Exempt 'missing coverage' row; chains from reviewed remediation commit d427fb0d (review 3 of 3, budget exhausted); expectation established by _make_request's 'preserve the response in history for context' and _append_response's usage recording
  • Source: https://github.com/pydantic/pydantic-ai/pull/11413

2026-10-26 · Escalated: complete vs interrupted marker · iter -

  • Decision: Posted options (a) complete / (b) interrupted / (c) special-case new prompt to Douwe, recommending (b); no code change until he decides
  • Why: douwebot showed new-prompt continuation regresses with complete+tool calls (reproduced); verified an interrupted complete response is acted on without re-request on no-prompt resume and closed out on new prompt, so the earlier rationale for complete was wrong
  • Source: https://github.com/pydantic/pydantic-ai/pull/11413#issuecomment-6426746624
  • Supersedes: Over-limit response is committed as an ordinary complete response

2026-10-26 · Douwe: keep counting over-limit step in usage.requests · iter -

2026-10-26 · Douwe: uncovered paths tracked in #11425 · iter -

2026-10-26 · pre-push review 1 of 3 (task: implement option b) at 1d3e415abc518e2aa4a5bd5b92b2597784f2fff7 · iter -

2026-10-26 · pre-push review 1 of 3 (task: implement option b) at 1d3e415abc518e2aa4a5bd5b92b2597784f2fff7 · iter -

2026-10-26 · pre-push review 2 of 3 (task: implement option b) at 8764a833ca8ffb20b1a6961180ade909d4d51d31 · iter -

2026-10-26 · pre-push review 2 of 3 (task: implement option b) at 8764a833ca8ffb20b1a6961180ade909d4d51d31 · iter -

2026-10-26 · exempt delta: docstring-only at 96d32fbda667d9ede12d29a84168a4646581313a · iter -

2026-10-26 · Douwe: over-limit response marked interrupted · iter -

2026-10-26 · exempt delta: docstring-only at e6eab83d840f06a436a371e77261ff086da8312d · iter -

2026-10-26 · Douwe: merge #11406 first · iter -

2026-10-26 · pre-push review 3 of 3 (task: implement option b) at 571ac42ff1af9cb428fc105c80e99e360b52d5cb · iter -

2026-10-26 · pre-push review 3 of 3 (task: implement option b) at 571ac42ff1af9cb428fc105c80e99e360b52d5cb · iter -

2026-10-26 · douwebot finding: requests definition at 5475dce9171c1c33c9ba8afa11894daf0ed7c321 · iter -

  • Decision: Unified the RunUsage.requests definition (usage.py field + request_limit docstrings, _append_response docstring, docs/agent.md, docs/retries.md) as responses committed to the run's history, incl. the one a token/cost limit stops the run on; pushed without local review (budget 3/3 exhausted), douwebot re-run is the review
  • Why: Follows Douwe's decision to count the step; definitions previously said 'acts on'
  • Source: https://github.com/pydantic/pydantic-ai/pull/11413#discussion_r4383287333

2026-10-26 · requests redefinition verified narrow · iter -

  • Decision: Keep 5475dce: docs/docstrings only, no code change; for runs that don't hit a token/cost limit 'committed to history' and the old 'acted on' count the same responses (interrupted-stream commits and ModelRetry context commits were already counted before this PR); the only new count is Douwe's settled over-limit step
  • Why: Lead asked to verify the public-field definition change is narrow and backward compatible
  • Source: https://github.com/pydantic/pydantic-ai/pull/11413#discussion_r4383287333

2026-10-26 · exempt delta: test snapshot at 071725d8b227fc2ea45fcde3b4b2975898f6b08a · iter -

  • Decision: douwebot finding: test asserts full all_messages() snapshot instead of class names; pushed without local review
  • Why: Test-only fixture/snapshot correction to established behavior (response kept for context before RetryFeedbackPart, per _make_request comment); chains from reviewed 8764a83 via exempt/doc-only deltas and 5475dce (budget-exhausted push reviewed by douwebot)
  • Source: https://github.com/pydantic/pydantic-ai/pull/11413

2026-10-26 · Declined optional: single usage-record/enforce sequence · iter -

  • Decision: Keep _append_response's record_usage branch for the ModelRetry callers instead of moving record+enforce into each caller
  • Why: The refactor would duplicate the record step into both ModelRetry branches and touch paths this PR deliberately leaves unchanged (#11425); douwebot marked it optional
  • Source: https://github.com/pydantic/pydantic-ai/pull/11413

2026-10-26 · merged origin/main after #11406 (no conflicts) · iter -

2026-10-26 · Rewrote #11406's 'billed but not captured' sentences at 9a0b75c9ac61188f17ab4b95de40fd8398d1d787 · iter -

  • Decision: docs/agent.md recovery section and skill TESTING-AND-DEBUGGING.md now say the over-limit response is kept as interrupted and not re-requested, except a ModelRetry-rejected one (#11425); link Usage Limits. Pushed without local review (task budget 3/3 used); douwebot re-run reviews it
  • Why: douwebot sequencing thread
  • Source: https://github.com/pydantic/pydantic-ai/pull/11413#discussion_r4383576844

Checklist

  • No breaking changes in accordance with the version policy.
  • Any permitted compatibility impact has a label, warning, migration and release note, and an exact API-check waiver if the gate reports it.
  • PR title is fit for the release changelog.