Bring 21 `pydantic_ai` schema, signature and prompt-formatting functions under the cognitive complexity limit of 15

Merged
DS
1mo ago
+734-540

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. 21 schema, signature and prompt-formatting functions scored over that on main, 612 points in total: the OpenAI, Google and base JSON schema transformers, function_schema and its docstring parsing, the code-mode signature renderer, Choices, Anthropic's strict schema limits, $defs merging, format_as_xml, the agent spec schema builder, group_by_temporal and ScopedTask.wait_passing_on_cancellation. This PR brings each of them to 15 or under with no change in behavior. It is part of #10983, which it does not close: the remaining modules are later PRs.

Each function took the fix that agent_docs/complexity.md names for its shape:

  • Tree-walks, one handler per node kind: OpenAIJsonSchemaTransformer.transform (_transform_ref, _transform_strict_incompatible_values, _transform_object, _check_array_items), GoogleOpenAPISchemaTransformer.transform (_fit_enum_to_strings, _widen_tuple), JsonSchemaTransformer._handle (_inlined_ref; the $ref inlining bound is untouched), _drop_unsupported_schema_keywords, _type_to_expr / _schema_to_type_expr (_ref_to_expr, _array_to_expr, _object_to_expr), _update_mapped_json_schema_refs, and _ToXml's dataclass and model handlers.
  • Closure-hosted: the nested defs of group_by_temporal became module functions over a private data-only _TemporalGroupsContext, which holds the pull its cleanup cancels; those of _replace_type_refs and build_schema_types became module functions.
  • State on a data-only context: function_schema's per-parameter loop state moved onto a private data-only _FunctionSchemaContext, filled by _add_parameter and _add_field next to the caller.
  • Named phases and predicates (single-use, as the guide allows): Choices, merge_json_schema_defs, exceeded_limit, doc_descriptions, enum_member_docstrings, _flatten_all_of and google_realtime_model_profile. wait_passing_on_cancellation only moved its message ternary out; every cancellation path stays in place.

New public surface

None. Every new function, method and class is private, and Choices keeps its signature, overloads and docstring.

Verification

  • Existing tests and inline snapshots pass unchanged over the 39 test files that reach the changed modules. No test file, snapshot or cassette changes.
  • Requests are byte-identical, main against this branch, with tests/refactor_capture.py: 164 requests over 82 test nodes, 0 differences, across OpenAI strict schemas, Google, Anthropic schema limits and the Gemini Live function declarations that carry the OpenAPI subset.
  • scripts/check_complexity.py passes. Every function in the 11 changed files scores 15 or under; the 34 new or hoisted private functions score 0 to 15. The two # noqa: C901 markers RUF100 flagged are gone.
Before and after scores: 612 → 200
FunctionFileBeforeAfter
OpenAIJsonSchemaTransformer.transformprofiles/openai.py6911
function_schema_function_schema.py5614
_ToXml._parse_data_structuresformat_prompt.py5011
group_by_temporal_utils.py310
_type_to_exprfunction_signature.py315
build_schema_types_spec.py3011
Choicesoutput.py3010
merge_json_schema_defs_utils.py2815
_drop_unsupported_schema_keywordsprofiles/google.py282
GoogleOpenAPISchemaTransformer.transformprofiles/google.py285
JsonSchemaTransformer._handle_json_schema.py2714
_update_mapped_json_schema_refs_utils.py275
_replace_type_refsfunction_signature.py274
_schema_to_type_exprfunction_signature.py239
exceeded_limitmodels/_anthropic_schema_limits.py215
_flatten_all_ofprofiles/google.py2114
doc_descriptions_griffe.py1815
_ToXml._to_xmlformat_prompt.py1812
ScopedTask.wait_passing_on_cancellation_utils.py1711
enum_member_docstrings_utils.py1614
google_realtime_model_profileprofiles/google.py1613
Total612200
Request capture

uv run python -m tests.refactor_capture "$(git merge-base HEAD upstream/main)" <nodes>, with a local plugin that also records each frame tests/realtime/ws_cassettes.py::ReplayWebSocket.send sends as a request record: Gemini Live is the only wire path of GoogleOpenAPISchemaTransformer, _drop_unsupported_schema_keywords and google_realtime_model_profile, and the capture records HTTP only. 82 nodes and 177 records on each side, 164 requests, 157 stream events, 0 differing, 0 one-sided.

