跪拜 Guibai
← All articles
Open Source

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

By jincheng_xie ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

Passing tests don't prove behavior unchanged after a large refactor, because they only cover written paths and mocking can silently miss moved code. This post lays out a practical four-step verification workflow, from record/replay to mutation testing, that any developer refactoring legacy functions can adapt to catch subtle behavioral differences.

Summary

A background task function that called upstream services, handled rate limiting and retries, wrote results, and sent notifications had grown to 1572 lines with cyclomatic complexity 143. An AI coding assistant split it into 150 lines with complexity 7, following rulemason, an open-source tool that imposes code rules and checkpoints for AI edits. All 6471 tests passed at every step, but the team refused to treat green tests as proof of behavioral equivalence.

Four extra checks were added. Record/replay ran the relevant 554 tests both before and after, comparing every SQL statement and log line; it found 4 tests issuing one extra database query each due to cache release differences. Differential testing generated 12,000 random scenarios and ran old and new versions against bookkeeping stand-ins, requiring identical return values, dependency calls, exceptions, and database writes; all matched. Coverage self-check confirmed all 814 changed lines were executed. Finally, 63 deliberate bugs were planted, and the differential exam caught all of them, after earlier rounds missed some until scenarios were expanded.

The refactoring increased file length by 31%, from 3400 to 4453 lines, because splitting doesn't reduce total branch points. rulemason handled limits, queueing, planning, and rules but did not include the verification scripts; those were written by AI on the spot under the principle that evidence must be independent of the test suite.

Takeaways
— The main function went from 1572 lines and cyclomatic complexity 143 to 150 lines and complexity 7, with all 6471 tests passing at each of four reversible steps.
— Cyclomatic complexity was the refactoring target, not line count; a 22-line function with 12 branches needed splitting while an 85-line function with 2 branches did not.
— Record/replay of 554 tests found 4 tests each performing an extra database query after the refactor, caused by cache release when the function split; results were identical so differential testing couldn't catch it.
— Differential testing ran 12,000 randomly generated scenarios against stand-in dependencies; old and new versions produced identical outcomes in every case.
— Deliberately planting 63 bugs and rerunning the differential exam eventually caught all of them; early rounds missed some until scenarios were expanded.
— File length grew 31% (3400 to 4453 lines) because splitting doesn't reduce total branch points; the main function stops at 150 lines since the remaining complexity is 7.
— rulemason installed a complexity limit of 10 via Ruff, queued modules by problem count, and required a human-confirmed plan before AI refactoring; it does not bundle the verification scripts.
— Each verification check was validated by deliberately introducing a bug and confirming the check would fail, per rulemason's principle that evidence must be independent of passing tests.
Conclusions

Line count is a poor proxy for code readability; cyclomatic complexity captures branching intensity, and the article's 22-line, 12-branch example shows how length can hide complexity.

The mutation testing step is the strongest because it verifies the verification itself: a check that can't catch an injected bug is worthless, regardless of how many scenarios pass.

The 31% file-length increase shows that reducing complexity trades monolithic functions for smaller callable pieces; the total number of branch points stays the same, just spread out.

Concepts & terms
Cyclomatic complexity
A metric measuring the number of independent paths through a function, counting each branch point (if, loop, except). Ruff's C901 rule flags functions above a configurable limit, default 10, based on McCabe's original recommendation.
rulemason
An open-source tool that sets coding rules and checkpoints for AI coding assistants, enforcing complexity limits, queueing cleanup tasks, and requiring human confirmation before AI refactoring. It supports Claude Code, Cursor, Codex, and OpenCode.
Differential testing
Running old and new versions of code against the same generated scenarios and comparing outputs, dependency calls, exceptions, and database writes to detect behavioral differences that unit tests might miss.
Mutation testing
Deliberately introducing bugs (changing constants, boundaries, or dependency calls) and rerunning a test or verification suite to confirm it can detect the injected fault, validating the suite's ability to catch real errors.
Record/replay comparison
Capturing each test's external interactions (SQL statements, log lines) before and after a change, then comparing them line by line to spot differences in behavior that result-equality wouldn't show.
From the discussion

The discussion centers on how a green test suite can still leave entire code paths uncovered. A concrete failure case shows an assertion that only checked data-table length while the actual write-to-database step lived in an untested service, causing a production bug. Another response suggests deliberately deleting the critical line and rerunning tests to confirm actual coverage. A separate question raises function-splitting criteria, but that thread goes no further.

— A green unit test may verify only the data table, not the service-side write path, so behavior breaks in production despite full test pass; evidence of coverage must include a test that walks the entire path from start to finish.
— Deliberately removing a key line and rerunning the suite serves as a direct way to verify whether that path is genuinely tested — if the suite stays green, the path has no real coverage.
— The standard for splitting a function (line count, cyclomatic complexity, or intuition) is raised as an open question, though no consensus emerges in these comments.
Featured comments
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?

See top comments, translated →
Source: juejin.cn ↗ Google Translate ↗ Backup ↗