DEV Community

Alex Arbatskiy
Alex Arbatskiy

Posted on Edited on AI-assisted

Tests Pass. Your Code Still Gets Harder to Read.

Gate complexity regressions on the code you actually change, not the whole repo.

LLM-assisted coding agents in the IDE and CLI make it easy to ship the next feature fast. The catch is that each follow-up edit tends to add another branch, wrapper, or "just in case" handler. One pass is fine. Five passes on the same function, and you can end up with code that still passes tests but reads like it was designed by a committee.

Cyclomatic complexity won't always tell you that story. Two functions with the same number of paths can feel very different to read:

# Cyclomatic complexity: 4, cognitive complexity: 3
def route_flat(a, b, c):
    if a:
        return "a"
    if b:
        return "b"
    if c:
        return "c"
    return "default"


# Cyclomatic complexity: 4, cognitive complexity: 6
def route_nested(a, b, c):
    if a:
        if b:
            if c:
                return "a+b+c"
    return "default"
Enter fullscreen mode Exit fullscreen mode

An agent "improving" error handling often drifts from the first shape toward the second. Tests still green. Review still looks plausible. Maintenance gets worse anyway.

We already fail CI on formatting, lint, and type errors. Complexity belongs in that same bucket: deterministic, diff-scoped, not a vibes check from the model.

Three numbers worth tracking (Python)

None of these scores mean "good code." They're tripwires for "this change made things harder to follow or harder to test."

Metric What it catches Tool
Cognitive complexity Nesting and flow that's hard to hold in your head complexipy
Cyclomatic complexity Too many independent paths through a function Ruff C901 or Radon
Test coverage Code you can change without a safety net pytest-cov

Track them separately. Cognitive complexity cares about nesting; cyclomatic complexity counts decision points (paths through the function). Coverage answers a different question: whether you have tests at all.

Regression gates beat repo-wide thresholds

Don't start with "every function in the monolith must score under 10." You'll fight legacy debt forever.

Start with: on functions this PR touches, don't let cognitive complexity cross your threshold or creep upward without noticing.

complexipy compares against a git ref or your staged changes and can fail the run when the gate fails:

pip install complexipy
complexipy . --diff main --max-complexity-allowed 15
# before commit (staged vs HEAD):
complexipy . --staged --max-complexity-allowed 15
Enter fullscreen mode Exit fullscreen mode

With --diff, complexipy prints regressions and improvements. The process exits non-zero when a new or regressed function ends up above --max-complexity-allowed (default 15 if you omit the flag). A small bump that stays under the cap still shows up in the report, but it does not fail the gate by itself. For legacy codebases, snapshots record known offenders so CI blocks only new violations and functions that get worse.

For cyclomatic complexity, enable Ruff's C901 rule (not enabled by default):

[tool.ruff.lint]
extend-select = ["C901"]

[tool.ruff.lint.mccabe]
max-complexity = 10
Enter fullscreen mode Exit fullscreen mode

Run ruff check on the same paths you changed. Coverage is coarser: think "don't drop coverage on touched files" rather than chasing a perfect percentage.

New functions have no prior score on main. The same --max-complexity-allowed ceiling covers them, or a snapshot baseline if you're adopting on brownfield code. See CI integration for GitHub Actions and pre-commit.

Don't trust the model. Give it rules

Paste something like this into your agent instructions:

On every modified Python function: run complexipy with --diff or --staged and fix cognitive complexity regressions. Run ruff check with C901 enabled. Do not add nesting or branches "for safety" unless the task requires it. Keep or improve test coverage on changed code; run the relevant tests before you finish.

That turns "write clean code" into commands that exit non-zero.

What this won't catch

Metrics can be gamed. Extracting five one-line helpers might flatten cyclomatic scores while scattering logic. A giant if/elif ladder can look "simple" on paper and still be miserable. That's why cognitive complexity plus coverage deltas matter alongside cyclomatic checks, and why a human still reads the diff.

Sometimes complexity should go up. The point isn't minimal scores. It's stopping silent erosion across repeated AI edits.

Where to start

  1. Add complexipy . --diff main --max-complexity-allowed 15 (tune the number) to CI or pre-commit.
  2. Turn on Ruff C901 with a sensible max-complexity.
  3. Post complexity deltas in PR comments before you hard-fail the whole team.

Agents can dump a lot of code in one go. Asking for a second pass with a concrete target (route_nested cognitive score went up, flatten the nesting) costs little next to shipping it.


Have you wired cognitive or cyclomatic complexity checks into AI-assisted workflows? Curious what broke in practice and what you'd do differently.

Top comments (0)