Sub topic 8
Apply one change at a time
You have a diagnosis you trust, and the assistant has proposed a fix. This chapter covers how to apply that fix so you can tell what worked and undo it cleanly if it didn't.
This chapter assumes you can use git for commits, diffs, and branches. It also assumes you can run a test or script from a terminal, and that you have already reproduced the failure and checked the diagnosis against the evidence, as covered in earlier chapters.
Why one change at a time
An assistant can rewrite a whole file in a few seconds. That speed is the risk. If it changes five things at once and the failure disappears, you don't know which change fixed it. If the failure stays, you don't know which change made things worse. If a new failure appears, you can't tell which edit caused it.
Debugging is an experiment. Each change is a hypothesis: "if I do this, the failure goes away." A single change gives you a clear result. Several changes at once make the result ambiguous.
Small changes also bring practical benefits:
- You can review a three-line diff properly. Reviews of 200-line diffs tend to be skimmed.
- A small change is easy to revert without losing other work.
- The commit history records what fixed the problem, which helps whoever hits the bug next.
- An assistant that edits only what is needed is less likely to introduce unrelated bugs.
Start from a clean, recoverable state
Before you apply anything, make sure you can get back to where you started. Check the working tree, then create a branch for the fix.
git status
git switch -c fix/average-empty-listIf git status shows uncommitted changes, deal with them first. Either commit them or set them aside with git stash. Otherwise your own edits and the assistant's edits end up mixed in one diff, and you lose the ability to say which is which.
The branch gives you a place to experiment. If the fix goes badly, you can discard the branch and the main line is untouched.
# Abandon one file's uncommitted changes
git restore stats.py
# Abandon the whole experiment and return to the main branch
git switch main
git branch -D fix/average-empty-listgit restore and git branch -D discard work permanently, so run them only when you are sure you don't need the changes.
Ask for the smallest change
Your prompt already asked for "the smallest change that fixes it." Hold the assistant to that. When a reply includes more than you asked for, you have three options: ask it to trim the reply, reject it, or apply only part of it.
Take the failing function from the running example:
def average(values):
return sum(values) / len(values)
print(average([]))The diagnosis was that len(values) is 0 for an empty list, so the division raises ZeroDivisionError. The expected behavior was a clear error telling the caller the input is empty. The smallest fix is two added lines:
def average(values):
if not values:
raise ValueError("average() requires at least one value")
return sum(values) / len(values)Now consider a reply that looks helpful but is much bigger. It might rename the function, add type hints, switch to statistics.mean, add logging, and wrap the call in a try/except. Some of that may be good practice. None of it is needed to fix this bug. Mixed into one change, those extras make the fix harder to review and add behavior you didn't ask for. For example, statistics.mean raises StatisticsError on empty input, not ValueError, so existing callers that catch ValueError could break.
You can keep the useful ideas without applying them now. Note them for later and handle each as its own change after the bug is fixed.
Prompts that keep the scope tight
These follow-up prompts keep the assistant within bounds:
- "Show me only the lines that change, as a diff. Don't rewrite the whole function."
- "Don't rename anything, add features, or reformat code. Fix only this error."
- "Which of these changes are required for the fix, and which are optional?"
- "Give me the fix and list any other problems you noticed separately, without applying them."
The last prompt is useful. It lets the assistant report extra findings without mixing them into the patch.
Read the diff before you accept it
Whether you paste the change by hand or the assistant edits files directly, look at the actual diff before you run anything.
git diffFor the fix above, the diff should look like this:
def average(values):
+ if not values:
+ raise ValueError("average() requires at least one value")
return sum(values) / len(values)Check four things:
- Scope. Does the diff touch only the files and functions involved in the failure? Use
git diff --statfor a quick count of files and lines. - Intent. Does each changed line follow from the diagnosis? If you can't explain a line, ask the assistant why it is there.
- Side effects. Did the change alter behavior for inputs that already worked? Here, non-empty lists take the same path as before.
- Surprises. Look for deleted code, changed imports, edited config, and modified tests. A "fix" that deletes a failing test or loosens an assertion is a red flag.
If a diff is mostly good with one questionable hunk, stage only the parts you want:
git add -pGit shows each hunk in turn and asks whether to stage it. Answer y to stage, n to skip, and s to split a hunk into smaller pieces. Then git commit records only what you approved. Skipped hunks stay in your working tree, so you can discard them with git restore or revisit them later.
The apply, run, decide loop
The workflow is a short loop. Each pass tests one hypothesis.
In practice, a pass looks like this:
- Apply the single change.
- Run the same reproduction you used before: the smallest script or test that shows the failure. Running the exact same check is what makes the before-and-after comparison valid.
- If the failure is gone and nothing else broke, commit with a message that names the cause.
- If it isn't, revert. Don't pile a second change on top of a failed first one.
Reverting a failed attempt matters more than it seems. If you keep a failed change and add another, you are now debugging the combination. If the first change was wrong but harmless, it stays in the code as noise. If it was wrong and harmful, it hides the real result of the second change.
For a quick revert of one file:
git restore stats.pyIf you already committed an attempt and then decided it was wrong, undo it without rewriting history:
git revert HEADgit revert adds a new commit that undoes the previous one. That is safe on a shared branch. Avoid git reset --hard unless you know exactly which work you are discarding.
Commit each working step
When a change passes, commit it before you start anything else. A commit is a checkpoint you can return to.
git add stats.py
git commit -m "Raise ValueError when average() gets an empty list"A good message states the behavior change and, where it helps, the cause. "Fix bug" tells the next reader nothing. "Raise ValueError when average() gets an empty list" does. Later chapters cover recording the root cause and adding a regression test. For now, the point is that one working step becomes one commit.
If the assistant suggests a second improvement, such as handling None input, treat it as a new pass through the loop. It gets its own change, its own reproduction, and its own commit.
When one fix needs more than one change
Some bugs really do need edits in several places. Suppose a function returns the wrong value because both a helper and its caller mishandle the same input. That isn't a reason to apply everything at once. Split the work into steps that can each be checked on their own:
- Order the edits so that each leaves the code in a runnable state.
- After each edit, run the reproduction. It may still fail, but the failure should change in a way that matches your expectation. For example, the error moves from the caller to the next layer.
- If the failure changes in a way you didn't predict, stop. Your model of the bug is incomplete, and you should return to the diagnosis step instead of applying more edits.
A changed error message is useful information. It tells you the first edit had an effect, and the new message points at the next problem.
Letting the assistant edit files directly
Many tools let the assistant edit your files directly instead of pasting a patch. The same rules apply, and the cost of ignoring them is higher, because edits land without a copy-and-paste step that forces you to look at them.
- Start from a clean tree, so every change in
git diffcame from the assistant. - Ask it to make one edit at a time, or at least to stop after each logical step.
- Review
git diffafter each step, not only at the end. - Don't let it commit for you until you have read the diff.
Running commands and tests is a separate topic, covered in the agentic debugging chapter.
Common mistakes
| Mistake | What goes wrong | Better habit |
|---|---|---|
| Accepting a whole-file rewrite | You can't see what changed or why | Ask for a diff of only the changed lines |
| Applying two fixes before testing | You can't tell which one worked | Apply, run, then decide, once per change |
| Keeping a failed attempt in the code | Later results are confounded by it | Revert before the next attempt |
| Fixing "while you're here" | Unrelated edits hide the real fix | Note extras and handle them separately |
| Running a different check each time | Results aren't comparable | Reuse the same reproduction |
| Starting with a dirty working tree | Your edits and the assistant's blur together | Commit or stash first |
Summary
Treat each fix as a single experiment. Start from a clean branch, ask for the smallest change, and read the diff before you run it. Rerun the same reproduction, then commit what works and revert what doesn't. Keep unrelated improvements out of the fix and handle them afterward as their own changes.
Exercise
An assistant replies to your average([]) bug with a patch that adds the empty-list check, renames values to numbers, adds type hints, and wraps the caller in a try/except Exception. The empty-list check looks correct. Using git, how do you apply only that part, and what do you do with the rest?
Show answer
Create or switch to a fix branch from a clean working tree and apply the patch. Run git diff to read it, then run git add -p and stage only the hunk with the empty-list check, answering n to the rename, type hints, and try/except. Use s to split hunks if the check and another edit share one. Run the original reproduction to confirm the failure is gone, then commit with a message such as "Raise ValueError when average() gets an empty list". Discard the unstaged hunks with git restore, or save the rename and type hints as separate follow-up changes. Reject the try/except Exception outright, because it would hide errors that should reach the caller.
Exercise
You applied a fix and the original error is gone, but the same script now fails with a different error further down. Should you commit, keep editing on top, or revert? Explain.
Show answer
Don't commit yet, and don't just keep stacking edits. A new error means the first change had an effect, but the bug is not fully understood. Compare the new error with what you predicted. If the change was correct and exposed a second, separate problem, you can commit the first change as its own step and treat the new error as a new debugging pass. If the new error was caused by your change, revert it and go back to the diagnosis. In both cases, handle one change at a time and rerun the same reproduction after each.