Sub topic 5
Handling nondeterministic output
This chapter assumes you can run the pytest golden-dataset suite from the earlier chapters, including the deterministic checks for format, content, and constraints. It covers what to do when the same input gives different outputs on different runs, so your suite neither fails randomly nor hides real regressions.
Why the same prompt gives different answers
A conventional unit test calls a function and compares the result with a fixed expectation. An LLM call can return a different string each time. Three sources cause this:
- Sampling. The model picks each token from a probability distribution. A higher temperature or top-p value spreads that choice out.
- Infrastructure. Even at temperature 0, results can vary. Batching, floating-point order of operations, and routing between hardware or model replicas can all change which token ranks first when two candidates are close.
- Input you did not control. Timestamps, retrieved documents in a different order, and tool results that change over time all alter the prompt itself.
Setting temperature to 0 shrinks the variance but does not remove it. Some APIs offer a seed parameter, but the provider usually documents it as best effort. Some models do not let you set temperature at all. Design the suite as if variance will always be present.
Reduce variance first, then measure what is left
Do the cheap things before you add repeated runs:
- Use the lowest temperature the feature allows in tests. Test with the production parameters if they differ, but also keep one low-variance run to separate parameter effects from prompt effects.
- Pass a seed where the API supports it.
- Use structured output or a JSON schema mode if your provider offers one. This removes a whole class of format failures.
- Freeze external inputs. Stub the clock, and feed retrieval and tool steps fixed fixtures in tests.
- Write checks on properties, not exact text. "Contains the key
category" survives rewording. "Equals this sentence" does not.
Normalize before you compare. Strip whitespace, lowercase text, and parse JSON instead of comparing raw strings. The deterministic check in the first code example already does this by calling json.loads and comparing keys as sets.
Repeat each case and aggregate
After you reduce variance, the remaining randomness is something you measure. Run each case several times and record how many trials pass. The result for one case is a pass rate, not a single pass or fail.
import json
import random
from dataclasses import dataclass
@dataclass
class CaseResult:
case_id: str
passes: int
trials: int
@property
def rate(self):
return self.passes / self.trials
def check_output(case, output):
try:
data = json.loads(output)
except json.JSONDecodeError:
return False
if not isinstance(data, dict):
return False
if not set(case["required_keys"]) <= set(data):
return False
return all(p.lower() in output.lower() for p in case.get("must_contain", []))
def run_case(case, run_prompt, trials=5):
passes = sum(
1 for _ in range(trials) if check_output(case, run_prompt(case["input"]))
)
return CaseResult(case["id"], passes, trials)
def classify(result, min_rate=0.8):
if result.passes == result.trials:
return "stable"
if result.rate >= min_rate:
return "flaky"
return "failing"
if __name__ == "__main__":
random.seed(7)
def fake_model(prompt):
# Simulates a model that sometimes refuses instead of returning JSON.
if random.random() < 0.15:
return "Sorry, I cannot help with that."
return json.dumps({"summary": "Refund issued", "category": "billing"})
case = {
"id": "refund-01",
"input": "Customer asks for a refund",
"required_keys": ["summary", "category"],
"must_contain": ["refund"],
}
result = run_case(case, fake_model, trials=10)
print(result, classify(result))The three labels in classify are useful in reports:
- stable: every trial passed.
- flaky: most trials passed. The behavior is real but unreliable, and a prompt change may be able to fix it.
- failing: most trials failed. Treat this as a defect.
Replace fake_model with your own run_prompt wrapper to use this against the real model.
Choose a per-case rule
Once you have trial counts, you need a rule that decides whether a case passes. Each option trades sensitivity against noise.
| Rule | Behavior | Risk |
|---|---|---|
| All trials must pass | Strictest. Catches any instability. | A case that is 95% reliable fails often by chance. |
| Majority of trials must pass | Tolerates occasional misses. | Can hide a drop from 100% to 60%. |
| Report the rate, gate on the suite | Keeps all the information. | Needs a good suite-level threshold. |
The arithmetic explains why "all trials must pass" is fragile. Suppose a case passes 95% of the time. With 3 trials, the chance that all pass is 0.95³, about 86%. This case fails the gate roughly one run in seven even though nothing changed. With a 2-of-3 rule, the chance of passing is 3(0.95²)(0.05) + 0.95³, about 99.3%.
A practical default is to gate on the suite pass rate. Mark the few cases that must never fail, such as safety constraints, as "all trials must pass". Keep a majority rule or a plain rate for the rest.
Know your noise before you set a tolerance
The suite-level check from the golden dataset chapter used a tolerance of 0.02. That number only makes sense if it is larger than the run-to-run noise of an unchanged system. Estimate it with an A/A test: run the same prompt and model against the same dataset several times and look at how much the suite pass rate moves.
import statistics
def noise_band(rates, k=2.0):
"""Return mean and k standard deviations for repeated A/A suite runs."""
return statistics.mean(rates), k * statistics.stdev(rates)
aa_rates = [0.91, 0.89, 0.92, 0.90, 0.88, 0.91]
mean, band = noise_band(aa_rates)
print(f"mean={mean:.3f}, 2-sigma band={band:.3f}")For these six runs the band is about 0.03, which is larger than 0.02. A gate with a 0.02 tolerance would fail by chance on this suite. Either raise the tolerance to cover the band or reduce the noise.
You can also reason about noise from the sample size. If the true pass rate is 90% and you score 100 independent samples, the standard deviation of the observed rate is √(0.9 × 0.1 / 100) = 0.03. Running 3 trials per case on 100 cases gives 300 samples and a standard deviation of about 0.017. More trials narrow the band, but the trials of one case are correlated, so the real gain is smaller than the formula suggests. More distinct cases help more than more repeats of the same case.
Do not retry until green
A common shortcut for flaky tests is a retry plugin that reruns a failed test until it passes. Do not use it for regression tests. If a case fails 40% of the time and you retry up to three times, it shows as passing about 78% of the time, and the report records nothing about the instability. A real regression turns into a quiet pass.
Use repeats and retries for different purposes:
- Repeated trials are planned. You always run
nof them and report all outcomes. - Retries on infrastructure errors are acceptable if they apply only to timeouts, rate limits, and 5xx responses, and if you log them. A timeout says nothing about output quality, so exclude it from the trial count or count it separately.
Keep a distinction in your results between an error (no output was produced) and a failure (output was produced and broke a check). Mixing them makes a provider outage look like a prompt regression.
Common mistakes
- Comparing raw strings. Parse, normalize, and check properties.
- Treating one failed run as a regression. Rerun the failing cases with more trials before you act. If the rate is within the noise band, it is noise.
- Treating one passing run as proof. A single success on a case that is 70% reliable proves very little.
- Raising the tolerance until the gate stops failing. Set it from A/A measurements and keep the number in version control with a note on how you got it.
- Ignoring cost.
ntrials multiply your API spend and runtime byn. Run few trials on pull requests and more on a schedule. The later chapter on test tiers covers this. - Using high temperature in tests without a reason. Test with production settings, but use extra trials to pay for the variance.
Exercise
A case passes 90% of the time when nothing has changed. You run 3 trials and require all 3 to pass. About how often does the case fail the gate by chance, and what rule would reduce that?
Show answer
All three pass with probability 0.9³ = 0.729, so the case fails the gate about 27% of the time. A 2-of-3 rule passes with probability 3(0.9²)(0.1) + 0.9³ = 0.243 + 0.729 = 0.972, so it fails about 3% of the time. Alternatively, report the case's pass rate and gate on the suite-level rate.
Exercise
Your A/A runs of an unchanged suite give pass rates of 0.86, 0.90, 0.88, 0.92, and 0.89. A teammate proposes a regression tolerance of 0.01. What is wrong with that, and what do you do?
Show answer
The runs vary by several points on their own (from 0.86 to 0.92), so a 0.01 tolerance would fail on noise alone. Compute the standard deviation of these rates (about 0.023), set the tolerance near two standard deviations or higher, or reduce the noise first with lower temperature, a seed, structured output, more distinct cases, or more trials. Record how you chose the value.