Bring 22 `pydantic_ai` message-history functions under the cognitive complexity limit of 15
This pull request was posted by Claude Code using claude-opus-5-5 on behalf of David.
Why we make these changes
The cognitive complexity gate from #11117 allows 15 per function. 22 functions in the message-history modules scored over that on main, 582 points in total: the instruction window and recorded-prefix passes in _instructions.py, dynamic system prompt re-evaluation, local tool-search synthesis, and in messages.py the _clean_message_history passes, sanitize_messages, part promotion, compaction windows, OTel conversion and ThinkingPartDelta.apply. This PR brings each of them to 15 or under with no change in behavior. It does not close #10983: the remaining packages and modules are later PRs.
Each function took the fix that agent_docs/complexity.md names for its shape:
- History passes (
update_instruction_history,_dangling_tool_calls_by_response,_repair_dangling_tool_calls,_drop_orphaned_tool_results,_drop_compaction_parts,_post_compaction_window_start,_post_compaction_window_for_response,reevaluate_dynamic_system_prompts,synthesize_local_tool_search_messages): the index phase and the rebuild split into their own functions, such as_dangling_tool_calls_to_repairand_synthesized_tool_returns, withcontinueguards. - Arms per message or part kind (
_merge_consecutive_messages,narrow_message_parts,_check_parts,ThinkingPartDelta.apply,UserPromptPart.otel_message_parts): one function per kind, such as_append_request/_append_responseandThinkingPartDelta._apply_to_part/_apply_to_delta. - Request-wide state on a context (
resolve_sourced_instructions,_sanitize_messages): a private data-only dataclass, asmodels/anthropic/__init__.py::_MapMessagesContextis, with one module function per input kind next to the caller._sanitize_messages' warnings move into_warn_sanitizedwithstacklevel=4, so they still point at the caller ofsanitize_messagesor the UI adapter. - Closure-hosted (
recorded_prefix): the recursive nestedsplitbecame the module function_split_recorded_prefix. - The rest (
_register_typed_tool_part,CapabilityEvent.__init_subclass__,_sanitize_tool_return_content,BaseToolReturnPart.content_items,RetryPromptPart.model_response): one check or handler moved next to its only caller, or a ternary.
New public surface
None. Every new function, method and class is private.
Verification
- Existing tests and inline snapshots pass unchanged, over the test files that reach each changed module. No test file, snapshot or cassette changes.
- Request bodies are byte-identical,
mainagainst this branch: 172 HTTP bodies over 78 test nodes, across Anthropic, OpenAI Responses and Chat, OpenRouter, Gemini, Groq, Cohere and Bedrock, plus the 624 historiesFunctionModelandTestModelreceived over 319 nodes. 0 differences. - Streamed events from thinking-delta streams are identical with
tests/refactor_capture.py: 23 nodes, 0 differences. scripts/check_complexity.pypasses. Every function in the 4 changed files scores 15 or under; the 34 new private functions score 1 to 15.
Before and after scores: 582 → 231
| Function | File | Before | After |
|---|---|---|---|
update_instruction_history | _instructions.py | 41 | 15 |
_dangling_tool_calls_by_response | messages.py | 38 | 7 |
ThinkingPartDelta.apply | messages.py | 36 | 2 |
UserPromptPart.otel_message_parts | messages.py | 35 | 12 |
reevaluate_dynamic_system_prompts | _system_prompt.py | 33 | 11 |
synthesize_local_tool_search_messages | _tool_search.py | 32 | 10 |
_check_parts | messages.py | 32 | 13 |
_merge_consecutive_messages | messages.py | 32 | 4 |
recorded_prefix | _instructions.py | 30 | 3 |
_sanitize_messages | messages.py | 28 | 7 |
_repair_dangling_tool_calls | messages.py | 25 | 15 |
CapabilityEvent.__init_subclass__ | messages.py | 24 | 15 |
resolve_sourced_instructions | _instructions.py | 23 | 9 |
_register_typed_tool_part | messages.py | 23 | 12 |
narrow_message_parts | messages.py | 23 | 5 |
_drop_compaction_parts | messages.py | 21 | 8 |
_sanitize_tool_return_content | messages.py | 21 | 15 |
_post_compaction_window_start | messages.py | 19 | 13 |
BaseToolReturnPart.content_items | messages.py | 17 | 11 |
_drop_orphaned_tool_results | messages.py | 17 | 15 |
RetryPromptPart.model_response | messages.py | 16 | 15 |
_post_compaction_window_for_response | messages.py | 16 | 14 |
| Total | 582 | 231 |
Request-body capture
Captured with an httpx request tap, and a tap on the message history FunctionModel and TestModel receive, for the passes whose tests run no provider. Each capture ran over main's library sources and over this branch's with the same tests, and the two were diffed per test node after normalizing generated ids, multipart boundaries and clock values (timestamps, attempt durations).
| Pass | Test nodes | HTTP bodies | Model inputs |
|---|---|---|---|
Instruction history (update_instruction_history, recorded_prefix, resolve_sourced_instructions) | tests/test_instruction_updates.py (Anthropic, OpenRouter, OpenAI Responses, and their fallback members) | 82 | 251 |
Dangling calls, orphaned results, merged requests (_clean_message_history) | tests/test_transcript_repair.py | – | 34 |
| Request-side compaction window and merge | tests/models/test_unattributed_compaction.py (OpenAI Chat and Responses, Anthropic, Gemini, Groq, Cohere) | 30 | – |
| Mid-conversation system prompts and merged requests | tests/models/test_anthropic_mid_conversation_system.py (Anthropic, Anthropic on Bedrock) | 20 | – |
Dynamic system prompts (reevaluate_dynamic_system_prompts) | tests/test_dynamic_system_prompt_changes.py | – | 39 |
Local tool-search synthesis (synthesize_local_tool_search_messages) | tests/test_tool_search.py::test_cross_provider_capability_replay (5 cases), test_anthropic_to_google_deferred_capability_history_replay, test_live_tool_search_handoff_anthropic_openai_anthropic, test_openai_promotes_local_search_history_round_trip, test_anthropic_promotes_local_search_history_round_trip, test_openai_multiple_native_tool_searches_stream_through_ag_ui | 41 | – |
UI sanitization and narrowing (_sanitize_messages, _drop_compaction_parts, narrow_message_parts) | tests/test_ag_ui.py, tests/test_vercel_ai.py | 2 | 300 |
Stream-event capture
uv run python -m tests.refactor_capture "$(git merge-base HEAD upstream/main)" <nodes> over the streams that apply ThinkingPartDeltas: test_openai_responses_raw_cot_stream_openrouter (callable provider_details), test_openai_responses_thinking_with_code_execution_tool_stream, test_anthropic_model_thinking_part_stream, test_anthropic_model_thinking_part_redacted_stream, test_bedrock_model_thinking_part_stream and tests/models/test_openai_stream_part_boundaries.py. 23 nodes and 34 records on each side, 1,360 stream events, 0 differences.
What changes for existing users
Nothing.
PR decisions
2026-11-03 · R4 scope re-scored on main 78372f8a7 · iter -
- Decision: All 22 listed functions in scope at their listed scores; no logic moved out of them since the inventory commit d44704ec7 (only a docstring and two with_config decorators changed in these files)
- Why: dispatch: re-score on current main, drop any under 15, pick up moved logic
- Source: https://github.com/pydantic/pydantic-ai/issues/10983
- Session: 8df97991-63d8-4104-8825-4c94d5a96d38
2026-11-03 · warning frames kept on the public caller · iter -
- Decision: _sanitize_messages' seven warnings move into _MessageSanitizer.warn, one frame deeper, so stacklevel goes 3 -> 4 and they still point at the caller of sanitize_messages / the UI adapter method
- Why: behavior unchanged: the docstring says warnings point at the caller of the public function
- Source: https://github.com/pydantic/pydantic-ai/issues/10983
- Session: 8df97991-63d8-4104-8825-4c94d5a96d38
2026-11-03 · context dataclasses for resolve_sourced_instructions and _sanitize_messages · iter -
- Decision: Both carry request-wide state on a private dataclass with one method per input kind (_ResolvedInstructions, _MessageSanitizer), as OpenAIChatModel._MapModelResponseContext does, instead of module functions taking 7-9 pass-through arguments
- Why: agent_docs/complexity.md part-ladder fix: keep request-wide state on a context; avoids helper signatures that thread every option
- Source: https://github.com/pydantic/pydantic-ai/issues/10983
- Session: 8df97991-63d8-4104-8825-4c94d5a96d38
2026-11-03 · proof W extended to FunctionModel and TestModel inputs · iter -
- Decision: No cassette test sends a dangling-call, orphaned-result or dynamic-system-prompt history over HTTP; those passes are proved by a local companion tap (local-notes/r4/plugin/fn_trace.py) recording the history FunctionModel/TestModel receive, diffed main vs branch alongside wire_trace's HTTP bodies
- Why: dispatch: prove byte-identical request bodies through each rewritten pass; test_transcript_repair.py and test_dynamic_system_prompt_changes.py drive those passes through FunctionModel only
- Source: https://github.com/pydantic/pydantic-ai/issues/10983
- Session: 8df97991-63d8-4104-8825-4c94d5a96d38
2026-11-03 · pre-push review 1 of 3 at 6a5943492d6e04b87e2fa5e5fb1ea72b32fe9837 · iter -
- Decision: reserved; outcome pending
- Why: tree 6743fcbab3fa903a3321a2568efa2f760d1038ae; scope 78372f8a7..6a5943492 (full branch); policy base 78372f8a7; first review; light tier (haiku) per Model tiers
- Source: https://github.com/pydantic/pydantic-ai/tree/history-passes-complexity
- Session: 8df97991-63d8-4104-8825-4c94d5a96d38
2026-11-03 · proof W normalization beyond compare_norm2 · iter -
- Decision: W diff adds three normalizers to compare_norm2's set: 32-hex uuid4().hex ids (conversation_id), epoch-ms event timestamps near the capture time, and FailedAttempt durations; before them 108 nodes differed only in those values, after them 0 of 398
- Why: those values come from uuid4 and the clock in both runs, not from the refactored passes
- Source: https://github.com/pydantic/pydantic-ai/issues/10983
- Session: 8df97991-63d8-4104-8825-4c94d5a96d38
2026-11-03 · pre-push review 1 of 3 at 6a5943492d6e04b87e2fa5e5fb1ea72b32fe9837 · iter -
- Decision: remediated in 061a7961f: two re-indented warning f-strings split under 120 columns (same text); closure parameter aliases dropped in _chain_provider_details (pyright still narrows). Skipped: a private alias for the non-None ProviderDetailsDelta union, net-neutral, since main already spells that union in _serialize_provider_details_delta and aliasing it rewrites the public ProviderDetailsDelta definition. Reviewer found no behavior difference
- Why: tree 6743fcbab3fa903a3321a2568efa2f760d1038ae; scope 78372f8a7..6a5943492 full branch
- Source: https://github.com/pydantic/pydantic-ai/tree/history-passes-complexity
- Session: 8df97991-63d8-4104-8825-4c94d5a96d38
2026-11-03 · pre-push review 2 of 3 at 061a7961ffd01748d3b3c44e155f65a6180b9de8 · iter -
- Decision: reserved; outcome pending
- Why: tree 5ca8e3b5e1f34e01a76716e0b2550ae8f80738ef; follow-up scope 6a5943492..061a7961f (review 1's fixes), prior findings to verify; light tier (haiku)
- Source: https://github.com/pydantic/pydantic-ai/tree/history-passes-complexity
- Session: 8df97991-63d8-4104-8825-4c94d5a96d38
2026-11-03 · pre-push review 2 of 3 at 061a7961ffd01748d3b3c44e155f65a6180b9de8 · iter -
- Decision: remediated in 3e4fb6b8b: finding 1's first split had pushed the overflow into the next literals (155 and 121 columns); both re-split, AST-joined warning texts identical to main's 7. Findings 2 (alias dismissal) and 3 (aliases dropped) accepted
- Why: tree 5ca8e3b5e1f34e01a76716e0b2550ae8f80738ef; follow-up scope 6a5943492..061a7961f
- Source: https://github.com/pydantic/pydantic-ai/tree/history-passes-complexity
- Session: 8df97991-63d8-4104-8825-4c94d5a96d38
2026-11-03 · pre-push review 3 of 3 at 3e4fb6b8bc84a84f0620cecf254962790129bee5 · iter -
- Decision: reserved; outcome pending
- Why: tree c4e58457351e8f50f05c93457ab33a5340507aa4; follow-up scope 061a7961f..3e4fb6b8b (review 2's fix); light tier (haiku)
- Source: https://github.com/pydantic/pydantic-ai/tree/history-passes-complexity
- Session: 8df97991-63d8-4104-8825-4c94d5a96d38
2026-11-03 · pre-push review 3 of 3 at 3e4fb6b8bc84a84f0620cecf254962790129bee5 · iter -
- Decision: current: both review-2 fixes verified, no new findings
- Why: tree c4e58457351e8f50f05c93457ab33a5340507aa4; follow-up scope 061a7961f..3e4fb6b8b
- Source: https://github.com/pydantic/pydantic-ai/tree/history-passes-complexity
- Session: 8df97991-63d8-4104-8825-4c94d5a96d38
2026-11-03 · douwebot review 1: contexts made data-only · iter -
- Decision: _MessageSanitizer -> data-only _SanitizeMessagesContext with module functions _sanitize_request, _sanitize_response, _warn_sanitized; _ResolvedInstructions -> data-only _ResolveInstructionsContext with _add_instruction_part, _add_instruction_text, _flush_instruction_group (the function-result arm went back inline); _serialize_content_items -> private staticmethod on BaseToolReturnPart. Supersedes the context-dataclass entry's 'one method per input kind'
- Why: agent_docs/provider-adapters.md: 'a context that nothing subclasses holds data only'; agent_docs/complexity.md: a complexity helper is a private method on the class or a function next to its only caller
- Source: https://github.com/pydantic/pydantic-ai/pull/12382#discussion_r4461265953
- Session: 8df97991-63d8-4104-8825-4c94d5a96d38
- Supersedes: context dataclasses for resolve_sourced_instructions and _sanitize_messages
2026-11-03 · review budget exhausted before d96390f61 · iter -
- Decision: pushed d96390f61 without a fourth pre-push review; it is douwebot's remediation, verified locally (pyright, ruff, gate, AST-identical warning texts, affected tests and a fresh W head capture) and re-reviewed by douwebot
- Why: pushing-commits-to-the-repo: after the third review, remediate and run local checks; do not dispatch a fourth
- Source: https://github.com/pydantic/pydantic-ai/pull/12382
- Session: 8df97991-63d8-4104-8825-4c94d5a96d38
2026-11-03 · douwebot review 5760454999 left undismissed · iter -
- Decision: Do not dismiss review 5760454999; re-apply douwebot once CI is green on the fixed head
- Why: a newer douwebot review replaces its older CHANGES_REQUESTED in reviewDecision, so the fresh APPROVE on d96390f61 makes the dismissal moot
- Source: https://github.com/pydantic/pydantic-ai/pull/12382#pullrequestreview-5760454999
- Session: 8df97991-63d8-4104-8825-4c94d5a96d38
2026-11-03 · chore label kept alongside refactor · iter -
- Decision: Keep both chore and refactor on #12382
- Why: bots.yml's category classifier defines 'chore: CI, refactoring, dev dependencies, tests-only'; release.yml excludes chore from the changelog, where a no-behavior-change refactor does not belong; #12303, #12354 and #12375 merged with both
- Source: https://github.com/pydantic/pydantic-ai/pull/12382
- Session: 8df97991-63d8-4104-8825-4c94d5a96d38
2026-11-04 · merge-queue removal: conflict with #11930 · iter -
- Decision: #11930 (a7e14d5d0) landed first and conflicts in reevaluate_dynamic_system_prompts; merged main in 0cfc30483, carrying #11930's new context_id=runner.context_id argument into _reevaluate_request_parts, so _system_prompt.py differs from main only by the extraction
- Why: D6: refactor PRs go first and #11930 rebases, but #11930 merged first, so this PR absorbs its change instead
- Source: https://github.com/pydantic/pydantic-ai/pull/11930
- Session: 8df97991-63d8-4104-8825-4c94d5a96d38
2026-11-04 · session_instruction_update (18) left as on main · iter -
- Decision: #11930 adds session_instruction_update to _instructions.py at complexity 18 on main; this PR leaves it unchanged, outside the R4 scope
- Why: a function outside the named fold set is not folded without a decision
- Source: https://github.com/pydantic/pydantic-ai/pull/11930
- Session: 8df97991-63d8-4104-8825-4c94d5a96d38
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.