Bring 21 `pydantic_ai` schema, signature and prompt-formatting 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. 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$refinlining 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_temporalbecame module functions over a private data-only_TemporalGroupsContext, which holds the pull its cleanup cancels; those of_replace_type_refsandbuild_schema_typesbecame 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_parameterand_add_fieldnext 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_ofandgoogle_realtime_model_profile.wait_passing_on_cancellationonly 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,
mainagainst this branch, withtests/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.pypasses. 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: C901markersRUF100flagged are gone.
Before and after scores: 612 → 200
| Function | File | Before | After |
|---|---|---|---|
OpenAIJsonSchemaTransformer.transform | profiles/openai.py | 69 | 11 |
function_schema | _function_schema.py | 56 | 14 |
_ToXml._parse_data_structures | format_prompt.py | 50 | 11 |
group_by_temporal | _utils.py | 31 | 0 |
_type_to_expr | function_signature.py | 31 | 5 |
build_schema_types | _spec.py | 30 | 11 |
Choices | output.py | 30 | 10 |
merge_json_schema_defs | _utils.py | 28 | 15 |
_drop_unsupported_schema_keywords | profiles/google.py | 28 | 2 |
GoogleOpenAPISchemaTransformer.transform | profiles/google.py | 28 | 5 |
JsonSchemaTransformer._handle | _json_schema.py | 27 | 14 |
_update_mapped_json_schema_refs | _utils.py | 27 | 5 |
_replace_type_refs | function_signature.py | 27 | 4 |
_schema_to_type_expr | function_signature.py | 23 | 9 |
exceeded_limit | models/_anthropic_schema_limits.py | 21 | 5 |
_flatten_all_of | profiles/google.py | 21 | 14 |
doc_descriptions | _griffe.py | 18 | 15 |
_ToXml._to_xml | format_prompt.py | 18 | 12 |
ScopedTask.wait_passing_on_cancellation | _utils.py | 17 | 11 |
enum_member_docstrings | _utils.py | 16 | 14 |
google_realtime_model_profile | profiles/google.py | 16 | 13 |
| Total | 612 | 200 |
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 code | Test 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 declarations | test_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 limits | anthropic/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 providers | test_ref_sibling_wire_contract.py, test_azure_grok_schema.py |
function_schema, docstrings, enum member docstrings | test_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 |
Choices | test_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 -
- Decision: reserved; outcome pending
- Why: tree 82553eb23281c0ed3bc69097fd8b2774939f9b44; scope 4d369ad9e353fd7b61de5c3dcd39dfec72d4ed4a..3a13a0de6e237f55867f2e977bb230cf926582c8 (full branch); policy base 4d369ad9e353fd7b61de5c3dcd39dfec72d4ed4a; first review; light tier (haiku) per Model tiers
- Source: https://github.com/pydantic/pydantic-ai/tree/schemas-complexity
- Session: b97cac1c-8114-43be-9789-6d0931fad1be
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 -
- Decision: reserved; outcome pending
- Why: tree 7667d40d07fa0282d4c76f4ff7a40d683c29a6c0; follow-up scope 3a13a0de6..da67143ef56d9a0d3b1765b4be96d4d54e862f6c (review 1's fixes), prior findings to verify, full branch diff as context; policy base 4d369ad9e; light tier (haiku)
- Source: https://github.com/pydantic/pydantic-ai/tree/schemas-complexity
- Session: b97cac1c-8114-43be-9789-6d0931fad1be
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 -
- Decision: no findings (current at da67143ef); review 1's three findings confirmed fixed
- Why: tree 7667d40d07fa0282d4c76f4ff7a40d683c29a6c0; follow-up scope 3a13a0de6..da67143ef
- Source: https://github.com/pydantic/pydantic-ai/tree/schemas-complexity
- Session: b97cac1c-8114-43be-9789-6d0931fad1be
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;
Choiceskeeps 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
mainacross 164 captured requests, including OpenAI strict schemas, Google, and Anthropic schema limits. scripts/check_complexity.pypasses with every function scoring 15 or under.