Bring 22 `pydantic_ai` message-history functions under the cognitive complexity limit of 15

Merged
DS
1mo ago
+706-502

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_repair and _synthesized_tool_returns, with continue guards.
  • 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_response and ThinkingPartDelta._apply_to_part / _apply_to_delta.
  • Request-wide state on a context (resolve_sourced_instructions, _sanitize_messages): a private data-only dataclass, as models/anthropic/__init__.py::_MapMessagesContext is, with one module function per input kind next to the caller. _sanitize_messages' warnings move into _warn_sanitized with stacklevel=4, so they still point at the caller of sanitize_messages or the UI adapter.
  • Closure-hosted (recorded_prefix): the recursive nested split became 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, main against this branch: 172 HTTP bodies over 78 test nodes, across Anthropic, OpenAI Responses and Chat, OpenRouter, Gemini, Groq, Cohere and Bedrock, plus the 624 histories FunctionModel and TestModel received 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.py passes. 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
FunctionFileBeforeAfter
update_instruction_history_instructions.py4115
_dangling_tool_calls_by_responsemessages.py387
ThinkingPartDelta.applymessages.py362
UserPromptPart.otel_message_partsmessages.py3512
reevaluate_dynamic_system_prompts_system_prompt.py3311
synthesize_local_tool_search_messages_tool_search.py3210
_check_partsmessages.py3213
_merge_consecutive_messagesmessages.py324
recorded_prefix_instructions.py303
_sanitize_messagesmessages.py287
_repair_dangling_tool_callsmessages.py2515
CapabilityEvent.__init_subclass__messages.py2415
resolve_sourced_instructions_instructions.py239
_register_typed_tool_partmessages.py2312
narrow_message_partsmessages.py235
_drop_compaction_partsmessages.py218
_sanitize_tool_return_contentmessages.py2115
_post_compaction_window_startmessages.py1913
BaseToolReturnPart.content_itemsmessages.py1711
_drop_orphaned_tool_resultsmessages.py1715
RetryPromptPart.model_responsemessages.py1615
_post_compaction_window_for_responsemessages.py1614
Total582231
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).

PassTest nodesHTTP bodiesModel inputs
Instruction history (update_instruction_history, recorded_prefix, resolve_sourced_instructions)tests/test_instruction_updates.py (Anthropic, OpenRouter, OpenAI Responses, and their fallback members)82251
Dangling calls, orphaned results, merged requests (_clean_message_history)tests/test_transcript_repair.py–34
Request-side compaction window and mergetests/models/test_unattributed_compaction.py (OpenAI Chat and Responses, Anthropic, Gemini, Groq, Cohere)30–
Mid-conversation system prompts and merged requeststests/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_ui41–
UI sanitization and narrowing (_sanitize_messages, _drop_compaction_parts, narrow_message_parts)tests/test_ag_ui.py, tests/test_vercel_ai.py2300
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 -

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 -

2026-11-03 · pre-push review 2 of 3 at 061a7961ffd01748d3b3c44e155f65a6180b9de8 · iter -

2026-11-03 · pre-push review 3 of 3 at 3e4fb6b8bc84a84f0620cecf254962790129bee5 · iter -

2026-11-03 · pre-push review 3 of 3 at 3e4fb6b8bc84a84f0620cecf254962790129bee5 · iter -

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 -

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.