Sub topic 6
Generating synthetic cases safely
Synthetic cases are test cases written by a language model instead of collected from users or written by experts. They are cheap and fast to produce. They are also easy to misuse, because a model that writes the questions tends to write questions it can already answer. This chapter shows how to use generation to fill gaps in your dataset without letting it distort your scores.
What you need before this chapter
This chapter assumes you have read the earlier chapters on the test case schema and on covering the input space with tagged slices. You should also be comfortable with these skills:
- Reading and writing JSONL in Python.
- Calling an LLM through a function that takes a prompt string and returns a string.
- The idea of a slice, which is a tag such as
returnsoradversarialthat groups related cases.
When synthetic data helps and when it hurts
Use synthetic generation when a slice is under-covered and real examples are scarce or slow to collect. Typical cases are rare edge inputs, adversarial phrasings, and variations of a known failure.
Do not use it as your only source. A generator has its own habits. It writes polite, grammatical, well-formed inputs. Real users write fragments, typos, mixed languages, and pasted email threads. If every case in a slice comes from one model, the slice measures how well your app handles that model's style.
A second risk is circularity. If the same model family generates the cases, writes the reference answers, and is then graded by a judge, the errors can agree with each other. A wrong reference answer will match a wrong output, and the score will look good.
The rule of thumb is that synthetic cases extend a dataset built from real traffic and expert writing. They do not replace it.
Generate from slices, not from nothing
Asking a model for "100 test questions about our app" produces many near-duplicates concentrated around the most obvious topics. Generate per slice instead. For each (tag, difficulty) pair you want to grow, give the model:
- The slice definition in one or two sentences.
- A few real seed cases from that slice, with their references.
- The number of cases to produce and the exact output format.
- Instructions about what should vary, such as length, tone, missing information, or a trap in the wording.
Seeds from real logs pull the output toward real phrasing. Asking for specific variation axes pushes the output away from copies of the seeds.
A generation and filtering script
The script below generates candidates for one slice, validates them, drops duplicates, and attaches provenance. The llm argument is any function that maps a prompt string to a reply string. A fake one is included so the code runs without an API key.
import hashlib
import json
import re
def normalize(text):
return re.sub(r"\W+", " ", text.lower()).strip()
def jaccard(a, b):
ta, tb = set(normalize(a).split()), set(normalize(b).split())
union = ta | tb
return len(ta & tb) / len(union) if union else 0.0
def make_prompt(tag, difficulty, seeds, n):
examples = "\n".join(json.dumps({"input": s["input"], "reference": s["reference"]}) for s in seeds)
return (
f"You write test cases for a customer-support assistant.\n"
f"Slice: {tag}. Difficulty: {difficulty}.\n"
f"Real examples:\n{examples}\n"
f"Write {n} new cases. Vary length, tone, and missing details. "
f"Do not copy the examples.\n"
f'Reply with only a JSON list of objects with keys "input" and "reference".'
)
def parse_candidates(reply):
try:
data = json.loads(reply)
except json.JSONDecodeError:
return []
return data if isinstance(data, list) else []
def check(candidate, existing_inputs, threshold=0.8):
if not isinstance(candidate, dict):
return "invalid"
inp, ref = candidate.get("input"), candidate.get("reference")
if not isinstance(inp, str) or not isinstance(ref, str):
return "invalid"
if not inp.strip() or not ref.strip():
return "invalid"
if any(jaccard(inp, e) >= threshold for e in existing_inputs):
return "duplicate"
return None
def generate_for_slice(llm, tag, difficulty, seeds, n, existing_inputs, generator_name):
reply = llm(make_prompt(tag, difficulty, seeds, n))
seen = list(existing_inputs)
accepted, rejected = [], {}
for cand in parse_candidates(reply):
reason = check(cand, seen)
if reason:
rejected[reason] = rejected.get(reason, 0) + 1
continue
digest = hashlib.sha256(normalize(cand["input"]).encode("utf-8")).hexdigest()[:8]
accepted.append({
"id": f"syn-{tag}-{digest}",
"input": cand["input"].strip(),
"reference": cand["reference"].strip(),
"tags": [tag],
"source": "synthetic",
"difficulty": difficulty,
"generator": generator_name,
"review": "pending",
})
seen.append(cand["input"])
return accepted, rejected
def fake_llm(prompt):
return json.dumps([
{"input": "Can I return headphones after 31 days?",
"reference": "No. Returns are accepted within 30 days of delivery."},
{"input": "Can I return a laptop after 45 days?",
"reference": "No. Returns are accepted within 30 days of delivery."},
{"input": "", "reference": "No."},
])
seeds = [{
"input": "Can I return a laptop after 45 days?",
"reference": "No. Returns are accepted within 30 days of delivery.",
}]
cases, rejected = generate_for_slice(
fake_llm, "returns", "easy", seeds, 3,
existing_inputs=[s["input"] for s in seeds],
generator_name="fake-llm-v0",
)
print(len(cases), rejected)
print(cases[0]["id"], cases[0]["review"])Running it prints 1 {'duplicate': 1, 'invalid': 1}, followed by the id of the one accepted case and pending.
Three design choices in this script matter:
- Content-derived ids. The id comes from a hash of the normalized input. Regenerating the same case yields the same id, so the duplicate-id check from the loader still works. Ids also stay stable if the dataset is rebuilt.
- Provenance fields.
source,generator, andreviewlet you filter synthetic cases out of a report later. Without them you cannot tell afterward which cases a model wrote. - Pending review. Nothing synthetic is treated as ground truth until a person has looked at it.
Filter before you trust
Generation output goes through several gates before it enters the dataset.
- Schema validation. Reject malformed JSON, missing fields, and empty strings. The script above does this.
- Deduplication against everything. Compare each candidate with the seeds, the existing dataset, and earlier candidates in the same batch. Token overlap is a cheap start. Embedding similarity catches paraphrases that share few words, at the cost of an extra model and a threshold to tune.
- Leakage check. If you plan to use some real cases as a held-out test set, make sure no generated case is a near-copy of a test case. A generated paraphrase of a test case in the dev set lets you tune against the test set without noticing.
- Reference verification. The generator's reference answer is a draft. A person should check a sample, and every case in a high-stakes slice. Check the facts against your policy documents, not against your own expectations.
- Realism check. Read twenty random cases. If they all sound like the same writer, the slice needs more real data or more varied prompts.
Failure modes and fixes
| Problem | Symptom | Fix |
|---|---|---|
| Low diversity | Many cases share the same opening words or structure | Generate per slice, add explicit variation axes, deduplicate by similarity |
| Wrong references | App fails cases that a human then judges correct | Human review of references, using source documents |
| Too easy | The slice scores near 100% on the first run | Ask for adversarial variants, and keep cases where a baseline model fails |
| Self-preference | Scores rise when the generator and the app use the same model | Use a different family for generation |
| Test contamination | Generated cases resemble held-out cases | Run the leakage check against the test set before merging |
| Unreal distribution | Synthetic slice scores differ widely from real traffic | Compare against real cases and keep real data as the main signal |
Keep synthetic and real cases separate in reports
Because every synthetic case carries source: "synthetic", you can report two numbers for a slice, one for real cases and one for synthetic ones. If the synthetic score is much higher than the real score, the synthetic cases are too easy or too close to your seeds. If it is much lower, the references may be wrong. Either gap tells you to inspect the data before you trust the aggregate.
Assign splits with the same hash-based rule you use for everything else, applied to the id. Also keep generated paraphrases of one seed in the same split as that seed. Otherwise a variation of a dev case can land in test and leak information. A simple way to do this is to store a seed_id field and hash that instead of the case id.
How much to generate
A useful ratio is to keep real cases as the majority of any slice that production traffic can supply, and let synthetic cases fill the gaps. For rare slices, such as a refusal or a safety edge case, synthetic cases may be most of the slice. In that case, say so in the report and review all of them by hand.
Track the rejection rate per batch. A batch where most candidates are duplicates means the prompt has run out of variation. A batch where most are invalid means the prompt or the output format is wrong. Both are cheaper to notice from the counts than from reading the cases.
Exercise
Your returns slice has 12 real cases and 80 synthetic cases generated by the same model that powers the app. The app scores 97% on the slice. Name two risks with this number and one change for each.
Show answer
First risk: self-preference and circularity, because the app's own model wrote the inputs and references, so the cases are ones it handles well and the references may share its mistakes. Change: generate with a different model family and have a human verify the references, at least on a sample. Second risk: the slice is dominated by synthetic cases that are probably too easy and too similar to each other, so 97% says little about real traffic. Change: report real and synthetic scores separately, add more real cases from production logs, and add adversarial variants so the slice is not saturated.