Make `TestModel` streamed usage match `run()` for tool calls and text

Merged
PY
19d ago
+154-29

This pull request was posted by Claude Code using claude-opus-5-5 on behalf of David.

Closes #11854

Why we make these changes

TestModel reported different usage for the same flow under run() and under streaming. Thanks to @BlueX888 for the report. #6062 made text-only responses consistent; two causes remained in TestStreamedResponse:

  • A streamed ToolCallPart added no output tokens, where TestModel.request counts 1 + tokens(args).
  • Streamed text summed one estimate per fragment, which over-counts across delimiters: 'Paris, ' and 'France.' count 2 + 2, 'Paris, France.' counts 3.

Fixing only the first makes streams over-count: with one tool, output_tokens_limit=15 then raises on the stream while run() and main stay within it. This PR fixes both, so streamed usage equals run() usage per response and in total, in run_stream, run_stream_events and iter with node.stream.

[!WARNING]
Compatibility impact: streamed TestModel runs report different usage. A response with tool calls now counts their tokens, and text with punctuation counts fewer. Tests that snapshot streamed TestModel usage, or set a usage limit close to it, see new values.

Why this can ship in a minor release: TestModel usage is a test estimate, and #6062 established that streamed usage matches run(). The old streamed values were a bug.

Migration: update the snapshots. The new values equal what run() reports for the same flow.

New public surface: none

User-visible behavior

The issue's one-tool repro, output_tokens per response:

-run_stream(): 0 + 13 = 13    run(): 7 + 12 = 19
+run_stream(): 7 + 12 = 19    run(): 7 + 12 = 19

Implementation

  • The ToolCallPart arm adds _estimate_response_part_tokens(part), the estimate TestModel.request uses.
  • _map_text_part adds the change in the estimate of the text streamed so far. That change depends only on the last non-whitespace character and whether whitespace follows it, so the stream carries just those, and the cost stays linear. A fully consumed run_stream over 5,000 × 'word,' (median of 7): main 0.118 s, this PR 0.128 s. Recomputing the whole streamed prefix per fragment took 1.279 s.

Verification

  • test_usage_consistent_across_run_modes: text, one tool, two tools, an output tool, and text with delimiters, each through run, run_stream, run_stream_events and iter with node.stream. Four of the five cases fail on main.
  • test_streamed_output_tokens_limit_matches_run: a stream stays within an output_tokens_limit equal to run()'s output tokens (14, tighter than the 15 that a tool-only fix broke). Fails on main.
  • Re-snapshotted: tests/test_streaming.py, tests/test_usage_limits.py::test_streamed_text_limits and tests/test_cli.py::test_ask_agent_accumulates_usage. Each final per-response and total value now equals run()'s for the same flow.

What changes for existing users

Streamed TestModel usage changes as the warning describes. Nothing else.

PR decisions

2026-11-16 · adopted PR #11877 at 2026-11-16 · iter -

  • Decision: Branch-context bootstrapped from existing PR + issue; no resolved threads to backfill.
  • Why: pydanty-authored PR taken over by a managed PR agent
  • Source: https://github.com/pydantic/pydantic-ai/pull/11877
  • Session: d2a9a5c4-6baf-44b9-b9d6-6867c0fa482b

2026-11-16 · David picked (A) on 2026-11-15 · iter -

  • Decision: Fold both fixes: streamed TestModel usage must equal run() usage in every mode, for tool calls and for text; add compatibility impact label + [!WARNING] section
  • Why: Tool-only fix flips stream from under- to over-count and regresses output_tokens_limit=15 (readiness probes/05); users' usage snapshots change once
  • Source: https://github.com/pydantic/pydantic-ai/pull/11877
  • Session: d2a9a5c4-6baf-44b9-b9d6-6867c0fa482b

2026-11-16 · readiness facts (blind architect, main d564378d6) · iter -

  • Decision: Tool-call fix site: TestStreamedResponse._map_part ToolCallPart arm, call _estimate_response_part_tokens(part), do not copy the formula. Text: per-fragment estimation over-counts across delimiters; prefix-difference fold reaches parity but is quadratic (5,000 words 1.3 s vs 0.12 s); write a linear version or stop and report.
  • Why: Premise VALID, candidate DIVERGED; readiness at /home/agent/pydantic/ai/manager/local-notes/readiness/11877/
  • Source: https://github.com/pydantic/pydantic-ai/issues/11854
  • Session: d2a9a5c4-6baf-44b9-b9d6-6867c0fa482b

2026-11-16 · linear tail-carry text estimate · iter -

  • Decision: _map_text_part adds tokens(tail + fragment) - tokens(tail), tail = last non-whitespace char streamed + at most one following whitespace char; cumulative equals tokens(text streamed so far) after every fragment, so the part ends on the whole-string estimate
  • Why: Exact parity, linear. Fully consumed run_stream, median of 7: 5,000 x 'word,' main 0.118 s, head 0.128 s, prefix-difference 1.279 s; 5,000 x 'word' main 0.118 s, head 0.117 s, prefix-difference 1.332 s; 50,000 x 'word,' main 1.288 s, head 1.159 s. Fuzz: 200k random fragmentations 0 violations; 1,500 random texts run()==run_stream() and monotone
  • Source: https://github.com/pydantic/pydantic-ai/pull/11877
  • Session: d2a9a5c4-6baf-44b9-b9d6-6867c0fa482b

2026-11-16 · pre-push review 1 of 3 at 41d2c03da9f810af0cfa00b6405c587ba138e178 · iter -

2026-11-16 · pre-push review 1 of 3 at 41d2c03da9f810af0cfa00b6405c587ba138e178 · iter -

  • Decision: remediated: moved the ToolCallPart usage line above the args-cast comment block so the comment stays on the yield it explains (one finding). First launch failed before any model ran (CLI flag parsing swallowed the prompt), so it consumed no review.
  • Why: reviewed tree 3eb0a9ffe86dca343e7b5d6d1f7486739bc154cb; scope 2a690aacc..41d2c03da full branch; light tier haiku via claude -p from detached policy-base ae2e70340, read-only tools, no fan-out
  • Source: https://github.com/pydantic/pydantic-ai/pull/11877
  • Session: d2a9a5c4-6baf-44b9-b9d6-6867c0fa482b

2026-11-16 · exempt delta f3e9c16cf2834374ab6bbfe1f75f9c01ba008806 chains from reviewed 41d2c03da9f810af0cfa00b6405c587ba138e178 · iter -

  • Decision: Push without review 2 of 3: the delta moves one unchanged statement above a comment block in the same match arm
  • Why: Rubric rungs: public API untouched; behavior unchanged (the same statement still runs before the same yield, nothing between them executes); docs/tests untouched; code quality is the review finding it applies. Targeted tests rerun.
  • Source: https://github.com/pydantic/pydantic-ai/pull/11877
  • Session: d2a9a5c4-6baf-44b9-b9d6-6867c0fa482b

2026-11-16 · step 7 second opinion: none · iter -

  • Decision: Overmanager picked none on 2026-11-16
  • Why: Parity fuzz (200k fragmentations, 0 mismatches) tests the tail-carry argument directly; douwebot approved the full diff; compatibility impact label and [!WARNING] cover the changed values
  • Source: https://github.com/pydantic/pydantic-ai/pull/11877
  • Session: d2a9a5c4-6baf-44b9-b9d6-6867c0fa482b

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.

https://claude.ai/code/session_01BYcNCm2ZQL4M5Exiqwh2Ho