跪拜 Guibai
← Back to the summary

A 1572-Line Function, Refactored to 150 Lines: Why Green Tests Weren't Enough

All tests green, doesn't mean nothing broke: After AI split a 1572-line function, I did four more things

A 1572-line function was split into 150 lines by AI following the cleanup process of the open-source tool rulemason, with all tests green. But green tests only mean the written cases didn't break. This post covers the four things we did afterward before we could say "behavior hasn't changed one bit".

Look at the results first

The project has a background task function that calls upstream services, handles rate limiting and retries, writes results, and sends notifications. Everything is in one function, 1572 lines. Anyone who wants to change it has to find the few lines they need within 1500+ lines.

This time, the AI coding assistant (Claude Code) did the work, following the existing cleanup process of rulemason. A human confirmed the plan and acceptance. rulemason is an open-source project: it sets rules for AI coding tools and adds checkpoints every change must pass. What it managed in this cleanup is discussed in Section 5. Results:

Before After
Main function lines 1572 150
Main function complexity 143 7
Full test suite 6471 passed 6471 passed, 0 failed at every step

What "complexity" means is explained in the next section.

1. How long is too long? Count branch points, not lines

A well-known table circulates online: fewer than 30 lines is ideal, 80-150 lines is somewhat long, over 200 lines needs refactoring, and 1500+ lines is a "big ball of mud". It's easy to remember, but only looks at length.

What actually tires you when reading code is how many cases you have to keep in mind at once. Cyclomatic complexity counts exactly that: how many branch points (if, loops, except...) are in a function. A 500-line function that runs straight through has complexity 1; a 20-line function full of conditionals can exceed 10. Python's lint tool Ruff checks this with rule C901, default limit 10, a figure from McCabe, who proposed cyclomatic complexity, back in his day.

We took the same batch of 11 functions and measured each with both rulers:

image.png

The two rulers agree at the extremes; 1572 lines is obviously worth splitting. The disagreement is in the middle:

So this time the goal only looks at complexity: split every function to under 10. Line count is not a goal; we agreed upfront not to promise line reduction.

2. How to split: 4 steps, each reversible

Splitting 1572 lines in one go and hitting a problem would leave you clueless about what caused it. We split into 4 steps, each a state that can be committed and reverted independently:

Before       143
Step 1       80   extract "write result" and "cleanup"
Step 2       68   extract "pre-checks" and "no available route"
Step 3        7   extract the hardest "route retry loop"
Step 4           handle 3 other over-limit functions in the same file

After splitting, the main function reads like a table of contents (illustrative, anonymized and simplified):

async def run_job(...):
    job = prepare_job(...)                      # pre-checks
    if (done := await already_finished(job)):   # already done, return early
        return done

    state = await run_route_loop(job)           # try each upstream route in order
    if state.finished:
        return state.result

    outcome = state.outcome()
    finalized = await finalize(job, outcome)    # write result, settle, audit
    await notify(job, finalized)                # push and alert
    return summary(job, outcome)

We also fixed several typical problems along the way:

3. Four things after tests turned green

Why is green not enough? Two reasons:

So we did four more things. They share a rule: after each check is written, deliberately break the code in one spot, confirm the check catches it, then revert. A check that can't find an error is useless no matter how many times it runs. This principle is written in rulemason's cleanup process.

First: Record/replay comparison

Run the relevant 554 tests before and after, and log every SQL statement and every log line each test emits, then compare line by line. Like recording two videos of the program and comparing frame by frame.

Result: 535 identical, 14 unstable before the change (e.g., output contains AI-generated random copy), and 4 inconsistent.

These 4 each issued one extra database query, but the data fetched was exactly the same. Reason: these tests share a single database connection; before the change, the big function held onto a certain record in its cache, so re-reading didn't hit the DB; after splitting into small functions, the record is released when the function returns, so re-reading requires a new query. We temporarily kept the record alive and reran; the difference disappeared, confirming the cause. In production, each run creates a new connection, so it queries the DB anyway; no practical difference.

Differential testing can't catch this, because the results are identical.

Second: Old and new versions do the same exam

Keep a copy of the pre-change code alongside the new code. Replace all external dependencies (database, queue, upstream services) with bookkeeping stand-ins. Then randomly generate a large set of scenarios (upstream success, failure, rate limit, timeout...), run both versions on each, and require return values, which dependencies were called, what exceptions were raised, and final database writes to all match.

