Sub topic 11
Refining output with feedback
A first draft from an assistant is a starting point. This chapter covers how to turn a draft into something you would merge. It assumes you can run pytest, read a failing test report, and use python -m doctest. It also assumes you have used an assistant in a multi-turn chat and that you have read the earlier chapters on prompts and on reviewing tests.
Why the first draft is rarely the last
The assistant predicts plausible output from the context you gave it. It does not run the code it writes. A draft can therefore look complete and still have a wrong import path, a missing boundary case, or a docstring that describes behavior the code does not have.
Refinement means feeding evidence about the draft back to the assistant so the next draft is better. The key word is evidence. "Make the tests better" gives the assistant nothing to act on. "These three mutations of the function pass your tests" tells it exactly what to fix.
The refinement loop
Each round has the same shape: run the draft, observe, report, and ask for a targeted change. You decide when the loop ends.
The checks sit outside the assistant. Test runs, doctest, linters, and your own review are the sources of truth. The assistant's statement that it fixed something is not.
Feedback that carries information
Feedback is useful in proportion to how much concrete evidence it contains. The table lists common kinds, from weakest to strongest.
| Feedback | Example | Quality |
|---|---|---|
| Vague opinion | "These tests feel thin." | Weak. The assistant guesses what to change. |
| Named gap | "No test covers price equal to 0." | Good. Points to one case. |
| Failure output | The pytest traceback, pasted in full | Strong. Shows the actual error. |
| Survived mutation | "Changing `price < 0` to `price <= 0` still passes." | Strong. Proves a specific weakness. |
| Constraint restated | "Do not edit `pricing.py`. Only change the test file." | Needed whenever the assistant drifts. |
Paste the full traceback, not a paraphrase. Include the command you ran and the versions that matter, such as the Python and pytest versions. If the assistant needs the function again because the conversation is long, paste it again.
Worked example: tightening tests for `apply_discount`
Earlier chapters generated this test file for apply_discount. It looks fine and passes:
import pytest
from pricing import apply_discount
@pytest.mark.parametrize(
"price, percent, expected",
[
(100, 10, 90.0),
(80, 25, 60.0),
(19.99, 0, 19.99),
(50, 100, 0.0),
],
)
def test_apply_discount_returns_expected_price(price, percent, expected):
assert apply_discount(price, percent) == expected
@pytest.mark.parametrize("price, percent", [(-1, 10), (10, -5), (10, 101)])
def test_apply_discount_rejects_invalid_input(price, percent):
with pytest.raises(ValueError):
apply_discount(price, percent)Passing tells you little. To see how much the tests would notice, break the function on purpose and check that the tests fail. This is a small mutation check. Save this as mutation_check.py next to pricing.py and run it from the project root.
import subprocess
import sys
from pathlib import Path
SOURCE = Path("pricing.py")
# Each pair is (original text, broken text). Every change alters the file
# length, so Python does not reuse stale cached bytecode between runs.
MUTATIONS = [
("price < 0", "price <= 0"),
("0 <= percent <= 100", "-1 <= percent <= 100"),
("0 <= percent <= 100", "0 <= percent < 100"),
("1 - percent / 100", "1 - percent / 10"),
("round(price * (1 - percent / 100), 2)", "price * (1 - percent / 100)"),
]
def tests_pass() -> bool:
result = subprocess.run(
[sys.executable, "-m", "pytest", "-q", "-x", "tests"],
capture_output=True,
)
return result.returncode == 0
def main() -> int:
original = SOURCE.read_text()
survivors = []
try:
for old, new in MUTATIONS:
if old not in original:
raise SystemExit(f"Mutation target not found: {old!r}")
SOURCE.write_text(original.replace(old, new, 1))
if tests_pass():
survivors.append((old, new))
finally:
SOURCE.write_text(original)
for old, new in survivors:
print(f"SURVIVED: {old!r} -> {new!r}")
print(f"{len(MUTATIONS) - len(survivors)} of {len(MUTATIONS)} mutations caught")
return 1 if survivors else 0
if __name__ == "__main__":
sys.exit(main())The script restores the original file in a finally block. Even so, commit your work first so Git can recover the file if the run is interrupted harshly.
Run against the draft above, three mutations survive:
price < 0becameprice <= 0. No test uses a price of exactly 0.- The lower percent bound became -1. No test uses a negative percent between -1 and 0.
- The
roundcall was removed. Every expected value in the draft happens to be exact, so rounding is never exercised.
Now turn that evidence into feedback:
Your tests for apply_discount in tests/test_pricing.py pass, but a mutation
check shows three weaknesses. Each change below still passes your tests:
1. `price < 0` changed to `price <= 0` (price 0 is never tested)
2. `0 <= percent` changed to `-1 <= percent` (no negative percent above -1)
3. The round(..., 2) call removed (no expected value needs rounding)
Update only tests/test_pricing.py. Add cases that fail under each mutation.
Derive expected values from the docstring, not by re-implementing the
function. Check that the price errors and percent errors are distinguished
by message. Do not modify pricing.py.The reply should look like the following. Treat it as a draft and review it, because the assistant can still get an expected value wrong.
import pytest
from pricing import apply_discount
@pytest.mark.parametrize(
"price, percent, expected",
[
(100, 10, 90.0),
(80, 25, 60.0),
(19.99, 0, 19.99),
(50, 100, 0.0),
(0, 10, 0.0),
(9.99, 15, 8.49),
],
)
def test_apply_discount_returns_expected_price(price, percent, expected):
assert apply_discount(price, percent) == expected
@pytest.mark.parametrize("price", [-1, -0.01])
def test_apply_discount_rejects_negative_price(price):
with pytest.raises(ValueError, match="price"):
apply_discount(price, 10)
@pytest.mark.parametrize("percent", [-5, -0.01, 101, 100.01])
def test_apply_discount_rejects_percent_out_of_range(percent):
with pytest.raises(ValueError, match="percent"):
apply_discount(10, percent)The case (9.99, 15, 8.49) works because 9.99 × 0.85 is about 8.4915, so only a function that rounds to two decimals returns 8.49. Rerun mutation_check.py. All five mutations should now be caught. If one still survives, paste that line back and repeat.
Refining documentation
The same loop works for docstrings, with different checks. Ask for an Examples section, then run python -m doctest -v pricing.py. A failing example is precise evidence: it shows the call, the expected output, and the actual output. Paste that block into the next prompt.
Feedback for docs also includes things the tools cannot see. If the docstring says "Raises ValueError for invalid input" but does not say which inputs, name the gap yourself: "State the exact conditions, and say that 0 and 100 are valid percents." Check each claim in the revised text against the code, as covered in the previous chapter on verifying documentation.
Common errors
- Fixing the test to match a bug. When a generated test fails, decide first whether the test or the code is wrong. If you paste the failure and say "fix this", the assistant often edits the expectation until it passes, which hides a real bug. State which side is authoritative: "The docstring is correct. Do not change expected values."
- Letting the assistant edit the code under test. A revision that quietly changes
pricing.pymakes the tests pass by redefining the behavior. Restate "only change the test file" in every round, and checkgit difffor files you did not expect. - Drift in long conversations. After many rounds, early constraints such as the framework, the file path, and the no-tautology rule can fade. If answers start ignoring them, restate the full requirements in a fresh message, or start a new conversation with the current file contents.
- Piling on many requests at once. One message asking for new cases, a rename, and a style change makes it hard to see which edit caused a regression. Keep each round to one theme.
- Trusting a self-report. "I verified all edge cases" is text, not a test run. Run the checks yourself.
- Never stopping. Each round costs your time and adds code to maintain. Chasing every surviving mutation, including ones that represent no real behavior, produces bloated suites.
Knowing when to stop
Stop when these hold:
- The tests pass on the current code, and the mutation check or an equivalent review finds no gap you care about.
- Every assertion traces back to a documented rule, not to the function's current output.
- Doctest passes, and each claim in the docstring matches the code.
- You can explain each test to a reviewer.
If two rounds in a row produce no meaningful improvement, change tactics. Write the awkward test yourself and ask the assistant to extend it, or split the task into smaller functions that are easier to specify.
Exercise
A generated test for apply_discount fails with assert 8.5 == 8.49 for the input (9.99, 15). Describe how you would decide whether to change the test or the code, and write the feedback message you would send.
Show answer
First compute the expected value from the documented contract: 9.99 × 0.85 = 8.4915, which rounds to 8.49 at two decimals, so the expected value 8.49 is right and the code returned 8.5. The failure points to a bug in the code, or to a stale copy of it (for example, rounding to one decimal). Check the function before touching the test. A good message: "Test testapplydiscountreturnsexpected_price fails with assert 8.5 == 8.49 for (9.99, 15). The docstring says the result is rounded to two decimals, so 8.49 is correct. Do not change the expected value or the test. Explain what in pricing.py could produce 8.5." Then fix the code yourself or review the assistant's proposed fix.
Exercise
You run the mutation check and the mutation 0 <= percent <= 100 to 0 <= percent < 100 survives. What does this tell you, and what test case closes the gap?
Show answer
No test sends percent 100 to the function and expects a valid result. With the mutation, 100 raises ValueError, and nothing checks that. Add a valid case with percent exactly 100, such as (50, 100, 0.0) in the parametrized table. The first draft in this chapter already has that case, so the mutation would be caught there. Any suite that lacks it needs it added. Also check that the invalid cases include a value just above 100, such as 100.01, to pin the upper boundary from the other side.