Gate cognitive complexity in pre-commit and CI with `scripts/check_complexity.py`

Merged
DS
1mo ago
+1356-7

This pull request was posted by Claude Code using claude-opus-5-5 on behalf of David.

Why

Ruff's C901 counts branches, not nesting, so most production functions over cognitive complexity 15 pass it, and nothing stops a change from growing them. This adds the gate, part of #10983. The refactors come in later PRs.

scripts/check_complexity.py scores each changed function with complexipy and compares it with its base. A change fails when it adds a function over 15, takes one over 15, or grows one already over 15. Existing debt passes until a change makes it worse. Per #10983's replay of the last 1,000 merged PRs, the gate would have failed 37% of those touching production code. Renames and moves are paired, so they pass. During a merge, the hook reports a function only when it is worse than in both parents. # complexipy: ignore (<reason>) exempts a function; CI fails an ignore without a reason and annotates each new one.

New public surface

None. Contributor tooling only: the script, a pre-commit hook complexity, a CI check cognitive complexity, and agent_docs/complexity.md.

What a contributor sees

Before, 4fc34a0c4b, a merged PR, passed pre-commit and CI with no complexity report. Replayed through the gate:

pydantic_ai_slim/pydantic_ai/agent/__init__.py:4443: _PreparedAgentRun::open 31 -> 35: already over the limit, and this change made it worse (agent_docs/complexity.md#existing-debt)
    C003 at line 4512, about -12: move the block into a private method, or a function next to its caller (agent_docs/complexity.md#extract-a-method)
    C003 at line 4470, about -9: move the block into a private method, or a function next to its caller (agent_docs/complexity.md#extract-a-method)
    C005 at line 4459, about -2: name the compound condition as a predicate method (agent_docs/complexity.md#extract-a-method)
    pick the case whose shape matches the function, and apply its fix (agent_docs/complexity.md#cases)

Each C0.. line is a complexipy suggestion, pointed at the guide's fix for it. The last line links the guide's cases, which pair each function shape with the fix that fits this repo. In CI each failure is an error annotation on the def line, plus a step-summary table.

Verification

  • scripts/test_check_complexity.py: 100% branch coverage of the script. CI runs them in quality checks.
  • .github/scripts/test_ci_content_classifier.py covers the new job's skip wiring.
  • The check passes on this branch, which touches no production code.
  • The merge handling in 1ca99d90d6 and the complexipy 8.3.0 follow-up and review fixes in 361b318ef4, 7d929af0cb, 07e8d3267c, ad8120ba08, 743ca42415, bf2130ec8c, 887a515f5c and 293ef22099, and the main merges 5ab0a185af and 5be945b819, shipped on their tests and local checks, without another pre-push review.

Pre-commit cost

Median / max wall seconds over 7 runs with complexipy 8.3.0, each scenario staged in a scratch worktree, on an Apple M4 shared with other work (load average 10 to 17). The one-file rows append a small function. The last column includes pre-commit's own start-up, which the "nothing staged" row isolates.

Staged.py filesScriptpre-commit run complexity
one small file (_utils.py)10.12 / 0.340.52 / 0.80
one large file (models/openai.py, 7,561 lines)10.13 / 0.210.61 / 1.03
typical PR 4fc34a0c4b80.15 / 0.280.45 / 1.08
large PR 1b10e6dcdc440.20 / 0.210.53 / 0.66
nothing staged00.09 / 0.100.44 / 0.60

What changes for existing users

Nothing for library users; a contributor change that takes a production function past 15, or grows one already past it, now fails pre-commit and CI.

Deliberate scope choices
  • tests/, examples/, scripts/, clai/ and the scripts, examples and live integration tests under src/ are not gated. Ruff C901 still covers tests/.
  • Ruff C901 stays as it is. Its # noqa: C901 markers stay too.
  • complexipy is pinned to 8.3.0, a release dsfaccini audited. [tool.uv.exclude-newer-package] admits it until it is 7 days old, on 2026-11-03. Other dependencies are not pinned; a complexipy bump is deliberate.
  • complexipy's own --diff, --staged and snapshot modes are not used: each fails a pure rename or move of a function over the limit.
  • No refactor of existing functions here; those are the series PRs in #10983.
PR decisions

2026-10-23 · Gate roots are the five package directories · iter -

  • Decision: [tool.complexipy] paths lists the package dirs of slim, graph, evals, harness and clai2; clai/ and the scripts, examples and integration tests under src/ stay out
  • Why: The gate covers shipped production code; src/ also holds scripts, examples and live integration tests
  • Source: https://github.com/pydantic/pydantic-ai/issues/10983

2026-10-24 · Failure messages link the guide's cases · iter -

2026-10-23 · --head mode for the pre-push reviewer · iter -

  • Decision: Added --base A --head B, which reads both sides from git objects; pre-push-review runs the policy-base script over the candidate's commits
  • Why: The reviewer must not execute candidate content or read the candidate worktree
  • Source: https://github.com/pydantic/pydantic-ai/issues/10983

2026-10-23 · A moved function that grows is judged against its predecessor · iter -

  • Decision: A new function over the limit that pairs with a removed same-name function is classified crossed/worsened against it, not passed or failed as new
  • Why: Calling it new would misname the failure and drop its previous score from the report
  • Source: https://github.com/pydantic/pydantic-ai/issues/10983

2026-10-23 · Script tests run in quality checks · iter -

  • Decision: scripts/test_check_complexity.py runs as its own step in the quality job; the complexity job installs only the lint group
  • Why: The lint-only environment has no pytest; quality already hosts the other script tests
  • Source: https://github.com/pydantic/pydantic-ai/issues/10983

2026-10-23 · pre-push review 1 of 3 at 996e53de86dc1e07f6783d9c5fc65f1fffe7194a · iter -

2026-10-23 · pre-push review 2 of 3 at b84c1083004293a6f59b155852653c2e1b871217 · iter -

2026-10-23 · pre-push review 3 of 3 at bf6d457ec940134220af993cbe0aa4d05a1a535d · iter -

2026-10-23 · Second opinion: pydanty:review-lite · iter -

2026-10-23 · Moves pair by name before renames pair by score · iter 2

  • Decision: _predecessors runs a same-name pass over every new offender, then a same-score pass
  • Why: In one pass, a rename checked first could take the removed function a later move needed, and the move failed as new; reproduced by test_a_move_keeps_its_predecessor_when_a_rename_could_take_it
  • Source: https://github.com/pydantic/pydantic-ai/pull/11117#discussion_r4356031864

2026-10-23 · Ignore audit follows complexipy's decision · iter 2

  • Decision: An ignore is reported when complexipy drops a function in the head that it scored in the base; its line and reason come from the marker in that function's header (line above the decorators through the signature)
  • Why: Pydanty: a body marker ignores nothing, and a marker whose text already existed in the file slipped past a text comparison
  • Source: https://github.com/pydantic/pydantic-ai/pull/11117#issuecomment-6357505884

2026-10-23 · Every ignore in a changed file needs a reason · iter 3

  • Decision: The audit fails a reasonless ignore on any function complexipy drops in a changed file, and annotates only the ignores the change added
  • Why: Stripping the reason from an existing ignore passed, since only newly ignored functions were checked; the gated packages hold no markers, so nothing existing starts failing
  • Source: https://github.com/pydantic/pydantic-ai/pull/11117#discussion_r4356432656

2026-10-23 · Property accessors are keyed apart · iter 4

  • Decision: _functions keys a setter or deleter as <name>.setter/.deleter and drops @overload stubs, reading roles from decorator lines by regex only for repeated names
  • Why: Keeping the highest score per name let a complex getter hide a setter that crossed the limit; an AST parse per file doubled CPU on a 44-file change, the line scan keeps it flat
  • Source: https://github.com/pydantic/pydantic-ai/pull/11117#discussion_r4360663235

2026-10-23 · Pydanty review dismissed, no fresh pass · iter -

2026-10-23 · Complexity helper exception lives in rule 176 · iter -

2026-10-24 · Gate ships blocking before the hotspot series · iter -

2026-10-24 · douwebot review dismissed, no fresh pass · iter -

2026-10-25 · Merge of main skips the complexity hook · iter -

  • Decision: Committed merge 08c26f5174 with SKIP=complexity; the check passes against upstream/main
  • Why: On a merge, pre-commit passes every file that differs between the parents, and --staged compares with HEAD, so it reported six functions main grew before the gate
  • Source: https://github.com/pydantic/pydantic-ai/pull/11117

2026-10-25 · A merge is judged against both parents · iter -

2026-10-25 · Parked until complexipy ships the gate's fixes · iter -

2026-10-27 · adopted PR #11117 at 2026-10-27 · iter -

  • Decision: Branch-context rebuilt in a fresh worktree. Entries above are restored verbatim from the PR body's decisions section, which mirrored the lost log.
  • Why: The parked worktree and its branch-context were removed
  • Source: https://github.com/pydantic/pydantic-ai/pull/11117

2026-10-27 · Resumed on complexipy 8.3.0, pinned exactly · iter -

  • Decision: The lint group pins complexipy==8.3.0 and [tool.uv.exclude-newer-package] sets complexipy = false; a bump is deliberate, after an audit
  • Why: 8.2.0 ships rohaquinlop/complexipy#288 and #289, 8.3.0 ships #291 and #305 (release notes and compare API). David: "it may need an update to pin that exact release, leaving a comment that the pinned version is audited by dsfaccini (bc we generally don't pin)"
  • Source: https://github.com/rohaquinlop/complexipy/releases/tag/8.3.0
  • Supersedes: Parked until complexipy ships the gate's fixes

2026-10-27 · Ignore audit follows complexipy 8.3.0's scopes and marker grammar · iter -

  • Decision: _definitions walks every scope but function bodies, qualifying by class only; _IGNORE requires whole marker words separated by spaces or tabs and skips a marker followed by a [rule] list
  • Why: 8.2.0 scores methods of nested classes and functions under a module-level if/try, so an ignore on one raised KeyError in _ignores; 8.3.0 drops no function for ignoreX or a rule-scoped ignore[...] marker, which the old regex read as ignores. Reproduced by test_an_ignore_in_a_nested_scope_is_reported_at_its_marker and test_a_comment_complexipy_does_not_honor_is_not_read_as_the_ignore, which fail on the pre-fix script
  • Source: https://github.com/rohaquinlop/complexipy/releases/tag/8.2.0

2026-10-27 · No pre-push review for the 8.3.0 resume · iter -

  • Decision: Pushed the merge, the pin and the ignore-audit fix on targeted tests, 100% branch coverage of the script, pyright and the gate's own run, with no fourth pre-push review
  • Why: The pre-push budget is 3 of 3; douwebot and CI still gate the head
  • Source: https://github.com/pydantic/pydantic-ai/pull/11117

2026-10-27 · complexipy's early admit is a dated cutoff, not false · iter -

  • Decision: [tool.uv.exclude-newer-package] sets complexipy = "2026-10-27T05:00:00Z" with a TODO(dsfaccini) to remove it after 2026-11-03 05:00 UTC; the lint group pin stays complexipy==8.3.0
  • Why: douwebot: false is reserved for our own packages; third-party early admits (certifi, pillow, boxlite, prefect) use a dated cutoff, and false would let the next == bump admit a minutes-old release. Verified in the table's header comment and entries; 8.3.0's last file uploaded 2026-10-27T04:59:13Z
  • Source: https://github.com/pydantic/pydantic-ai/pull/11117#discussion_r4392180908
  • Supersedes: Resumed on complexipy 8.3.0, pinned exactly

2026-10-27 · The guide's cited functions are tested against the tree · iter -

  • Decision: Fixed the two exemplars main's anthropic package split left stale, and added test_every_function_the_guide_cites_is_where_it_says, which resolves every symbol in path pair in agent_docs/complexity.md against the gated packages
  • Why: douwebot: an agent following a case would search for a file and symbol that are gone; the other 17 pairs resolve, and the test keeps moves from rotting them
  • Source: https://github.com/pydantic/pydantic-ai/pull/11117#discussion_r4392690356

2026-10-27 · The part-ladder fix points at the provider-adapters rule · iter -

  • Decision: agent_docs/complexity.md's part-ladder case links provider-adapters.md#one-method-per-part-type-one-dispatch-per-message-kind for per-part methods and the data-only context, instead of citing OpenAIChatModel._MapModelResponseContext
  • Why: douwebot: provider-adapters.md names _MapMessagesContext as the data-only precedent and _MapModelResponseContext as the subclassed exception; linking keeps the two guides from drifting
  • Source: https://github.com/pydantic/pydantic-ai/pull/11117#discussion_r4392904128

2026-10-27 · Agent instructions document the complexity check, never run it · iter -

  • Decision: pre-push-review, AGENTS.md 'When to verify' and agent_docs/complexity.md document the check and that pre-commit and CI run it; none tells an agent to run it. The reviewer's allowed-tools entry is gone. --head stays as a script mode with no instructed caller
  • Why: David, verbatim: "I don't wanna tell the agent to run it. it should just run as part of pre-commit. documenting it in the skill is fine so the agent knows it exists but don't create waste compute (by making the agent run something that runs in precommit)"
  • Source: https://github.com/pydantic/pydantic-ai/pull/11117#discussion_r4393555900
  • Supersedes: --head mode for the pre-push reviewer

2026-10-27 · Pydanty review-lite findings refuted or skipped · iter -

  • Decision: No change for review 5673729878: the required workflow-command finding is refuted; the four optional suggestions are skipped
  • Why: The CI complexity job runs on pull_request and executes the PR's own scripts/check_complexity.py, so a PR that names a file '::error…' already controls that job's stdout; uv.lock's diff is complexipy's entries only; _escape, _git and the single-use pipeline helpers pydanty itself rated net-neutral
  • Source: https://github.com/pydantic/pydantic-ai/pull/11117#issuecomment-6451910249

2026-10-27 · No pre-push review for the instruction rewrite · iter -

2026-10-27 · --head mode removed · iter -

  • Decision: Dropped --head, its parse check, the revision branch of _changes and its two tests; _Options.head became staged: bool
  • Why: douwebot: since 743ca4241 nothing calls --head (pre-commit uses --staged, CI --base HEAD^1); deletion-only. Grep of the repo and the toolkit found no --head caller
  • Source: https://github.com/pydantic/pydantic-ai/pull/11117#discussion_r4393969725
  • Supersedes: Agent instructions document the complexity check, never run it

2026-10-27 · Named files stay · iter -

2026-10-27 · No pre-push review for the --head removal · iter -

  • Decision: Pushed the --head removal on the script's tests, branch coverage, pyright and ruff, with no fourth pre-push review
  • Why: The pre-push budget is 3 of 3; douwebot and CI still gate the head
  • Source: https://github.com/pydantic/pydantic-ai/pull/11117

2026-10-27 · Pydanty review-lite dismissed, no fresh pass · iter -

2026-10-27 · Named files removed with the toolkit editor hook · iter -

  • Decision: Dropped the positional [FILE...] filter, _select, _Options.files and test_named_files_limit_the_check; the toolkit's check-complexity.sh PostToolUse hook, its only caller, is deleted in pydantic-ai-tooling b1f7148
  • Why: David chose to remove the hook under his rule against agent-side runs of a check pre-commit already runs; douwebot had flagged the filter as uncalled
  • Source: https://github.com/pydantic/pydantic-ai/pull/11117#discussion_r4394206882
  • Supersedes: Named files stay

2026-10-27 · No pre-push review for the named-files removal · iter -

  • Decision: Pushed the named-files removal on the script's tests, branch coverage, pyright and ruff, with no fourth pre-push review
  • Why: The pre-push budget is 3 of 3; douwebot and CI still gate the head
  • Source: https://github.com/pydantic/pydantic-ai/pull/11117

2026-10-27 · Main merged; uv.lock relocked from main's · iter -

  • Decision: Merged upstream/main ca2e78a9c into c362d01a0 with 'git checkout --theirs uv.lock && uv lock'. complexipy==8.3.0 and its 2026-10-27T05:00:00Z exclude-newer-package cutoff survive. Every locked package version and source matches main except the added complexipy 8.3.0
  • Why: The lock diff against main is wider than complexipy: uv drops main's (mcp-tasks and stackone|dev) marker clauses and the win_amd64 wheels of 13 nvidia/cuda packages. Those clauses name combinations that pyproject's conflicts table declares impossible. #11570 (ipython extra) added them. The relocked markers and wheels match main's lock before #11570 (605f9d9c2). A pure 'uv lock' on main leaves main's lock unchanged
  • Source: https://github.com/pydantic/pydantic-ai/pull/11570
  • Session: e57607ed-275b-46fc-9774-61958d0f45bf

2026-10-27 · No pre-push review for the main merge · iter -

2026-10-27 · No pre-push review for the ignore docstring fix · iter -

2026-10-29 · Main merged at 5ab0a185a; guide citation follows #9348's rename · iter -

  • Decision: Merged upstream/main ad27fbfe2 into 293ef2209. pyproject.toml keeps both exclude-newer-package entries (complexipy, boxd); uv.lock relocked with 'git checkout --theirs uv.lock && uv lock'. agent_docs/complexity.md's precedence-resolution case now cites _resolve_layered_model_settings
  • Why: #9348 renamed _layer_model_settings, so test_every_function_the_guide_cites_is_where_it_says failed on the merged tree. complexipy==8.3.0 and its 2026-10-27T05:00:00Z cutoff survive; every locked package version and source matches main's except the added complexipy 8.3.0, with the same marker and nvidia-wheel delta as merge c362d01a0. The gate passes in --staged and --base upstream/main modes
  • Source: https://github.com/pydantic/pydantic-ai/pull/9348
  • Session: c889342f-81ee-4dbe-ab31-72fca09be75a

2026-10-29 · No pre-push review for the 5ab0a185a merge · iter -

  • Decision: Pushed merge 5ab0a185a on the script's tests, 100% branch coverage, pyright, the gate's own run and pre-commit over the branch diff, with no fourth pre-push review
  • Why: The pre-push budget is 3 of 3. The conflict resolution makes the merge non-exempt; outside the citation fix, the changed lines of git diff ca2e78a9c...293ef2209 equal those of git diff ad27fbfe2...5ab0a185a, uv.lock included. douwebot and CI still gate the head
  • Source: https://github.com/pydantic/pydantic-ai/pull/11117
  • Session: c889342f-81ee-4dbe-ab31-72fca09be75a

2026-10-30 · douwebot:review-agent-config authorized on 5ab0a185a · iter -

2026-10-30 · No push for optional notes on the approved head · iter -

  • Decision: At the merge bar, verbatim: "don't push for a non-blocking or Optional note on an approved head" and "Push only for a blocking finding, a red check, or a conflict. Otherwise reply on the note, or record it for a follow-up."
  • Why: David is merging; each push resets douwebot's approval and costs a full cycle. Relayed by the complexity-program manager
  • Source: https://github.com/pydantic/pydantic-ai/pull/11117
  • Session: c889342f-81ee-4dbe-ab31-72fca09be75a

2026-10-30 · Push rule at the merge bar: douwebot inline notes count · iter -

  • Decision: While the PR is at the merge bar, push only to fix a douwebot inline note (optional included), a blocking finding, a red check or a conflict. Verbatim: "Don't push for anything else while the PR is at the merge bar."
  • Why: 'Gate: clean douwebot approval' fails on any douwebot inline comment on the head: review_gates.py douwebot_approval appends 'Douwebot has inline findings on this head, including resolved/optional ones.' Relayed by the complexity-program manager, citing #10489
  • Source: https://github.com/pydantic/pydantic-ai/pull/10489
  • Session: c889342f-81ee-4dbe-ab31-72fca09be75a
  • Supersedes: No push for optional notes on the approved head

2026-10-30 · Merge bar: no human approval for size L since #11933 · iter -

  • Decision: #11117 is at the merge bar on 5ab0a185a: CI green and a clean douwebot approval. No human approval, no push and no main merge for #11933
  • Why: #11933 (merged 2026-10-30T01:44Z) sets M, L and XL to 'CI green and a clean douwebot approval'; pr-review-gates runs main's review_gates.py via pull_request_target, which no longer publishes the human gate. The 'Gate: human approval' failure on 5ab0a185a dates from 2026-10-29T22:26Z; 'Gate: clean douwebot approval' succeeded at 02:29Z; mergeStateStatus is UNSTABLE, not BLOCKED
  • Source: https://github.com/pydantic/pydantic-ai/pull/11933
  • Session: c889342f-81ee-4dbe-ab31-72fca09be75a

2026-10-30 · Main merged at 5be945b81 for the uv.lock conflict · iter -

  • Decision: Merged upstream/main 72fc98add into 5ab0a185a. Only uv.lock conflicted, resolved with 'git checkout --theirs uv.lock && uv lock'. review_gates.py, test_pr_gates.py and pr-review-gates.yml (#11933, #11940) merged as main's, with no hunk resolved; pyproject.toml took no change
  • Why: #11117 was DIRTY against main. The relocked lock matches main's except the added complexipy 8.3.0 and its 2026-10-27T05:00:00Z cutoff; outside uv.lock the branch diff's changed lines are identical to 5ab0a185a's
  • Source: https://github.com/pydantic/pydantic-ai/pull/11117
  • Session: c889342f-81ee-4dbe-ab31-72fca09be75a

2026-10-30 · No pre-push review for the 5be945b81 merge · iter -

  • Decision: Pushed merge 5be945b81 on the gate's --staged and --base runs, the script's tests at 100% branch coverage, test_pr_gates.py, test_ci_content_classifier.py, pyright and pre-commit over the branch diff, with no fourth pre-push review
  • Why: The pre-push budget is 3 of 3, and the only resolution is the uv.lock relock; douwebot and CI still gate the head
  • Source: https://github.com/pydantic/pydantic-ai/pull/11117
  • Session: c889342f-81ee-4dbe-ab31-72fca09be75a

2026-10-30 · douwebot:review-agent-config authorized on 5be945b81 · iter -

  • Decision: David authorized douwebot:review-agent-config on head 5be945b81938907b067065b8404bf1040e2a38ff only; removed the label left from 5ab0a185a and reapplied it, after CI run 41143422250 went green on that head
  • Why: The diff touches .agents/, AGENTS.md and agent_docs/; bots.yml runs the agent-config review only on a labeled event, so the label still present from 5ab0a185a had to be removed first. Relayed by the complexity-program manager, who checked that the diff against main matches 5ab0a185a's outside uv.lock
  • Source: https://github.com/pydantic/pydantic-ai/pull/11117
  • Session: c889342f-81ee-4dbe-ab31-72fca09be75a

2026-10-30 · douwebot agent-config APPROVE on 5be945b81 · iter -

2026-11-01 · Merge-queue removal on 2026-11-01 classified as a budget flake; no push · iter -

  • Decision: No push for merge-group run 41323933969 (5c8511ea7 = main 133a75127 + #11117). Its one failure, tests/models/anthropic/test_stream_parity.py::test_recorded_streams_match_the_complete_message, took 8.01s against the 8s PYTEST_TEST_BUDGET_SECONDS cost guard. David re-enqueues
  • Why: The test asserts nothing that failed; only the budget did. The run's durations table puts it at 3.3s on main, with eight other tests in the same job at least 2x and 1s slower than on main, so the runner was slow. Main at 133a75127 passed CI (run 41324911391), and main's push run 41311406075 at 3b5dcd0590 failed the same guard on a different test. #11117's diff touches no package or test code, and the test file last changed in #10054
  • Source: https://github.com/pydantic/pydantic-ai/actions/runs/41323933969/job/124899929348
  • Session: c889342f-81ee-4dbe-ab31-72fca09be75a

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.