The main function took 12,000 such scenarios, all identical.

We hit a trap here too: the referee missed something. The comparison script had the wrong log level; INFO-level logs were never recorded and thus not compared. After fixing and rerunning, the conclusion didn't change, but the evidence was only then complete. The checking tool itself must be checked.

Third: Confirm the exam actually reached the new code

All 12,000 scenarios passing requires the scenarios to actually execute the new code. Stats showed all 814 lines that were added or changed had been executed.

Fourth: Deliberately plant bugs

Executed doesn't mean checked. The final step is to deliberately plant bugs in the code: change a constant, alter a boundary, skip a dependency call... For each one, rerun the old-new differential exam and see if it catches it.

We planted 63 total, all caught in the end. The first few rounds had misses, meaning the random scenarios didn't reach the planted path; after adding scenarios, all were caught. Without this step, "12,000 all pass" could just mean the exam was too easy.

Tests green          6471 each step passed          baseline
Record/replay        554 tests compared line by line   externally emitted things same
Differential exam    12,000 scenarios all matched      results same across cases
Coverage self-check  814 lines all executed            exam reached new code
Deliberate bugs      63 all caught                     checks can catch errors

4. Costs and limitations

5. What rulemason did here

This function being discovered, scheduled, and split the way it was, every step had a piece of rulemason:

Integrate      install lint rules: complexity limit 10
  |            old code registered as "pre-integration legacy" so it doesn't go red on day one
  v
Diagnose       /rulemason cleanup: queues all 60 modules by problem count
  |            calls out "this function has complexity 143, needs batch splitting"
  v
Plan           complexity target, number of steps, no promise on line count, wait for human confirmation before acting
  |
  v
Act            AI follows the seven principles of the cleanup process
  |
  v
Wrap up        run ruff and full test suite; cleaned files removed from "legacy" list

Also state what rulemason didn't do: the record/replay, differential exam, and deliberate bug planting scripts were written on the spot by AI under the "evidence independent of tests" principle; rulemason doesn't currently bundle these tools. Conversely, the ~40 pieces of feedback recorded during cleanup of earlier modules in this project were written back into rulemason's cleanup process; that's where the seven principles above came from.

To try in your own project:

uv tool install rulemason    # install once
rulemason init               # run in project root, select your AI tool

Then run /rulemason in the AI tool to complete project info, then /rulemason cleanup for a repository-wide diagnosis. Supports Claude Code, Cursor, Codex, OpenCode.

6. Three lessons to take away

  1. Tests green is the baseline, not proof. To claim behavior unchanged, get several independent pieces of evidence, and first prove each piece can catch an error.
  2. Decide what to measure before acting. This time we measured branch points, not lines; measure before and after with the same command so numbers are comparable.
  3. Let AI work step by step, leaving evidence at each step. Every step can be reverted; if AI is interrupted mid-way, it can continue using the pre-change evidence saved earlier, without starting over.

Project repo: github.com/rulemason/rulemason. Contributions and issues welcome.

Comments

Top 2 of 3 from juejin.cn, machine-translated. The original thread is authoritative.

booboosui

I once hit a more insidious case of this "all tests green": there was a unit test that specifically asserted every preset copy didn't exceed 3000 characters, and it stayed green. But when tapping that bubble on a real device, the program only sent the message, didn't write the copy into the book, the model couldn't find it by name, and answered "never seen this scenario" right in front of the user. The assertion tested the data table, but the write-to-database line was inside a service, which the test never touched. Later, extracting that step into a unit-testable function finally blocked it: first write the book, then send the message; if a same-name entry exists, skip, because saving overwrites the entire row, and the second tap would overwrite your modified version without any warning. So now when I accept "behavior hasn't changed", I first ask: does this path have a test that actually goes through the whole flow from scratch?

jincheng_xie

Indeed 👍 The test only checked the character count wasn't exceeded; the real problem — writing to the book — was never touched by the test, so it stayed green. I had the AI deliberately delete the key line of code, then rerun the tests. If they're still all green, it means that path isn't actually tested. When you test the write-to-database step, do you connect to a real database or use a fake substitute?

jincheng_xie

What does your team use to decide when a function should be split? Line count, complexity, or just gut feeling?