Sub topic 11
Failure modes: invented APIs, behavior drift, over-broad edits
This chapter assumes you can read and write code, use Git branches and commits, and run a test suite and linter from the command line. It also assumes you have used a coding agent before. You will learn to recognize the three most common ways an agent goes wrong on existing code, and to set up guardrails that catch each one before it reaches your main branch.
Why failure modes matter more in existing code
A coding agent works in a loop: it reads files, edits them, runs commands, and observes the results. In a new project, a mistake costs little. In existing code, a mistake can break callers you did not think about, change behavior that users depend on, or hide inside a large diff that nobody reads closely.
Agent mistakes tend to look plausible. The code compiles, the style matches, and the summary the agent writes sounds confident. That is why you need checks that do not depend on how convincing the output looks.
The table below lists the three failure modes covered here and the main guardrail for each.
| Failure mode | What happens | Main guardrail |
|---|---|---|
| Invented API | The agent calls a function, method, or option that does not exist | Type checks, imports, and running the code |
| Behavior drift | The code is restructured, and its observable behavior changes | Characterization tests |
| Over-broad edit | The agent changes files or lines outside the task | Scope limits and diff review |
Failure mode 1: invented APIs
An invented API (sometimes called a hallucinated API) is a call to something that does not exist. The agent may use a method that belongs to a different library, a parameter name from an older version, or a helper function that it assumed your project had.
This happens because the agent predicts code that looks right. It does not always check the installed library version or search your repository first. The risk grows in migrations, where old and new versions of a library have similar names but different signatures.
What it looks like
Suppose you ask the agent to replace manual date parsing with a library function. The agent writes this:
from datetime import datetime
def parse_order_date(text):
# datetime has no method called parse_iso, so this fails at runtime
return datetime.parse_iso(text)The code reads naturally, but datetime has no parse_iso method. The real method is datetime.fromisoformat. In a dynamic language such as Python, nothing complains until the line runs. If no test covers that line, the error ships.
How to catch it
- Run the code paths that changed. A test that executes the new line fails immediately with an
AttributeError. - Use a type checker such as mypy or pyright, or the TypeScript compiler. These tools report unknown attributes without running the code.
- Run the linter. Many linters flag undefined names and unused or missing imports.
- Ask the agent to cite where it found the API: a file in your repo, or the version-specific documentation. If it cannot, treat the call as unverified.
A small script can also check that a name exists in the installed version before you rely on it:
import importlib
def api_exists(module_name, attribute_path):
"""Return True if module_name exposes the dotted attribute_path."""
obj = importlib.import_module(module_name)
for part in attribute_path.split("."):
if not hasattr(obj, part):
return False
obj = getattr(obj, part)
return True
print(api_exists("datetime", "datetime.fromisoformat")) # True
print(api_exists("datetime", "datetime.parse_iso")) # FalseGuardrails for migrations
In a library upgrade, pin the target version in your dependency file first, install it, and tell the agent which version it is working with. Point the agent to the upgrade guide or changelog for that version. Then let the compiler or type checker be the first judge of every change.
Failure mode 2: behavior drift
Behavior drift means the observable behavior of the code changes during a change that was supposed to keep it the same. A refactoring, by definition, keeps behavior fixed. Drift breaks that rule quietly.
Drift often comes from small things:
- Rounding or number formatting changes, for example when a float calculation is rewritten.
- Order changes, such as replacing a list with a set, which loses ordering.
- Different handling of
None, empty strings, or empty lists. - An exception that used to be raised is now swallowed, or the other way around.
- A default argument value changes.
- Evaluation order changes, so a side effect happens earlier, later, or not at all.
A worked example
The original function applies a 20 percent tax and rounds to two decimals:
def format_invoice(items):
subtotal = sum(i["price"] * i["qty"] for i in items)
tax = round(subtotal * 0.2, 2)
return {"subtotal": subtotal, "tax": tax, "total": subtotal + tax}An agent asked to extract the tax logic might produce a version that looks equivalent:
def calculate_tax(subtotal):
return subtotal * 0.2 # the round() call was dropped
def format_invoice(items):
subtotal = sum(i["price"] * i["qty"] for i in items)
tax = calculate_tax(subtotal)
return {"subtotal": subtotal, "tax": tax, "total": subtotal + tax}The diff is small and the structure is cleaner, but round(..., 2) is gone. Invoices with a subtotal of 10.15 now produce a tax value with floating-point noise instead of two decimals. No syntax error appears, and a type checker is satisfied.
How to catch it
A characterization test records what the code does today. Write it before the change, run it against the original code, and keep it unchanged while the agent works. The expected values come from running the existing code, not from a specification.
# tests/test_pricing.py
from pricing import format_invoice
def test_format_invoice_current_behavior():
items = [{"price": 10.15, "qty": 1}, {"price": 3.0, "qty": 2}]
result = format_invoice(items)
# Recorded by running the original implementation.
assert result["tax"] == round(result["subtotal"] * 0.2, 2)
assert result["tax"] == 3.23Run it before the change (it must pass) and after (it must still pass). With the dropped round, the second assertion fails and the drift is caught.
Include edge cases in characterization tests: empty input, zero values, None, very large numbers, and inputs that currently raise errors. These are where drift hides.
Guardrails against drift
- Tell the agent explicitly not to change the return value or public signature.
- Do not let the agent edit the characterization tests during a refactoring. If a test seems wrong, the agent should stop and report it.
- Watch for the opposite shortcut: when a test fails, an agent may change the test's expected value to match the new output. Reject any diff that changes assertions without a reason you agree with.
Failure mode 3: over-broad edits
An over-broad edit is a change outside the scope you asked for. The agent may reformat a whole file, rename unrelated variables, update imports in other modules, "fix" something it noticed, or delete code that looked unused.
These edits are risky for three reasons. They bury the real change in noise, so reviewers miss problems. They create merge conflicts with other work. And they can break code the agent did not understand, such as a function that looks unused but is called through reflection or a configuration file.
What it looks like
You ask for the calculate_tax extraction. The diff stat shows this:
git diff --stat
# pricing.py | 12 +++---
# tests/test_pricing.py | 9 ++---
# utils.py | 48 ++++++++++++++++++---------
# config/settings.yaml | 3 +-
# 4 files changedOnly the first two files were in scope. The changes to utils.py and config/settings.yaml need a close look, and usually a revert.
How to catch it
Check the list of changed files against the scope you set:
git diff --name-only
git diff --statYou can automate the check in a script that fails if any file outside an allowed list changed:
#!/usr/bin/env bash
# check_scope.sh: fail if files outside the allowed list were changed
allowed="pricing.py tests/test_pricing.py"
for file in $(git diff --name-only); do
case " $allowed " in
*" $file "*) ;;
*) echo "Out of scope: $file"; exit 1 ;;
esac
done
echo "All changes are in scope."If the agent touched something it should not have, restore only that file and keep the rest:
git restore utils.py config/settings.yamlGuardrails against over-broad edits
- Name the files in scope in the task description, and say "touch only these files".
- Ask for a plan first, and compare the plan's file list to your scope before approving it.
- Turn off or avoid automatic formatters on unrelated files while the agent works, so formatting changes do not enter the diff.
- Commit small steps. A small commit makes unrelated changes obvious.
- Do not accept "while I was here" cleanups. Ask for them as a separate task.
Other failure modes to watch for
Three more patterns appear often enough to know.
- Weakened verification. The agent skips a failing test, adds a
skipmarker, loosens a type, or adds a lint-ignore comment to make the check pass. Search the diff forskip,xfail,# type: ignore,noqa, andeslint-disable. - Unverified claims. The agent says "all tests pass" without running them. Run the checks yourself, or ask to see the command and its real output.
- Lost context in long sessions. In a long task, the agent may forget a constraint from the start. Repeat key constraints at each step, and keep the task small.
A quick search of the diff can find the first pattern:
git diff | grep -nE '^\+.*(skip|xfail|type: ignore|noqa|eslint-disable)'How the guardrails fit together
No single check catches every failure. Each layer catches a different kind of problem, so use them together at each small step.
Each failure mode maps to a layer. Type checkers and execution catch invented APIs. Characterization tests catch drift. Scope checks and diff review catch over-broad edits. Version control lets you undo any step cheaply.
Exercises
Exercise
An agent refactors a function and all existing tests pass, but a later bug report shows that a value is no longer rounded. Name the failure mode, and say what you should have done before the refactoring to catch it.
Show answer
This is behavior drift. Before the refactoring, you should have written characterization tests that record the current output, including rounding, and run them against the original code. They would have failed when the rounding was dropped. The existing tests passed because they did not cover that behavior.
Exercise
A diff for a one-function refactoring touches six files, including a configuration file and a formatting-only change in an unrelated module. What do you do, and what should the task description have included to prevent it?
Show answer
Restore the out-of-scope files (for example with git restore <file>), keep only the in-scope changes, and review what remains. The task description should have listed the files in scope, said to touch only those files, and asked for a plan to be approved before editing. Any useful cleanups should be requested as a separate task.
Exercise
The agent's diff makes a failing test pass by changing the test's expected value. Which two failure modes might be hiding behind this, and how do you search for related shortcuts?
Show answer
The change may hide behavior drift, because the code's output changed and the test was edited to match, and it is a form of weakened verification. Reject the change unless you agree the old expectation was wrong. Search the diff for added skip, xfail, # type: ignore, noqa, or eslint-disable markers, for example with git diff | grep -nE '^\+.*(skip|xfail|type: ignore|noqa|eslint-disable)'.