[complexity] Bring 14 Bedrock adapter functions under the cognitive complexity limit of 15

Merged
DS
1mo ago
+973-828

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. 14 functions in the Bedrock adapter scored over that on main, 691 points in total: its message, user-prompt and file mappers, its stream, its response parser, its thinking, top_k and tool_choice translators, its error mapper, its request builder and its cache-point helpers. This PR brings each to 15 or under with no change in behavior. It is part of #10983, which it does not close.

Each function took the fix agent_docs/complexity.md names for its shape, laid out as agent_docs/provider-adapters.md asks:

  • Part-ladder: _map_messages builds a data-only _MapMessagesContext and dispatches each message to _map_model_request or _map_model_response. The response dispatch is a match over parts ending in assert_never, with _map_thinking_part, _map_native_tool_call and _map_native_tool_return. The request dispatch keeps its isinstance chain because _UnpreparedPart is a union alias, as in #12764. Tool returns map in _map_tool_return, _map_tool_return_content and _map_tool_return_file. The passes after the loop move to _merge_consecutive_user_messages, _add_instruction_cache_points, _add_message_cache_points and _check_citations_tool_choice, and the nested flush_deferred_media becomes a module function.
  • User prompt and files: _map_user_prompt matches over content. Its UploadedFile arm and the tool-return one share _map_uploaded_file, and its CachePoint arm is _map_cache_point.
  • Stream: _get_event_iterator forwards a sync _map_chunk once. Content block start, delta and stop are _map_content_block_* methods, reasoning deltas are _map_reasoning_delta, and the tool ids, native tool returns and citations kept across events move to field(init=False) fields.
  • Response: _process_response maps each content block kind in a _map_*_block method.
  • Vocabulary translators: _tool_choice_declarations matches on the resolved choice. The thinking variants move to _add_thinking_fields, a match ending in assert_never, and top_k to _add_top_k_field.
  • Error mapper: the ClientError arm moves to _map_client_error, as _map_status_error does in models/openai.py.
  • Single-use steps, as the guide allows: _add_settings_params, _check_output_mode, _unified_thinking_type, _openai_responses_reasoning_effort, _tool_result_cannot_share_turn. _insert_cache_point_before_trailing_documents, _add_anthropic_thinking_fields, _limit_cache_points and _map_file_to_content_block take guard clauses instead.

No # complexipy: ignore is added, and the three # noqa: C901 markers go. Open PRs #4622, #6570, #7919, #9774, #10368, #11054, #11084, #11131, #11491 and #11781 edit some of these functions and rebase on this one.

This PR changes only bedrock.py, with no test-file change. Bedrock requests go through botocore, which tests/refactor_capture.py doesn't record, so the request proof below ran with a hook on botocore's Endpoint.make_request applied locally. That hook lands in a separate tooling PR.

New public surface

None. Every new function, method and field is private.

Verification

  • Existing tests and inline snapshots pass unchanged over the 39 test files that reach bedrock.py (listed below). No test file, snapshot or cassette changes.
  • Requests and stream events are identical, main against this branch, with tests/refactor_capture.py and the botocore hook applied locally, over 350 tests: 1,198 records on each side, 827 requests, and 151 tests with Bedrock streams carrying 7,392 events. The two differing tests differ between two runs of the same commit too (details below).
  • scripts/check_complexity.py passes. Every function in bedrock.py scores 15 or under, and the 32 new private functions and methods score 1 to 13.

What changes for existing users

Nothing.

Test files, capture nodes and results