Changed codeTest nodes
OpenAI strict schemas (OpenAIJsonSchemaTransformer)test_openai.py::test_strict_mode_cannot_infer_strict (all cases), ::test_openai_native_output_multiple, ::test_openai_responses_native_output_decimal_strict, test_openai_json_pointer_refs.py::test_mcp_json_pointer_ref_tool, ::test_mcp_zod4_definitions_tool, test_openai_responses.py::test_native_output_multiple
Google schemas and Gemini Live declarationstest_google.py::test_google_native_output_multiple, ::test_google_discriminated_union_native_output, ::test_google_prefix_items_native_output, test_google_boolean_schema_defs.py, realtime/test_google_ws.py::test_tool_call_round, ::test_tool_with_recursive_map_values, ::test_tool_with_property_names_and_contains_refs, ::test_extended_thinking_async_tool_round, ::test_async_tool_speech_stays_before_its_result
Anthropic schema limitsanthropic/test_strict_schema_limits.py::test_default_output_over_limits_uses_non_strict_tool_output, test_anthropic.py::test_anthropic_incompatible_schema_disables_auto_strict; ::test_explicit_strict_over_limits_falls_back and ::test_strict_tools_count_under_tool_choice_none refuse the request before sending it, so they record nothing on either side
$ref inlining and siblings (_handle), across providerstest_ref_sibling_wire_contract.py, test_azure_grok_schema.py
function_schema, docstrings, enum member docstringstest_openai.py::test_multiple_agent_tool_calls, test_google.py::test_google_model_structured_output, ::test_google_model_retry, ::test_google_model_iter_stream, and the OpenAI, Google and Anthropic *_enum_member_docstrings_reach_the_wire tests
Choicestest_choices.py::test_choices_round_trips_on_the_wire, test_typesafe.py::test_a_choices_route_is_described_by_what_the_set_says_about_itself

format_as_xml, build_schema_types, group_by_temporal, wait_passing_on_cancellation and the code-mode signature renderer send nothing of their own over a provider wire here; their proof is the existing tests.

What changes for existing users

Nothing.

PR decisions

