My AI Agent A program that calls a language model in a loop and lets it use tools, such as search or code. fixed a bug. A model reply that was cut off at the Output limit The most tokens a model may write in one reply. At the limit it stops, even mid sentence. counted as a success. The agent wrote tests. All 14 passed in one second, and it committed. The fix added one raise The Python statement that throws an error. The function stops there, and the error goes to its caller., and none of the 14 tests ran that raise. In this post I build a gate that runs as a Pre-commit hook A script Git runs before it saves a commit. If the script fails, Git refuses the commit.. It lists every new code line and runs the commit's tests. When a new line never ran, it rejects the commit.
The commit
Fourteen tests passed in one second
On Sunday, September 13, my agent worked on the model client in my own tooling. A model can stop because it hit the output token limit. The API then reports finishReason A field in the model's reply that says why it stopped, such as STOP or MAX_TOKENS. and returns half a reply. My client read that half reply as a normal answer. A later step applied it as if it were complete.
The agent's commit did three things. It removed the Token A small piece of text, often part of a word. Models read, write and bill text by the token. default output limit. It added a raise in the Reply parser My code that reads the model's raw reply and pulls out its text. for a MAX_TOKENS finish. And it added a branch to the Error classifier Code that reads an error message and sorts it, here into retry or fatal.. That branch marks a token-limit message as fatal, so my client does not retry it. The commit also added two test files. Later I replayed the commit on the tree it was made on: 14 tests passed in 1.01 seconds.
What the tests ran
One new test checked the new default limit. The other checked the classifier with a token-limit string. No test sent a cut-off reply to the parser, so the raise never ran. The commit changed 25 lines. Its own tests ran 4 of them. I also ran the whole suite on that tree, and the raise still never ran.
The commit had a second problem. The agent pasted the new classifier branch twice. The first copy returns early, so the second copy is Dead code Code that no input can ever reach, so it never runs. that no test can reach. It stayed in the file for 10 days, until a cleanup commit deleted it. The agent did add a test for the raise, but in a later commit, 52 minutes after the first one.
My Part 5 post, The Behavior Gate, re-runs the Pin A saved fingerprint of each baseline test. If a test changes, its fingerprint no longer matches. tests at commit time. My Part 6 post, The Repro Fence, checks two things: a bug test fails before the fix, and public Signature A function's name and its list of parameters. A call must match it. keep their shape. Both gates passed this commit. The pinned tests still passed, and the new tests were not bug Reproducer A test that shows the bug. It fails while the bug is there and passes once it is fixed.. Neither gate asks which new lines the tests run.
Get the next essay by email
One email per new essay: a production failure, taken apart, and the code that fixed it. Reply to any of them to unsubscribe.
The gate
The diff adds 9 lines
8 of them are code
The tests run 6 of the 8
The tests now run all 6
Step 1: list the new code lines
coverage_delta.py check reads the Staged Added to Git's staging area with git add, ready for the next commit but not yet saved in it. Diff The lines a change adds, removes or edits, compared with the code before it. with git diff --cached -U0. Each Hunk One block of changed lines in a diff. Its header gives the first line number and the line count. header gives the first added line and the count. So the gate gets the exact line numbers that the commit adds to each .py file:
def added_lines(repo: Path) -> dict[str, set[int]]:
"""Staged .py files mapped to the line numbers the commit adds to them."""
diff = git(repo, "diff", "--cached", "-U0", "--no-color", "--diff-filter=AMR", "--", "*.py")
out: dict[str, set[int]] = {}
current = ""
for line in diff.splitlines():
if line.startswith("+++ "):
current = line[6:] if line.startswith("+++ b/") else ""
continue
match = HUNK_RE.match(line)
if match and current:
start, count = int(match.group(1)), int(match.group(2) or "1")
out.setdefault(current, set()).update(range(start, start + count))
return outComments, blank lines, and Docstring A text string at the top of a Python function that describes it. It is not code that runs. continuation lines do not run, so they cannot count. The gate compiles the staged source. It keeps only the lines that produce Bytecode The small steps Python compiles source code into before it runs them. Comments and blank lines make none.. A new comment adds zero lines to check.
def executable_lines(source: str, rel: str) -> set[int]:
"""Line numbers that compile to at least one bytecode instruction."""
lines: set[int] = set()
stack = [compile(source, rel, "exec")]
while stack:
code = stack.pop()
lines.update(line for _, _, line in code.co_lines() if line is not None)
stack.extend(c for c in code.co_consts if hasattr(c, "co_lines"))
return linesStep 2: run the tests and record each line
Python 3.12 added sys.monitoring. It is a Standard library The modules that ship with Python itself, so nothing extra needs installing. hook that calls a function of mine on events such as "this line is about to run". The gate starts a fresh Interpreter The program that reads and runs Python code. A new one starts with no state from the last. and registers a LINE Callback A function I hand to other code. That code calls it each time a given event happens. there. Then it runs pytest A common Python test runner. It exits 1 when a test fails and 0 when all tests pass. on the staged test files in that interpreter:
mon = sys.monitoring
TOOL = 4
mon.use_tool_id(TOOL, "coverage-delta")
hits = {}
def on_line(code, line):
path = os.path.realpath(code.co_filename)
if path in targets:
hits.setdefault(path, set()).add(line)
return mon.DISABLE
mon.register_callback(TOOL, mon.events.LINE, on_line)
mon.set_events(TOOL, mon.events.LINE)
import pytest
rc = pytest.main(["-q", "-p", "no:cacheprovider", *sys.argv[3:]])The callback returns DISABLE. That turns the event off for that line after its first run. So each line costs one callback, not one per loop pass. The gate then compares the two sets: the new code lines and the lines that ran. A new code line that never ran prints as [COV-delta] file:line never ran with its source text, and the gate rejects the commit.
Three more rules keep the check honest. First, if the tests fail, the gate rejects the commit. Coverage The record of which code lines ran while the tests ran. A line no test ran is uncovered. from a failing run proves nothing. Second, if a staged file also has unstaged edits, the gate rejects it. The tests would run code that is not in the commit. Third, a line may opt out with # cov-delta: skip <reason>. A skip with no reason still fails.
The fix
The same commit, replayed
I rebuilt the commit in a two-file scratch repo with the same shape. It removes the default limit, adds a raise for a MAX_TOKENS finish, pastes the classifier branch twice, and adds tests for the default and the classifier. The tests pass, but the commit does not:
$ python3 -m pytest -q test_model_client.py
6 passed in 0.01s
$ git commit -m "fix: treat cut-off replies as errors"
[COV-delta] model_client.py:19 never ran: return "fatal"
[COV-delta] model_client.py:29 never ran: raise RuntimeError("[MAX_TOKENS] reply was cut off at the output limit")
coverage delta: 6 of 8 new code lines ran under test_model_client.py
exit=1Line 19 is the second copy of the classifier branch. Line 29 is the raise. Each one needs a different fix. I delete the duplicate. The raise gets a test that sends a cut-off reply and expects the error:
def test_cut_off_reply_raises():
with pytest.raises(RuntimeError, match="MAX_TOKENS"):
parse_reply(reply("half a sent", finish="MAX_TOKENS"))With both changes staged, the gate prints coverage delta: 6 of 6 new code lines ran under test_model_client.py, and the commit lands. The gate itself is 158 lines of standard library Python, with 6 tests of its own.
What each gate can see
Each row is one way a fix can look finished. Each cell says whether that gate rejects it.
| Move | Behavior gate (part 5) | Repro fence (part 6) | Coverage delta (part 7) |
|---|---|---|---|
| Fix line with no test that runs it | Missed, pinned tests pass | Missed, no reproducer given | Caught, [COV-delta] on the line |
| Pasted branch that can never run | Missed | Missed | Caught, same message |
| Regression test A test that checks an old feature still works after a change. When it fails, something broke. written green after the fix | Missed, not in the pinned baseline | Caught, the test passed before the fix | Missed, the test runs the new line |
| Public keyword added for one caller | Missed while pinned tests pass | Caught, signature changed | Missed |
| Pinned test body edited to pass | Caught, hash changed | n/a | Missed |
No column catches every row. That is why the three gates run in sequence. The coverage delta gate catches the first two rows: the untested fix line and the pasted branch. It misses the third. A regression test written after the fix runs the raise, so the coverage check passes. The repro fence rejects that commit instead.
The boundary
What this gate does not check
A test can run a line without checking it. A test can call the parser with a cut-off reply, catch every exception, and Assertion The line in a test that states what must be true. If it is false, the test fails. nothing. The gate sees the raise run, and it passes. Mutation testing A check that changes one line of code on purpose and expects at least one test to fail. asks the stronger question: does a test fail when the line changes? It costs minutes per file. This gate costs seconds per commit.
It counts lines, not branches. A one-line x = a if cond else b counts as run when either side runs. The other side may never run.
It sees Python only, and the staged tests decide what counts. When a commit stages test files, only those tests run. So a new line that an older test covers still fails. I pass --test to add that older test. A commit that stages no test file runs the whole suite. Above 30 staged .py files, the gate prints a notice and skips. So a large commit goes through unchecked.
Next I plan to build a small mutation pass for the lines this gate lists. It will change each new line and check that at least one test fails.
Three gates, one question each
Part 5 asks whether the old tests still pass. Part 6 asks whether the bug test failed before the fix and whether the public shape held. Part 7 asks whether the tests ran the new code. The agent on September 13 answered yes to the first two and never faced the third.
It reported "14 passed", and it was right. It did not report which lines those 14 tests ran, because nothing asked. Now the commit hook asks, and it prints the line numbers.
Primary research and documentation
- sys.monitoring, Python documentation: the standard library event API the gate uses, with
LINEevents and theDISABLEreturn value. - PEP 669: Low Impact Monitoring for CPython: the proposal that added
sys.monitoringin Python 3.12.