Existing tests. uv run pytest -p no:randomly <files> over tests/models/anthropic/test_carried_thinking.py, tests/models/bedrock/test_cache.py, tests/models/bedrock/test_contains.py, tests/models/bedrock/test_native_output.py, tests/models/bedrock/test_stream_parity.py, tests/models/bedrock/test_strict_schema_limits.py, tests/models/bedrock/test_strict_tool_calls.py, tests/models/test_bedrock_thread_cancellation.py, tests/models/test_bedrock.py, tests/models/test_citations.py, tests/models/test_model_names.py, tests/models/test_model_settings_support.py, tests/models/test_model.py, tests/models/test_multimodal_tool_returns.py, tests/models/test_prompt_cache_retention.py, tests/models/test_request_scoped_system_prompts.py, tests/models/test_system_voice_fallback.py, tests/models/test_tool_choice_matrix.py, tests/models/test_tool_choice_unit.py, tests/models/test_unattributed_compaction.py, tests/providers/test_bedrock_mantle.py, tests/providers/test_bedrock.py, tests/providers/test_gateway_cost.py, tests/providers/test_gateway.py, tests/test_cache_setting.py, tests/test_canonical_system_live.py, tests/test_canonical_system.py, tests/test_embeddings.py, tests/test_exceptions.py, tests/test_gateway_model_name_suggestions.py, tests/test_history_properties.py, tests/test_missing_usage.py, tests/test_model_name_suggestions.py, tests/test_retry_feedback.py, tests/test_streaming_errors.py, tests/test_thinking_placement.py, tests/test_thinking.py, tests/test_tool_failed_wire.py, tests/test_unreadable_tool_files.py: 2,556 passed, 90 skipped, 18 xfailed, at d8b037cbae. The later commit 5a0f5a1880 changes only _add_thinking_fields's fallback arm, a docstring and a default factory.

Requests and stream events. uv run python -m tests.refactor_capture d2992bc461 -p no:randomly -k bedrock <the same files>, at this PR's head 84e5876eee, with the botocore request hook (reverted here; it lands in the tooling PR) applied locally. An earlier run at 5a0f5a1880 gave the same result, plus the third noise node below. -k bedrock selects every test in the Bedrock test files and the Bedrock cases of the cross-provider ones, so it covers every Bedrock stream test.

Result: 350 nodes and 1,198 records on each side; only in main 0, only in branch 0, differing 2. Stream module pydantic_ai.models.bedrock reached by 151 nodes with 7,392 events, none differing. Requests reached 82 targets, 56 of them Bedrock Converse, ConverseStream and CountTokens endpoints across Nova, Claude, gpt-oss, GPT-5.6 and GPT-6, Qwen, Grok, Llama, Mistral, Writer, DeepSeek and other families.

The differing nodes are capture noise, not this change:

  • tests/models/test_model_settings_support.py::test_max_retries_keeps_the_bedrock_client_aws_profile and test_max_retries_sets_how_many_attempts_the_sdk_makes[AnthropicModel[bedrock]] differ only in the x-amz-date header that AnthropicModel's Bedrock client signs over httpx, outside bedrock.py. A capture of this branch against itself over the same selection gives the same two differences.
  • In the run at 5a0f5a1880 only, tests/models/test_bedrock.py::test_bedrock_streaming_error also differed, only in the key order of the replayed response's HTTPHeaders inside the error it records. This branch has produced different orders in different runs.

