Sub topic 10
Iterate when the first fix does not work
This chapter assumes you can read a Python traceback, run pytest from a terminal, and use git to commit and revert changes. It also assumes you have already written a debugging prompt and applied one change at a time, as covered in earlier chapters.
The first fix an assistant proposes often fails. That is normal. What matters is what you do next. A vague "that didn't work" produces another guess. A precise follow-up produces a better one.
Why a first fix fails
A fix can fail in several distinct ways. Each one points to a different next step.
| What you observe | What it usually means | Next step |
|---|---|---|
| Same error, same line | The change did not touch the cause, or was not applied | Confirm the edit is saved and the right file runs |
| Same error type, different line | The fix moved the problem or exposed a second one | Report the new traceback in full |
| New error type | The first fix worked and a later bug is now visible | Treat it as a new, smaller problem |
| No error, wrong output | The fix hides the symptom without fixing the cause | Compare actual output with expected output |
| Test passes, other tests fail | The fix broke an existing behavior | Share the failing test names and output |
Classify the result before you write anything. The classification decides what information the assistant needs.
The iteration loop
Each round has the same shape. You run the code, record what changed, and feed that evidence back.
Two details in this loop matter. First, you rerun the same reproduction every time, so results are comparable. Second, there is an exit. Without a limit, you can spend an hour on a bug you could have traced yourself in ten minutes.
Worked example: a fix that exposes a second bug
Suppose the earlier average function is now used in a report script. You applied this fix:
def average(values):
if not values:
raise ValueError("average() requires at least one value")
return sum(values) / len(values)The report script calls it for several groups of scores.
from stats import average
def report(groups):
for name, scores in groups.items():
print(f"{name}: {average(scores):.1f}")
report({"math": [90, 80], "art": []})Running it prints a line, then fails:
math: 85.0
Traceback (most recent call last):
File "report.py", line 9, in <module>
report({"math": [90, 80], "art": []})
File "report.py", line 6, in report
print(f"{name}: {average(scores):.1f}")
File "stats.py", line 3, in average
raise ValueError("average() requires at least one value")
ValueError: average() requires at least one valueThis is the "new error type" case from the table. The first fix did its job. average now rejects empty input with a clear message. The remaining question is a design decision: what should the report do for a group with no scores? The assistant cannot know this unless you say so.
Write the follow-up
A useful follow-up contains four things: what you changed, what happened, what stayed the same, and a constraint.
I applied your change to average() in stats.py. The original ZeroDivisionError is gone.
Running report.py now stops at the "art" group with:
ValueError: average() requires at least one value (traceback below)
<paste the full new traceback and report.py>
average() should keep raising on empty input, because other callers rely on that.
The report should print "art: n/a" for empty groups and continue.
What is the smallest change to report.py that does this?Compare this with "it still fails." The follow-up gives the new error, keeps the earlier fix in place, and states a constraint that prevents the assistant from undoing it. Without the constraint, a common response is to make average return 0, which would hide empty input everywhere.
The resulting change stays in report.py:
from stats import average
def report(groups):
for name, scores in groups.items():
if scores:
print(f"{name}: {average(scores):.1f}")
else:
print(f"{name}: n/a")
report({"math": [90, 80], "art": []})Output:
math: 85.0
art: n/aWhat to include in each follow-up
- The exact new output. Paste the traceback or test output unchanged. Do not summarize it.
- What you actually applied. If you adjusted the suggestion, say so. The assistant otherwise reasons about code you are not running.
- What you ruled out. For example, "the file is saved and I restarted the server." This stops the assistant from repeating basic suggestions.
- Constraints. Name behavior that must not change, such as public function signatures or other callers.
- A narrow request. Ask for the smallest next change, not a rewrite.
Keep the conversation clean
Long debugging threads accumulate failed attempts. The assistant may anchor on an early wrong theory or mix up which version of the code is current. You can reduce this in three ways.
- Restate the current state. Every few rounds, paste the current version of the function and the current error. Say "ignore earlier versions."
- Revert failed attempts. Use
git diffto see what has changed andgit restore <file>to discard an edit that did not help. A clean working tree makes the next experiment readable. Commit a fix only when its test passes. - Start a new conversation. If the thread has gone around in circles, open a fresh one. Include the original problem, the evidence gathered so far, and a list of theories already ruled out.
Ask for diagnosis, not just another patch
When two attempts fail, the issue is often the diagnosis, not the code. Ask the assistant to step back:
Your last two fixes did not resolve this. Before proposing another change:
1. List the hypotheses that could explain the evidence so far.
2. For each one, name a command or print statement that would confirm or rule it out.
3. Tell me which to check first.Then run the checks yourself and report the results. This turns the assistant into a planner for experiments instead of a generator of guesses. It also catches the case where the assistant is reasoning from a wrong assumption, such as the wrong Python version or a stale installed copy of a package.
A quick check that often settles the "is my change even running" question is:
import stats
print(stats.__file__)If this prints a path you did not expect, such as a copy in site-packages, your edits are not the code that runs.
Edge cases
- The failure is intermittent. A fix that passes once proves little. Run the reproduction several times, or add logging around the suspect step, and report how often it fails.
- The error message changes but the cause does not. Different symptoms can share one root cause, such as bad input read at the start of the program. Ask whether the new error could come from the same upstream value.
- The assistant contradicts an earlier answer. Ask it to reconcile the two statements against the evidence. Do not simply choose the more recent one.
- The assistant asks for information you cannot provide. Say so, and ask for a way to narrow the problem without it.
- Progress is only apparent. If errors change every round but the program is no closer to working, stop and compare your current code with the last known working commit.
Decide when the loop has run long enough
Track progress honestly. A round counts as progress if the error moved closer to the expected behavior, you learned a fact that rules out a hypothesis, or a test went from failing to passing. A round that only changes the error text does not count.
A practical rule: after three rounds without progress, change your approach. Add a debugger breakpoint or print statements, read the relevant source yourself, or bisect with git bisect to find the commit that introduced the bug. Later chapters cover when to take over fully.
Recap
- Classify what happened after a fix before writing the follow-up.
- Send exact output, what you applied, what you ruled out, and what must not change.
- Revert failed attempts so each experiment starts from a known state.
- After two failures, ask for hypotheses and checks instead of another patch.
- Set an exit rule so the loop does not run indefinitely.
Exercise
You apply an assistant's fix for a failing test. The original error disappears, but the test now fails on a different line with a KeyError. Which row of the classification table does this match, and what should your follow-up contain?
Show answer
It matches "Same error type, different line" only if the error type were unchanged. A KeyError after a different error is a "new error type", so the first fix probably worked and exposed a later bug. Your follow-up should include the full new traceback, a statement that the original error is gone, the code you are now running, any constraints on behavior that must not change, and a request for the smallest change that addresses the KeyError.
Exercise
A second suggested fix did not help, and you have already applied it on top of the first, which also did not help. What should you do before asking again, and why?
Show answer
Revert both changes (for example with git restore) so you return to a known state, then apply one change at a time. Stacked unverified fixes make it impossible to tell which change caused which result. After reverting, ask the assistant for a list of hypotheses and a check for each, run those checks, and report the results.