Sub topic 9
Regression testing prompt changes
This chapter assumes you can render a template with named variables, store it as a versioned file such as prompts/summarize/1.2.0.yaml, and read short Python. You don't need a testing framework. Everything here runs with the standard library.
Why prompts regress
A regression is a case that worked before a change and fails after it. Prompts regress easily because a small edit can shift behavior far from the line you touched. Suppose you add "answer in one sentence if the text is short" to fix one complaint. The same sentence can make the model drop dates from meeting notes, or stop following the requested style.
Nobody sees this in code review. The diff is a few words of English, and nothing fails to compile. The only way to find out is to run the new version on inputs where you already know what a good answer looks like.
A prompt regression test set is the small collection of inputs and expectations you run against every new version before release. It plays the same role as a unit test suite, with one difference. The model's output is text that varies between runs, so the checks must tolerate variation while still catching real breakage.
The shape of a test case
Each case has an input for the template variables and a description of acceptable output. Don't store the one exact expected output. Model text changes in wording from run to run, so an exact-match test fails for reasons that don't matter.
Store properties of a good answer instead:
| Check | Example | What it catches |
|---|---|---|
| Must contain | The word "Friday" appears | Dropped facts |
| Must not contain | No "As an AI" phrasing | Unwanted boilerplate |
| Length limit | At most 30 words | Ignored length instructions |
| Format | Output parses as JSON | Broken structured output |
| Judge-based | A second model rates faithfulness | Qualities you can't check with code |
Start with the first four. They are cheap, fast, and deterministic, which means the same output always gets the same verdict. Judge-based checks are useful, but they add cost and their own variability. Add them only when string checks can't express the property you care about.
Where cases come from
The best cases come from real failures. Each time a prompt produces a bad output in testing or production, add the input and a check that would have caught it. Over time the set records the mistakes your prompt has made. Also include a few ordinary inputs, plus edge cases such as empty text, very long text, and text in another language.
Twenty to fifty cases are enough to start. A set you can run in under a minute gets run on every change. A set that takes an hour gets skipped.
A minimal suite
The first version follows the pattern from this tutorial's earlier examples. It takes a generate function, which is any callable that accepts a prompt version and the input text and returns the model's output. Passing the function in keeps the suite independent of any provider's API. To make the example runnable, the code below uses a stand-in fake_generate that mimics two prompt versions.
cases = [
{"text": "Cats sleep a lot.", "must_contain": ["cat"]},
{"text": "The meeting moved to Friday.", "must_contain": ["Friday"]},
]
def run_suite(generate, prompt_version):
failures = []
for case in cases:
output = generate(prompt_version, case["text"])
for word in case["must_contain"]:
if word.lower() not in output.lower():
failures.append((case["text"], word))
return failures
def fake_generate(prompt_version, text):
if prompt_version == "1.2.0":
return f"Summary: {text}"
return "Short summary."
print(run_suite(fake_generate, "1.2.0"))
print(run_suite(fake_generate, "1.3.0"))The first call prints [], so every check passes. The second prints both failures, because the stand-in for version 1.3.0 ignores the input entirely. In a real project, fake_generate becomes a function that loads the pinned version file, renders the template, and calls your model.
The comparison is case-insensitive on purpose. "Friday" and "friday" are the same fact, and a test that fails on capitalization teaches people to ignore failures.
Comparing two versions
A pass or fail on the new version alone isn't enough. If 1.2.0 already fails a case, a failure in 1.3.0 isn't a regression. It's a known weakness. What you want to know is which cases got worse and which got better. That means running both versions on the same cases.
The next version of the suite adds three things. Each case gets an id so reports are readable. The checks go into a separate function and cover forbidden words and length. Each case is also run several times, because a single sample can pass or fail by luck.
cases = [
{"id": "cat-short", "text": "Cats sleep a lot.",
"must_contain": ["cat"], "max_words": 10},
{"id": "meeting-date", "text": "The meeting moved to Friday.",
"must_contain": ["Friday"], "max_words": 10},
]
def check(output, case):
problems = []
lowered = output.lower()
for word in case.get("must_contain", []):
if word.lower() not in lowered:
problems.append(f"missing '{word}'")
for word in case.get("must_not_contain", []):
if word.lower() in lowered:
problems.append(f"forbidden '{word}'")
max_words = case.get("max_words")
if max_words is not None and len(output.split()) > max_words:
problems.append(f"over {max_words} words")
return problems
def run_cases(generate, version, cases, repeats=3):
results = {}
for case in cases:
failed_runs = 0
for _ in range(repeats):
output = generate(version, case["text"])
if check(output, case):
failed_runs += 1
results[case["id"]] = failed_runs
return results
def compare(generate, old, new, cases, repeats=3):
old_results = run_cases(generate, old, cases, repeats)
new_results = run_cases(generate, new, cases, repeats)
regressions = [c for c in new_results if new_results[c] > old_results[c]]
fixes = [c for c in new_results if new_results[c] < old_results[c]]
return regressions, fixes
def fake_generate(version, text):
if "Cats" in text:
return "Cats sleep a lot."
if version == "1.2.0":
return "Meeting moved to Friday."
return "The meeting changed."
print(compare(fake_generate, "1.2.0", "1.3.0", cases))This prints (['meeting-date'], []). The new version lost the day of the week, so meeting-date is a regression and nothing improved. The report names the case, which tells the author where to look.
Handling nondeterminism
Models don't return identical text on every call, especially at a nonzero temperature. Three practices keep your suite useful anyway.
- Fix the settings for tests. Use the same model and a low temperature, ideally 0, for every run. Record these settings with the results, because a change in model or temperature can look like a change in the prompt.
- Repeat each case. The
repeatsargument above runs each case several times and counts failures. A case that fails 1 run in 3 is flakier than one that fails 3 of 3, and the report should show that difference. - Set a tolerance. Decide in advance what counts as a regression. For example, any case whose failure count rises is flagged, and the release is blocked if more than one case regresses. A rule written beforehand stops the team from arguing about each result.
Even at temperature 0, some providers don't guarantee identical outputs. Treat the suite as a signal and not as proof. A clean run means "no regressions found in these cases", not "no regressions".
Where the suite fits in the change process
The suite should run whenever a prompt file changes. It should also run when the model name or its settings change, because those change behavior just as a prompt edit does. The diagram shows the loop.
The comparison output belongs in the pull request, next to the changelog entry from the version file. A reviewer can then see both what the author intended ("ask for a one-sentence answer when the text is short") and what happened on the cases. Reviewing and releasing the version are covered in the next chapter.
Keeping cases out of the code
Once the set grows past a handful of cases, move it out of the Python file. A YAML or JSON file, such as prompts/summarize/cases.yaml, can be reviewed and tracked in Git like the templates. Test cases for a prompt should sit beside the prompt they test, so that a prompt change and its new cases can go in one commit.
Add a case each time you fix a bug. If the fix and the case are committed together, the history shows what broke and the evidence that it was repaired.
Common errors
- Exact-match expectations. Comparing the whole output to a stored string fails on harmless rewording. Check properties instead.
- Checks too loose to fail. A
must_containof "the" passes almost anything. After writing a check, run it against a deliberately bad output and confirm it fails. - Checks too strict. Requiring the exact phrase "moved to Friday" rejects a correct answer such as "rescheduled for Friday". Test for the fact, here the word "Friday".
- Testing only the new version. Without the old version's results, you can't separate new failures from existing ones.
- A single sample per case. One run can pass by chance. Repeat cases, or at least rerun any case that fails.
- Stale cases. If the product's requirements change, update the cases in the same change. An outdated case that blocks releases will soon be ignored or deleted.
- Overfitting. If you tune a prompt until it passes these exact cases, it may do worse on inputs outside them. Keep a few cases aside that you don't use while editing, and check them only before release.
What the suite does not tell you
A passing suite means the new version did at least as well on your chosen cases. It doesn't measure overall quality, and it can't detect problems you didn't write a check for. Production logs, covered in a later chapter, fill part of that gap. They let you trace a bad output back to the prompt version that produced it, and then add a new case so that failure can't return unnoticed.
Exercise
In the comparison code, version 1.2.0 fails the case "long-text" in all 3 runs, and version 1.3.0 also fails it in all 3 runs. Does compare report a regression for it? Why is that the right behavior?
Show answer
No. compare flags a case only when the new version's failure count is higher than the old version's, and 3 is not greater than 3. The case is a known weakness that predates the change, so blocking the release for it would hide the cases that did get worse. It should still be tracked and fixed separately.
Exercise
Extend the check function with a must_match_format option that accepts a regular expression, and fails the output if re.search finds no match. Give the new lines of code and one case that uses it to require an ISO date such as 2026-11-27 in the output.
Show answer
Add import re at the top of the file. Inside check, before return problems, add:
pattern = case.get("mustmatchformat")
if pattern is not None and not re.search(pattern, output):
problems.append(f"no match for {pattern}")
A case that uses it:
{"id": "iso-date", "text": "The launch is on 27 November 2026.",
"mustmatchformat": r"\d{4}-\d{2}-\d{2}"}
The check fails any output that doesn't contain a date written as four digits, two digits, and two digits separated by hyphens.