Nodes that reach each changed request mapper, picked from the request bodies they recorded, all identical on both sides:

  • _map_model_request, _map_tool_return: test_bedrock.py::test_bedrock_model_retry, test_bedrock.py::test_bedrock_moonshotai_tool_call; without status: test_bedrock.py::test_bedrock_writer_tool_result_followed_by_text_accepted
  • _map_tool_return_file: test_multimodal_tool_returns.py::test_mixed_content_ordering[bedrock_claude], test_bedrock.py::test_bedrock_mistral_tool_return_image_accepted
  • _merge_consecutive_user_messages: test_bedrock.py::test_bedrock_llama_tool_result_followed_by_text_accepted, test_bedrock.py::test_bedrock_mistral_two_tool_returns_images_accepted
  • leading user turn: test_bedrock.py::test_bedrock_model_with_instructions_only[nova-micro], test_bedrock.py::test_bedrock_model_instructions_only_then_message_history[nova-micro]
  • _map_model_response, _map_thinking_part: test_bedrock.py::test_bedrock_model_thinking_part_anthropic, test_bedrock.py::test_bedrock_model_thinking_part_redacted; carried thinking: test_bedrock.py::test_bedrock_model_structured_output
  • _map_native_tool_call, _map_native_tool_return: test_bedrock.py::test_bedrock_model_with_code_execution_tool, test_bedrock.py::test_bedrock_model_code_execution_tool_sandbox_timeout
  • _add_instruction_cache_points, _add_message_cache_points, _limit_cache_points: test_bedrock.py::test_bedrock_cache_write_and_read, test_bedrock.py::test_unified_cache_reads_history_after_wide_turn_real_api
  • _map_cache_point, _insert_cache_point_before_trailing_documents: test_bedrock.py::test_bedrock_cache_messages_trailing_text_document_after_cache_point, test_bedrock.py::test_bedrock_cache_write_and_read
  • _check_citations_tool_choice path, cited documents: test_citations.py::test_document_citations[bedrock-pdf], test_citations.py::test_bedrock_tool_return_document_citations
  • _map_user_prompt, _map_file_to_content_block: test_bedrock.py::test_image_as_binary_content_input, test_bedrock.py::test_video_url_input, test_bedrock.py::test_document_url_input
  • _map_uploaded_file: test_multimodal_tool_returns.py::test_multimodal_tool_return_matrix[tool_return_content-uploaded_file-image-bedrock_claude]
  • _build_additional_model_request_fields, _add_thinking_fields, _add_anthropic_thinking_fields: test_bedrock.py::test_bedrock_anthropic_unified_max_effort, test_bedrock.py::test_bedrock_model_thinking_part_anthropic_adaptive_effort, test_bedrock.py::test_bedrock_thinking_high_openai_variant, test_bedrock.py::test_bedrock_thinking_false_openai_responses_variant_always_on, test_bedrock.py::test_bedrock_thinking_high_qwen_variant; top_k: test_bedrock.py::test_bedrock_top_k_nova_variant, test_bedrock.py::test_bedrock_top_k_anthropic_variant; native tool_choice none: test_bedrock.py::test_bedrock_tool_choice_none_after_tool_call_claude
  • _tool_choice_declarations, _effective_thinking_type: test_bedrock.py::test_bedrock_specific_tool_choice_with_adaptive_thinking_runs, test_tool_choice_matrix.py::test_tool_choice_matrix[list_single-bedrock], test_bedrock.py::test_bedrock_model_structured_output
  • _messages_create, _add_settings_params: test_bedrock.py::test_bedrock_model_other_parameters, test_bedrock.py::test_bedrock_model_service_tier
  • prepare_request, _check_output_mode: test_bedrock.py::test_bedrock_zai_native_output, bedrock/test_native_output.py::test_bedrock_native_output_qwen
  • count tokens: test_bedrock.py::test_bedrock_count_tokens_tool_config

Paths are under tests/models/. No Bedrock test sends a json-format tool result or a user-prompt UploadedFile over botocore; their arms are reached by the existing tests that call the mappers directly, and _map_uploaded_file by the tool-return node above.

Before and after scores: 691 → 151

All in pydantic_ai_slim/pydantic_ai/models/bedrock.py, scored with complexipy on main at d2992bc461 and on this branch.

Functionmainafter
BedrockConverseModel._map_messages28214
BedrockStreamedResponse._get_event_iterator924
BedrockConverseModel._map_user_prompt5412
BedrockConverseModel._process_response4013
BedrockConverseModel._build_additional_model_request_fields346
BedrockConverseModel._tool_choice_declarations289
BedrockConverseModel._messages_create2612
_effective_thinking_type2415
_map_api_errors224
_add_anthropic_thinking_fields1913
BedrockConverseModel._map_file_to_content_block1914
_insert_cache_point_before_trailing_documents1811
BedrockConverseModel._limit_cache_points1714
BedrockConverseModel.prepare_request1610
Total691151
PR decisions

2026-11-07 · R11 scope re-scored on main 7e72d571ce · iter -

  • Decision: 14 functions in scope, same set and scores as the plan (691 points); no other bedrock.py function over 15
  • Why: manager dispatch: re-score on current main first
  • Source: https://github.com/pydantic/pydantic-ai/tree/7e72d571ce
  • Session: 8b577650-4849-4dc3-9cc0-36b9318d5272