2026-11-04 · R5 scope re-scored on main ce4c9ae9e · iter -

  • Decision: All 21 listed functions in scope at their listed scores; no logic moved out of them since the inventory commit d44704ec7 (four main commits touched these files: #12377 added the inlining bound around _handle's callees, the rest are small edits)
  • 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: b97cac1c-8114-43be-9789-6d0931fad1be

2026-11-04 · proof W via local wire_trace · iter -

  • Decision: #12416 (refactor_capture wire kind) is still open, so W uses the local plugin/wire_trace.py + byte-identity/compare_norm2.py
  • Why: dispatch: use the committed wire kind only if #12416 has merged when W runs
  • Source: https://github.com/pydantic/pydantic-ai/pull/12416
  • Session: b97cac1c-8114-43be-9789-6d0931fad1be

2026-11-04 · proof W via committed tests/refactor_capture.py · iter -

  • Decision: #12416 merged (4d369ad9e); branch fast-forwarded onto it; W uses 'uv run python -m tests.refactor_capture ' (wire kind), not the local wire_trace.py
  • Why: manager dispatch 2026-11-04T02:57Z: use the committed capture once #12416 merges
  • Source: https://github.com/pydantic/pydantic-ai/pull/12416
  • Session: b97cac1c-8114-43be-9789-6d0931fad1be
  • Supersedes: proof W via local wire_trace

2026-11-04 · function_schema parameter state on a context dataclass · iter -

  • Decision: function_schema's per-parameter loop state (fields, positional fields, *args/**kwargs schema, missing descriptions, decorators) lives on a private kw-only _ToolParameters dataclass with add/_add_field, sharing function_schema's errors list, instead of a module function threading 8 arguments
  • Why: agent_docs/complexity.md: keep request-wide state on a data-only context; R4 did the same for _sanitize_messages
  • Source: https://github.com/pydantic/pydantic-ai/issues/10983
  • Session: b97cac1c-8114-43be-9789-6d0931fad1be

2026-11-04 · _typeshed.DataclassInstance for format_prompt's dataclass handlers · iter -

  • Decision: format_prompt.py imports DataclassInstance from _typeshed under TYPE_CHECKING to type _ToXml._dataclass_to_xml/_parse_dataclass; first _typeshed import in the repo
  • Why: it is the type is_dataclass narrows to and asdict/fields require; the alternative is Any, which the repo rules forbid
  • Source: https://github.com/pydantic/pydantic-ai/issues/10983
  • Session: b97cac1c-8114-43be-9789-6d0931fad1be

2026-11-04 · match with case _: pass in _json_schema._handle and _replace_type_ref · iter -

  • Decision: if/elif chains over a node's type became match with a trailing 'case _: pass', as function_signature.py and _file_input.py already do
  • Why: pyright strict requires the match to be exhaustive; match costs 1 where each elif costs 1
  • Source: https://github.com/pydantic/pydantic-ai/issues/10983
  • Session: b97cac1c-8114-43be-9789-6d0931fad1be

2026-11-04 · proof W result at 3a13a0de6 · iter -

  • Decision: tests.refactor_capture 4d369ad9e vs working tree over 30 selections (local-notes/r5/w-nodes.txt): 82 nodes, 177 records each side, 164 requests (OpenAI Chat/Responses incl. Azure and MockOpenAI, Anthropic, Gemini, OpenRouter, Bedrock, 5 Gemini Live WebSocket frames), 0 differing, 0 one-sided
  • Why: Gemini Live is the only wire path of GoogleOpenAPISchemaTransformer/_drop_unsupported_schema_keywords/google_realtime_model_profile and the capture records HTTP only, so a local -p ws_tap plugin (outside the repo) recorded ReplayWebSocket.send frames as request records in the same capture dirs
  • Source: https://github.com/pydantic/pydantic-ai/pull/12416
  • Session: b97cac1c-8114-43be-9789-6d0931fad1be

2026-11-04 · S run order · iter -

  • Decision: Final S pass over 39 test files on 3a13a0de6 passed once files were grouped by directory with test_capability_spec.py before test_toolsets.py; the first ordering failed 7 nodes on two pre-existing order dependencies untouched by this branch (pytest 9.1.1 conftest fixture binding when top-level files interleave tests/models/ files; blockbuster poisoning importlib.metadata in test_toolsets::test_context_manager)
  • Why: dispatch: S proof = existing tests pass unchanged; the failures are command-order artifacts, reported to the manager separately
  • Source: https://github.com/pydantic/pydantic-ai/issues/10983
  • Session: b97cac1c-8114-43be-9789-6d0931fad1be

2026-11-04 · pre-push review 1 of 3 at 3a13a0de6e237f55867f2e977bb230cf926582c8 · iter -

2026-11-04 · pre-push review 1 of 3 at 3a13a0de6e237f55867f2e977bb230cf926582c8 · iter -

  • Decision: remediated in da67143ef: (1) _ToolParameters and _TemporalGroups made data-only (_FunctionSchemaContext, _TemporalGroupsContext) with module functions _add_parameter/_add_field and _ungrouped_items/_debounced_groups/_wait_for_next_item, matching R4's data-only contexts and models/AGENTS.md; context variable named schema_context since ctx means RunContext in that module; (2) _replace_type_ref renamed _replace_in_expr (one letter from _replace_type_refs); (3) a 124-column docstring wrapped, and a 143-column chained assignment split into two (same dict object, same insertion order)
  • Why: tree 82553eb23281c0ed3bc69097fd8b2774939f9b44; scope 4d369ad9e..3a13a0de6 full branch; reviewer found no behavior difference
  • Source: https://github.com/pydantic/pydantic-ai/tree/schemas-complexity
  • Session: b97cac1c-8114-43be-9789-6d0931fad1be

2026-11-04 · context dataclasses are data-only · iter -

  • Decision: function_schema's loop state is the data-only _FunctionSchemaContext filled by module functions _add_parameter/_add_field; group_by_temporal's state is the data-only _TemporalGroupsContext read by _ungrouped_items/_debounced_groups/_wait_for_next_item
  • Why: pre-push review 1: a private context class holds data only (models/AGENTS.md; R4's _ResolveInstructionsContext/_SanitizeMessagesContext on main)
  • Source: https://github.com/pydantic/pydantic-ai/tree/schemas-complexity
  • Session: b97cac1c-8114-43be-9789-6d0931fad1be
  • Supersedes: function_schema parameter state on a context dataclass

2026-11-04 · pre-push review 2 of 3 at da67143ef56d9a0d3b1765b4be96d4d54e862f6c · iter -

2026-11-04 · proof W re-run at da67143ef · iter -

  • Decision: Same 30 selections after review-1 fixes: 82 nodes, 177 records each side, 164 requests, 0 differing, 0 one-sided
  • Why: review 1's remediation changed function_schema and group_by_temporal structure; W re-run on the new head
  • Source: https://github.com/pydantic/pydantic-ai/pull/12416
  • Session: b97cac1c-8114-43be-9789-6d0931fad1be

2026-11-04 · pre-push review 2 of 3 at da67143ef56d9a0d3b1765b4be96d4d54e862f6c · iter -

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.

Summary by cubic

Brings 21 schema, signature, and prompt-formatting functions under the cognitive complexity limit of 15, cutting their combined score from 612 to 200 with no behavior change. Part of #10983, which stays open for the remaining modules.

Refactors

  • Split tree-walks into one handler per node kind, hoisted nested closures to module functions, and moved parameter state onto data-only context classes.
  • All new functions and classes are private; Choices keeps its public signature, overloads, and docstring.

Verification

  • Existing tests and inline snapshots pass unchanged; no test file, snapshot, or cassette changes.
  • Provider requests are byte-identical to main across 164 captured requests, including OpenAI strict schemas, Google, and Anthropic schema limits.
  • scripts/check_complexity.py passes with every function scoring 15 or under.