Bring every `pydantic_evals` function under the cognitive complexity limit of 15

Merged
DS
1mo ago
+442-335

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. 20 functions in pydantic_evals scored over that, 528 points in total. This PR brings each of them to 15 or under, with no change in behavior, as part of #10983. It does not close that issue. After it, no function in pydantic_evals scores over 15, and the one # noqa: C901 in the package is gone.

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

  • Check chains (SpanNode._matches_query): one predicate per section the code already had, as SpanNode._attribute_matches does.
  • Closure-hosted (OnlineEvaluation.wrap_run, ReportCaseAggregate.average): the nested functions became methods or module functions.
  • Dispatch on type (_render_analysis): match, with one function per analysis type.
  • Orchestration (dispatch_evaluators, Dataset.evaluate, _run_and_collect): steps with no cleanup moved out, such as argument checks and grouping. Every try/finally stays in its function.
  • Guard clauses (sample_evaluators, _run_task_and_evaluators, _add_context_span_exporter): an early raise, return or continue replaces an else, with no new function.
  • Reuse: PrecisionRecallEvaluator.evaluate now calls the existing _downsample, and _wrap_sync shares its running-loop check with _dispatch_on_error.

New public surface

None. Every new function and method is private.

Verification

  • Existing tests and inline snapshots pass unchanged. No test file, snapshot or cassette changes.
  • scripts/check_complexity.py passes, and every function in the changed files scores 15 or under, new ones included.
Before and after scores: 528 → 245
FunctionFileBeforeAfter
SpanNode._matches_queryotel/span_tree.py6910
EvaluationReport._metadata_panelreporting/__init__.py5014
OnlineEvaluation.wrap_runonline_capability.py3813
ReportCaseAggregate.averagereporting/__init__.py3211
Contains.evaluateevaluators/common.py2814
dispatch_evaluators_online.py2715
ReportCaseAggregate.average_from_aggregatesreporting/__init__.py2613
Dataset.evaluatedataset.py2414
ConfusionMatrixEvaluator._extractevaluators/report_common.py2312
_render_analysisreporting/__init__.py231
_iter_threshold_countsevaluators/report_common.py2210
ReportCaseRenderer.build_diff_rowreporting/__init__.py2214
EvaluationRenderer.build_diff_tablereporting/__init__.py2213
_github_actions_attributes_ci_provenance.py2114
_run_and_collect_online.py1810
_wrap_synconline.py1813
PrecisionRecallEvaluator.evaluateevaluators/report_common.py1710
sample_evaluators_online.py1614
_run_task_and_evaluatorsdataset.py1615
_add_context_span_exporterotel/_context_in_memory_span_exporter.py1615
Total528245

New private functions score 0–13.

What changes for existing users

Nothing.

PR decisions

2026-11-03 · one function per analysis type in _render_analysis · iter -

  • Decision: match over the analysis union, every case a call to its own render function, including the two small arms
  • Why: agent_docs/complexity.md#dispatch-on-type: keep each case to a call; a new analysis type then adds one flat arm
  • Source: https://github.com/pydantic/pydantic-ai/tree/evals-complexity
  • Session: fe9f6ad2-3181-41a3-a22b-51bce6f0deae

2026-11-03 · _downsample made generic, reused by PrecisionRecallEvaluator · iter -

  • Decision: PrecisionRecallEvaluator.evaluate calls _downsample instead of its inline copy of the same indices
  • Why: identical condition and index formula; dedup removes 7 points without a new helper
  • Source: https://github.com/pydantic/pydantic-ai/tree/evals-complexity
  • Session: fe9f6ad2-3181-41a3-a22b-51bce6f0deae

2026-11-03 · _result_values used only in build_diff_row · iter -

  • Decision: ReportCaseAggregate.average keeps its inline {k: v.value} comprehensions
  • Why: _scores_averages takes list[dict[str, int | float | bool]]; a TypeVar-returned dict[str, int | float] is not assignable under dict invariance, and average already lands at 15
  • Source: https://github.com/pydantic/pydantic-ai/tree/evals-complexity
  • Session: fe9f6ad2-3181-41a3-a22b-51bce6f0deae

2026-11-03 · nested helpers kept where the function already fits · iter -

  • Decision: average_from_aggregates keeps nested _avg_numeric_dicts; _descendants_match and _ancestors_match keep their @cache local functions
  • Why: each host scores 13 or 12 with them; hoisting adds diff for no gate change. D1 bars creating nested defs, not keeping existing ones
  • Source: https://github.com/pydantic/pydantic-ai/tree/evals-complexity
  • Session: fe9f6ad2-3181-41a3-a22b-51bce6f0deae

2026-11-03 · _metadata_diff_lines checks empty sides first · iter -

  • Decision: guards for baseline-empty, then report-empty, then the per-key diff, instead of the original both/report/baseline order
  • Why: outcomes identical because the caller returns None unless one side has metadata; the original order scores 16
  • Source: https://github.com/pydantic/pydantic-ai/tree/evals-complexity
  • Session: fe9f6ad2-3181-41a3-a22b-51bce6f0deae