2026-11-07 · implement directly, no plan-only PR · iter -

  • Decision: initialize-worktree complexity question skipped: implement + PR
  • Why: manager dispatch fixes scope, shapes and decisions (D1, D2, D6); a [relaying for david] session cannot take AskUserQuestion
  • Source: https://github.com/pydantic/pydantic-ai/issues/10983
  • Session: 8b577650-4849-4dc3-9cc0-36b9318d5272

2026-11-07 · Proof W hook: botocore Endpoint.make_request · iter -

  • Decision: Proof W records Bedrock requests by wrapping botocore.endpoint.Endpoint.make_request in tests/refactor_capture.py, applied locally uncommitted for R11's proofs; where it lands is still open (manager asking David)
  • Why: Managing session's call, on this session's probe: it carries the extra headers and the body bytes, without SigV4 noise
  • Source: https://github.com/pydantic/pydantic-ai/issues/10983
  • Session: 8b577650-4849-4dc3-9cc0-36b9318d5272

2026-11-07 · Proof W tooling lands inside R11 as its own commit · iter -

  • Decision: The Endpoint.make_request hook in tests/refactor_capture.py (plus the matching tests/AGENTS.md capture-section update) is committed inside R11, as a commit separate from the refactor commits; it is the one test-file change R11 allows
  • Why: David's decision, relayed by the managing session
  • Source: https://github.com/pydantic/pydantic-ai/issues/10983
  • Session: 8b577650-4849-4dc3-9cc0-36b9318d5272
  • Supersedes: Proof W hook: botocore Endpoint.make_request (landing place only)

2026-11-07 · pre-push review 1 of 3 at d8b037cbae78e6315b47f8a6dfe5598ce0be66f3 · iter -

2026-11-07 · pre-push review 1 of 3 at d8b037cbae78e6315b47f8a6dfe5598ce0be66f3 · iter -

  • Decision: remediated: _add_thinking_fields falls through for an unknown or missing variant as main does (case _ no-op, not assert_never); _check_output_mode docstring names both guards; _citations default_factory is dict[int, list['CitationsDeltaTypeDef']] like its sibling fields (string forward ref, the TypeDef is TYPE_CHECKING-only)
  • Why: reviewed tree 3bf1772da17b6038561d326b7801afe62614be4a; scope d2992bc461..d8b037cbae (full branch); haiku, read-only tools, no fan-out, detached policy-base worktree at 58b007e6c3; first launch failed on CLI args and second on the usage limit before reviewing, neither reached a verdict
  • Source: https://github.com/pydantic/pydantic-ai/tree/bedrock-complexity
  • Session: 8b577650-4849-4dc3-9cc0-36b9318d5272
  • Supersedes: pre-push review 1 of 3 at d8b037cbae78e6315b47f8a6dfe5598ce0be66f3 (reserved)

2026-11-07 · response-part dispatch ends in assert_never · iter -

  • Decision: _map_model_response matches every ModelResponsePart and ends in case _: assert_never(part), where main ended its isinstance chain with assert isinstance(item, ToolCallPart)
  • Why: this session's call: models/AGENTS.md asks for exhaustive matching with assert_never; both raise AssertionError for an object outside the part union, only the message differs; the part union is the type of ModelResponse.parts, unlike the profile-supplied thinking variant
  • Source: https://github.com/pydantic/pydantic-ai/tree/bedrock-complexity
  • Session: 8b577650-4849-4dc3-9cc0-36b9318d5272

2026-11-07 · pre-push review 2 of 3 at 5a0f5a1880576d0d9a9a62cbdf978daad20acd39 · iter -

2026-11-07 · _add_thinking_fields falls through for an unknown variant · iter -

  • Decision: match on bedrock_thinking_variant ends in case _: pass (no fields, as on main), not case _: assert_never(variant)
  • Why: this session's call: the dispatch requires behavior unchanged, and the variant comes from a profile a user can set through profile=, where main silently adds no thinking fields; cost: a Literal value added later without an arm is not caught by pyright; a maintainer may prefer assert_never
  • Source: https://github.com/pydantic/pydantic-ai/tree/bedrock-complexity
  • Session: 8b577650-4849-4dc3-9cc0-36b9318d5272

