Keep the response that crosses a token or cost limit in `capture_run_messages`
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 onmainand passes here: captured messages snapshot withstate='interrupted',usage.requests == 1, the model's own response object leftcomplete, 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_usagecovers theModelRetrybranch that still records a recovered response's usage when it commits it.- Local runs of every test module touching usage limits or
capture_run_messagespass (apart from Bedrock-credential and Prefect/DBOS failures that also fail onmainlocally).
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/mainand rewrites #11406's "billed but not captured" sentences in thedocs/agent.mdrecovery section and the skill'sreferences/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 (ModelRetryrejection,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 -
- Decision: reserved (dispatching)
- Why: tree 319c06b836d455fd374ebd1586d7a65ec6a87176; scope full branch c432cba022a22b50ae1078ee516b1fc8583d1019..311849f9679ddb11478c9bd3fc8266801907cf12; first review
- Source: https://github.com/pydantic/pydantic-ai/tree/fix-usage-limit-captured-response
2026-10-26 · pre-push review 1 of 3 at 311849f9679ddb11478c9bd3fc8266801907cf12 · iter -
- Decision: no review performed: read-only Explore reviewer's file tools are rooted in another checkout and could not open /tmp bundle/diff/policy-base
- Why: tree 319c06b836d455fd374ebd1586d7a65ec6a87176; scope full branch c432cba022a22b50ae1078ee516b1fc8583d1019..311849f9679ddb11478c9bd3fc8266801907cf12; dispatch counted against budget even though it returned no verdict
- Source: https://github.com/pydantic/pydantic-ai/tree/fix-usage-limit-captured-response
2026-10-26 · pre-push review 2 of 3 at 311849f9679ddb11478c9bd3fc8266801907cf12 · iter -
- Decision: reserved (dispatching fresh no-history 'self' reviewer, read-only by instruction, reading via shell)
- Why: tree 319c06b836d455fd374ebd1586d7a65ec6a87176; scope full branch c432cba022a22b50ae1078ee516b1fc8583d1019..311849f9679ddb11478c9bd3fc8266801907cf12; same content as dispatch 1
- Source: https://github.com/pydantic/pydantic-ai/tree/fix-usage-limit-captured-response
2026-10-26 · pre-push review 2 of 3 at 311849f9679ddb11478c9bd3fc8266801907cf12 · iter -
- Decision: remediated: moved docs paragraph into Usage Limits (+ModelRetry/requests caveats), production.md links #usage-limits, test snapshots captured messages and pins usage.requests; ModelRetry-branch and continuation/fallback findings kept out of scope (documented, PR body)
- Why: tree 319c06b836d455fd374ebd1586d7a65ec6a87176; scope full branch c432cba022a22b50ae1078ee516b1fc8583d1019..311849f9679ddb11478c9bd3fc8266801907cf12; 4 findings
- Source: https://github.com/pydantic/pydantic-ai/tree/fix-usage-limit-captured-response
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 -
- Decision: reserved (dispatching)
- Why: tree 1d840bc51fd5bb0382351c8f6a2a9aec345ba94e; follow-up scope 311849f9679ddb11478c9bd3fc8266801907cf12..423390061950f705e6bab8f319086823e416f292 plus prior findings; full branch diff as context
- Source: https://github.com/pydantic/pydantic-ai/tree/fix-usage-limit-captured-response
2026-10-26 · pre-push review 3 of 3 at 423390061950f705e6bab8f319086823e416f292 · iter -
- Decision: remediated: scoped the docs ModelRetry sentence to responses that cross a limit (at d427fb0d9eb0aaac20ce62bf8f0cf926d934941c); budget exhausted, no further dispatch
- Why: tree 1d840bc51fd5bb0382351c8f6a2a9aec345ba94e; follow-up scope 311849f9679ddb11478c9bd3fc8266801907cf12..423390061950f705e6bab8f319086823e416f292; prior 4 findings verified fixed/answered; 1 minor docs finding
- Source: https://github.com/pydantic/pydantic-ai/tree/fix-usage-limit-captured-response
2026-10-26 · Over-limit docs live in Usage Limits · iter -
- Decision: Docs sentence lives in docs/agent.md '#### Usage Limits' (not the capture/model-errors section) plus docs/production.md cost section; #11376 section still left to that issue
- Why: Pre-push review 2 finding 3: placement interrupted the interrupted-messages example
- Source: https://github.com/pydantic/pydantic-ai/tree/fix-usage-limit-captured-response
- Supersedes: Recovery docs section left to #11376
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 -
- Decision: Settled (a): keep counting
- Why: Maintainer decision
- Source: https://github.com/pydantic/pydantic-ai/pull/11413#issuecomment-6426994894
2026-10-26 · Douwe: uncovered paths tracked in #11425 · iter -
- Decision: ModelRetry rejection, pause_turn/background continuations and FallbackModel-rejected responses stay out of scope; follow-up #11425
- Why: Maintainer decision
- Source: https://github.com/pydantic/pydantic-ai/pull/11413#issuecomment-6426994894
2026-10-26 · pre-push review 1 of 3 (task: implement option b) at 1d3e415abc518e2aa4a5bd5b92b2597784f2fff7 · iter -
- Decision: reserved (dispatching)
- Why: tree df38e4f7a9bb3f63d161c5f5075e910db42aeb52; follow-up scope d427fb0d9eb0aaac20ce62bf8f0cf926d934941c..1d3e415abc518e2aa4a5bd5b92b2597784f2fff7 (last locally reviewed commit) plus douwebot findings; new task, new budget
- Source: https://github.com/pydantic/pydantic-ai/pull/11413
2026-10-26 · pre-push review 1 of 3 (task: implement option b) at 1d3e415abc518e2aa4a5bd5b92b2597784f2fff7 · iter -
- Decision: remediated: messages.py ModelResponseState/state docstrings name the new interrupted case; agent.md 'parts streamed' sentence narrowed; replace committed copy instead of mutating response (+test); PR body to be updated after push
- Why: tree df38e4f7a9bb3f63d161c5f5075e910db42aeb52; scope d427fb0d9eb0aaac20ce62bf8f0cf926d934941c..1d3e415abc518e2aa4a5bd5b92b2597784f2fff7; 4 findings, all valid
- Source: https://github.com/pydantic/pydantic-ai/pull/11413
2026-10-26 · pre-push review 2 of 3 (task: implement option b) at 8764a833ca8ffb20b1a6961180ade909d4d51d31 · iter -
- Decision: reserved (dispatching)
- Why: tree abee2725d083f344ef98f0ffa1d2a50c5493cb89; follow-up scope 1d3e415abc518e2aa4a5bd5b92b2597784f2fff7..8764a833ca8ffb20b1a6961180ade909d4d51d31 plus prior findings
- Source: https://github.com/pydantic/pydantic-ai/pull/11413
2026-10-26 · pre-push review 2 of 3 (task: implement option b) at 8764a833ca8ffb20b1a6961180ade909d4d51d31 · iter -
- Decision: remediated finding 2 (_repair_interrupted_tail docstring) at 96d32fbda667d9ede12d29a84168a4646581313a; finding 1 is PR metadata/threads (done after push); finding 3 (speech [Interrupted] marker) dismissed: no model adapter builds SpeechPart, realtime sessions don't go through ModelRequestNode._finish_handling
- Why: tree abee2725d083f344ef98f0ffa1d2a50c5493cb89; scope 1d3e415abc518e2aa4a5bd5b92b2597784f2fff7..8764a833ca8ffb20b1a6961180ade909d4d51d31
- Source: https://github.com/pydantic/pydantic-ai/pull/11413
2026-10-26 · exempt delta: docstring-only at 96d32fbda667d9ede12d29a84168a4646581313a · iter -
- Decision: Pushed without a further review
- Why: Comments/docstrings-only row: git diff 8764a833ca8ffb20b1a6961180ade909d4d51d31..96d32fbda667d9ede12d29a84168a4646581313a changes only a docstring in _agent_graph.py; chains from reviewed 8764a833ca8ffb20b1a6961180ade909d4d51d31
- Source: https://github.com/pydantic/pydantic-ai/pull/11413
2026-10-26 · Douwe: over-limit response marked interrupted · iter -
- Decision: Implement option (b): replace the committed copy with state='interrupted' when a token/cost limit raises
- Why: Maintainer decision; both continuations work with no re-billing
- Source: https://github.com/pydantic/pydantic-ai/pull/11413#issuecomment-6427921182
- Supersedes: Over-limit response is committed as an ordinary complete response
2026-10-26 · exempt delta: docstring-only at e6eab83d840f06a436a371e77261ff086da8312d · iter -
- Decision: douwebot finding: widened 'interrupted' lead in ModelResponseState/ModelResponse.state and added the over-limit case to capture_run_messages docstring; pushed without review
- Why: Comments/docstrings-only row: only docstring lines changed since reviewed 8764a833ca8ffb20b1a6961180ade909d4d51d31 (+ exempt 96d32fbda667d9ede12d29a84168a4646581313a)
- Source: https://github.com/pydantic/pydantic-ai/pull/11413
2026-10-26 · Douwe: merge #11406 first · iter -
- Decision: After #11406 merges, merge origin/main into this branch and rewrite its 'billed but not captured' sentences in docs/agent.md recovery section and the skill's TESTING-AND-DEBUGGING.md
- Why: Maintainer sequencing decision
- Source: https://github.com/pydantic/pydantic-ai/pull/11413#issuecomment-6428198762
2026-10-26 · pre-push review 3 of 3 (task: implement option b) at 571ac42ff1af9cb428fc105c80e99e360b52d5cb · iter -
- Decision: reserved (dispatching)
- Why: tree ec1ff684107a15ba67ede8402fc2de78610ea773; follow-up scope 8764a833ca8ffb20b1a6961180ade909d4d51d31..571ac42ff1af9cb428fc105c80e99e360b52d5cb (two docstring-only commits + message-history.md fix for douwebot thread)
- Source: https://github.com/pydantic/pydantic-ai/pull/11413
2026-10-26 · pre-push review 3 of 3 (task: implement option b) at 571ac42ff1af9cb428fc105c80e99e360b52d5cb · iter -
- Decision: remediated: rewrapped two over-long docstring lines (at 8c46fc79c1480e6cc231635517e49b597acec6b2); prior findings verified; speech-marker dismissal holds except for custom speech models crossing a limit (non-blocking, noted); budget exhausted
- Why: tree ec1ff684107a15ba67ede8402fc2de78610ea773; scope 8764a833ca8ffb20b1a6961180ade909d4d51d31..571ac42ff1af9cb428fc105c80e99e360b52d5cb
- Source: https://github.com/pydantic/pydantic-ai/pull/11413
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 -
- Decision: Merge commit, no conflict resolution; exempt target-branch merge
- Why: Douwe's sequencing decision; #11406 merged 23:07Z
- Source: https://github.com/pydantic/pydantic-ai/pull/11413#issuecomment-6428198762
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.