2026-11-03 · running-loop detection shared by _wrap_sync and _dispatch_on_error · iter -

  • Decision: _dispatch_on_running_loop_or_thread replaces both copies
  • Why: same choice (dispatch_async on a running loop, else a background thread); creating the coroutine first has no side effect
  • Source: https://github.com/pydantic/pydantic-ai/tree/evals-complexity
  • Session: fe9f6ad2-3181-41a3-a22b-51bce6f0deae

2026-11-03 · _result_values also used in ReportCaseAggregate.average · iter -

  • Decision: average projects scores and labels through _result_values, like build_diff_row
  • Why: pyright accepts it (0 errors); the earlier entry's invariance claim was unverified and wrong
  • Source: https://github.com/pydantic/pydantic-ai/tree/evals-complexity
  • Session: fe9f6ad2-3181-41a3-a22b-51bce6f0deae
  • Supersedes: _result_values used only in build_diff_row

2026-11-03 · pre-push review 1 of 3 at 0ade87b6c358d4f96bdf293ec400be3310acfb51 · iter -

2026-11-03 · pre-push review 1 of 3 at 0ade87b6c358d4f96bdf293ec400be3310acfb51 · iter -

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

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

2026-11-03 · final metadata check at ec557db0f · iter -

  • Decision: kept 1 of 4 corrections: moved the #10983 reference from the opening line into Why we make these changes; kept chore, the score-table
    and "None."
  • Why: "Put related but non-closing issues in the explanation instead"; bots.yml classifier defines chore as "CI, refactoring" and release.yml excludes chore from the changelog; the dispatch requires the score table and the per-goal
    rule covers multi-goal bodies; "None." already writes none
  • Source: https://github.com/pydantic/pydantic-ai/pull/12303
  • Session: fe9f6ad2-3181-41a3-a22b-51bce6f0deae

2026-11-03 · additional review surface: pydanty:review-lite · iter -

  • Decision: author applied pydanty:review-lite at 2026-11-03T03:10:37Z; pydanty run df_run_f5c404b89bff49d88953 accepted
  • Why: the author chooses the second opinion; recommendation was none, with review-lite as the fit for a behavior-equivalence check
  • Source: https://github.com/pydantic/pydantic-ai/pull/12303#issuecomment-6594461630
  • Session: fe9f6ad2-3181-41a3-a22b-51bce6f0deae

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

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

2026-11-03 · pydanty review-lite: inline 2 helpers, keep 8 · iter -

  • Decision: inlined _run_case_evaluators (continue guard) and _unsupported_provider_error (else after return dropped); kept findings 2-9
  • Why: D1: helper "allowed when guard clauses, match and arms cannot reach 15"; guards reach 15 for those two hosts, not for hosts scoring 22-69 at base
  • Source: https://github.com/pydantic/pydantic-ai/pull/12303#issuecomment-6606278096
  • Session: fe9f6ad2-3181-41a3-a22b-51bce6f0deae

2026-11-03 · douwebot comment on 7fa29dbd4: drop duplicated comment in _wrap_sync · iter -

2026-11-03 · douwebot comment on 7fa29dbd4: held, PR already queued · iter -

2026-11-03 · merge-queue ejection 15:55Z classified as known flake · iter -

  • Decision: run 41665953998 failure in tests/harness/modal_sandbox/test_modal_sandbox.py::test_agent_with_filesystem_does_not_warn is the leaked-event-loop unraisable flake already on main; not re-enqueued
  • Why: same 3-warning signature (two AF_UNIX sockets plus an unclosed _UnixSelectorEventLoop) failed tests/test_vercel_ai.py on main push run 41509330096 and tests/test_tool_search.py in merge_group run 41489928363; the PR touches only pydantic_evals
  • Source: https://github.com/pydantic/pydantic-ai/actions/runs/41665953998
  • Session: fe9f6ad2-3181-41a3-a22b-51bce6f0deae

2026-11-03 · push held comment fix 9e8c05eca after ejection · iter -

  • Decision: author chose option A: push 9e8c05eca, then CI and a fresh douwebot pass on it before the author re-enqueues
  • Why: the PR left the queue; the merge bar needs douwebot APPROVE with no douwebot comments on the head, and the thread reply committed to landing the fix once the PR left the queue
  • Source: https://github.com/pydantic/pydantic-ai/pull/12303#discussion_r4457077321
  • Session: fe9f6ad2-3181-41a3-a22b-51bce6f0deae
  • Supersedes: douwebot comment on 7fa29dbd4: held, PR already queued

2026-11-03 · final metadata check at 9e8c05eca · iter -

  • Decision: rejected the one correction (remove chore); title, body and labels otherwise current
  • Why: the rule asks only that the category label be aligned with the PR's purpose; bots.yml applied chore, defined there as 'CI, refactoring, dev dependencies, tests-only', and would re-add it on the next synchronize because refactor is not in its CATEGORY_LABELS; release.yml excludes chore from the changelog
  • Source: https://github.com/pydantic/pydantic-ai/pull/12303
  • Session: fe9f6ad2-3181-41a3-a22b-51bce6f0deae

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 the 20 pydantic_evals functions that exceeded the cognitive complexity limit of 15 (528 points total) back under it, with no behavior change. Each function now extracts its complex sections into private methods or module-level helpers, flattens with guard clauses, or reuses existing helpers; the package's only # noqa: C901 is removed. No new public surface and no impact on existing behavior.