2026-11-07 · pre-push review 2 of 3 at 5a0f5a1880576d0d9a9a62cbdf978daad20acd39 · iter -

2026-11-07 · thinking-variant fallback kept: case _: pass · iter -

  • Decision: _add_thinking_fields keeps case _: pass for an unknown or missing bedrock_thinking_variant (no fields, as on main), not assert_never
  • Why: the managing session's call: R11's hard constraint is behavior unchanged, and a user can set the variant through profile=; cost as stated in the entry it supersedes
  • Source: https://github.com/pydantic/pydantic-ai/pull/12816
  • Session: 8b577650-4849-4dc3-9cc0-36b9318d5272
  • Supersedes: _add_thinking_fields falls through for an unknown variant

2026-11-07 · tooling placement re-opened; douwebot and pushes on hold · iter -

  • Decision: where the botocore capture commit lands is re-asked of David; until the managing session answers: apply no douwebot label and push nothing; CI may run on the current head; the capture-noise fixes (x-amz-date normalization, HTTPHeaders order) wait for the same answer
  • Why: the managing session's call: its question to David cited only the original D7, not the 2026-11-03 amendments that gave each capture its own PR (David picked 'Own PR, parallel' then)
  • Source: https://github.com/pydantic/pydantic-ai/pull/12816
  • Session: 8b577650-4849-4dc3-9cc0-36b9318d5272

2026-11-07 · capture hook split out of R11 · iter -

  • Decision: revert b31e36a2f7 (botocore capture hook) with a new commit; R11 changes only bedrock.py; the hook lands in a separate tooling PR built by another worker from b31e36a2f7 plus the two capture-noise fixes; Proof W ran with the hook applied locally
  • Why: David's decision, relayed by the managing session, matching his amended D7 ('Own PR, parallel'); the 'inside R11' decision rested on a citation of the original D7 only
  • Source: https://github.com/pydantic/pydantic-ai/pull/12816
  • Session: 8b577650-4849-4dc3-9cc0-36b9318d5272
  • Supersedes: Proof W tooling lands inside R11 as its own commit

2026-11-07 · pre-push review 3 of 3 at 84e5876eee4a9a17e503d6f2c9db3dc4e6edfc77 · iter -

2026-11-07 · pre-push review 3 of 3 at 84e5876eee4a9a17e503d6f2c9db3dc4e6edfc77 · iter -

2026-11-07 · no additional review surface; enqueue after the metadata check · iter -

  • Decision: no second opinion beyond the required CI and douwebot reviews; #12816 is enqueued after the final metadata check, by the managing session (this worker never enqueues)
  • Why: David's call, relayed by the managing session; options framed by this session: none (recommended), pydanty:review-branch, pydanty:review-lite, douwebot again, local pre-push review
  • Source: https://github.com/pydantic/pydantic-ai/pull/12816
  • Session: 8b577650-4849-4dc3-9cc0-36b9318d5272

2026-11-07 · enqueued at 2026-11-07T20:47:54Z · iter -

  • Decision: #12816 added to the merge queue at head 84e5876eee by the managing session; this worker stays in monitor mode and never enqueues or re-enqueues
  • Why: David's call, relayed by the managing session, after the final metadata check
  • Source: https://github.com/pydantic/pydantic-ai/pull/12816
  • Session: 8b577650-4849-4dc3-9cc0-36b9318d5272

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

Refactors 14 Bedrock adapter functions in bedrock.py to bring each under the 15-point cognitive complexity limit, with no user-visible behavior change.

Refactor

  • Maps messages through a data-only context with one method per message kind and part type; the context's wire lists now use default factories, so the constructor call passes only the facts each part is mapped against.
  • Moves thinking, top_k, and tool_choice translation into match statements with private helper methods.
  • Extracts error mapping, settings building, and cache-point handling into private functions.
  • Adds no public surface and no complexipy ignores; all existing tests and inline snapshots pass unchanged.