Sub topic 2
Reproduce the Failure and Shrink It
This chapter assumes you can run Python from a terminal, use git at a basic level, and read a stack trace (covered in the previous chapter). Examples use Python 3.12 and pytest, but the method applies to any language.
An assistant can only reason about what you show it. If you cannot make a failure happen on demand, you cannot tell whether a fix worked. If the failing case is buried in 2,000 lines of unrelated code, the assistant will spend its attention on the wrong parts. Two steps address both problems: reproduce the failure reliably, then shrink it to a minimal example.
Why reproduction comes first
A reproduction is a command or short script that triggers the failure every time. It does three jobs:
- It proves the problem exists in your current code and environment, not in your memory of what happened.
- It gives you a pass/fail check. After a change, you rerun it and see whether the failure is gone.
- It gives the assistant something concrete to reason about, which reduces guessing.
Without a reproduction, a "fix" is only a guess that nobody can check.
Step 1: Make the failure repeatable
Start by writing down exactly how you triggered the failure. Record the command, the input, and the state the program was in. Then run it again and see whether the same error appears.
Three outcomes are possible:
- The failure happens every time with the same error. This is the easy case. Continue to shrinking.
- The failure happens sometimes. The cause is something that changes between runs.
- The failure does not happen again. The original run depended on something you did not record.
Intermittent failures
Intermittent failures usually come from a short list of sources. Check these before you ask for help, and tell the assistant which ones you ruled out.
| Source of variation | How to pin it down |
|---|---|
| Random numbers | Set the seed, for example `random.seed(1234)`. |
| Current time or date | Pass the time in as a parameter, or freeze it in the test. |
| Test order or shared state | Run the failing test alone, then run the whole suite, and compare. |
| Concurrency (threads, async tasks) | Reduce to one worker, then add workers back. |
| External services or network | Replace the call with a recorded response or a stub. |
| Environment (versions, env variables, OS) | Record versions and variables, then try a clean virtual environment. |
If the failure only appears in the full test suite and not when the test runs alone, shared state is the usual cause. One test leaves data behind that another test reads. That fact is very useful to the assistant, so include it.
Capture the exact conditions
Before you change anything, collect the facts that define the failure:
- The exact command you ran.
- The exact input, copied rather than described.
- The language and library versions, such as
python --versionandpip freeze. - The git commit you were on, from
git rev-parse --short HEAD. - Whether the failure is new. If it worked last week,
git logandgit bisectcan find the commit that broke it.
Step 2: Shrink it to a minimal example
A minimal example is the smallest piece of code that still shows the same failure. "Same failure" matters: the error type and the failing behavior must match the original. If shrinking changes the error, you have started debugging a different problem.
Shrinking works by removal. You delete things and rerun after each deletion. If the failure survives, the deleted part was irrelevant. If the failure disappears, you have just found something that matters, so put it back.
What to remove
Work from the outside in:
- Inputs. Replace a 10,000-row file with the three rows that matter. Replace a large dictionary with the two keys that are read.
- Callers. If the error occurs inside a function, call that function directly with the failing arguments instead of starting the whole application.
- Dependencies. Replace database calls, HTTP requests, and file reads with hard-coded values.
- Unrelated code. Delete features, logging, configuration, and helper functions that the failing path never touches.
- Third-party libraries. If the failure still occurs without a library, remove the library. If it only occurs with it, you may have found a library issue.
A worked example
Suppose a report script crashes in production with a long traceback that passes through a web framework, a database layer, and a formatting function. Following the traceback, the deepest frame in your own code is in a function that computes an average. You pull that function out and call it with the same data the report used. For the failing report, that data was an empty list because no records matched the filter.
The reduced version is:
def average(values):
return sum(values) / len(values)
print(average([]))This is about four lines instead of the whole application. It fails with the same error type as the original:
Traceback (most recent call last):
File "stats.py", line 5, in <module>
print(average([]))
File "stats.py", line 2, in average
return sum(values) / len(values)
ZeroDivisionError: division by zeroThe last line gives the error type, and the frame above it gives the failing line inside average. Notice what the shrinking taught you. The bug is not in the web framework, the database layer, or the formatting. It is that average has no defined behavior for empty input, and the real problem upstream is that a filter returned no records. Both facts came from shrinking, and neither would have been obvious from the original traceback.
Check that the reduced example is faithful
After shrinking, confirm three things:
- It fails with the same error type and message as the original.
- It fails at the same kind of location, for example inside the same function.
- It runs on its own, without needing files or services that only exist on your machine.
If the original failure was ZeroDivisionError and your reduced one is TypeError, you have not reproduced the bug. You have created a new one.
Turn the reproduction into a test
A script you run by hand works, but a test is better because it is repeatable and can be kept. You can write it before you know the fix. It should fail now and pass after the fix.
import pytest
from stats import average
def test_average_of_empty_list_raises():
with pytest.raises(ValueError):
average([])Run it now and it fails, because the current code raises ZeroDivisionError, not ValueError. That failing test is your reproduction in executable form. Later chapters cover verifying and keeping the test. For now, the important point is that you have a command that reports pass or fail, which is what makes the rest of the workflow checkable.
Run it with:
python -m pytest -q test_stats.pyIf the failure came from a bug report with a specific input, put that input in the test. If it came from a crash in a larger program, use the reduced call from your minimal example.
Common mistakes
- Shrinking by rewriting. If you rewrite the code in your own words instead of deleting from the original, you can accidentally remove the bug. Always cut from the real code and rerun.
- Removing several things at once. If the failure disappears, you do not know which removal mattered. Remove one piece at a time, or use halving: remove half, and if the failure disappears, restore it and remove the other half.
- Changing the error while shrinking. Compare the error message each time. A different error means a different bug.
- Fixing while shrinking. Do not edit logic during this step. You are narrowing the failure, not solving it.
- Giving up on the intermittent case. "It fails sometimes" is not a reproduction. Find what varies, fix it in place, and then reproduce.
- Reducing past usefulness. If the minimal example uses a made-up value that real data never produces, it may not match the real failure. Keep data that is realistic in shape.
Letting the assistant help you shrink
You can ask an assistant to help with shrinking, but treat its output as a proposal. Paste the failing code and the error, and ask for a smaller version that produces the same error. Then run it yourself. If the error differs from the original, reject it.
This works well when you give the assistant a clear acceptance check:
Here is a 60-line script that raises ZeroDivisionError at line 41.
Reduce it to the smallest script that still raises the same error.
Do not change the error type. I will run your version and compare.The check you perform, not the assistant's confidence, decides whether the reduction is valid.
What to bring to the next step
When this step is done, you should have:
- A command that triggers the failure every time.
- A minimal example, ideally as a failing test.
- The exact error output from that minimal example.
- Notes on the environment and on what you ruled out.
This package is the raw material for the next chapter, where you decide which context the assistant needs.
Exercise
A test passes when you run it alone but fails when you run the whole suite. You try to shrink the failing test by deleting code from it, but it keeps passing. What is the most likely cause, and what should you do before asking an assistant for help?
Show answer
The most likely cause is shared state or test-order dependence: another test changes global data, a file, or a database row that the failing test reads. Deleting code from the failing test will not help because the cause lives in a different test. Instead, run the suite with the failing test and bisect the other tests (run half of them with it, then the other half) until you find the one that triggers the failure. Then give the assistant that pair of tests, the order they ran in, and the error output.
Exercise
You shrink a crashing script and your reduced version now raises a TypeError, while the original raised a ZeroDivisionError. Is the reduced example valid? What should you do?
Show answer
No. A different error type means the reduction changed the problem, probably by removing or altering something the original depended on, such as the input type. Restore the last piece you removed, confirm the original error returns, and continue shrinking one piece at a time while comparing the error message after each rerun.