Sub topic 3
Design the test case schema
This chapter assumes you can read and write JSONL, call an LLM app from Python, and compute a mean or proportion. The schema you pick here decides what you can measure later. Slicing, splitting, versioning, and grading all read fields from it, so it is worth designing before you collect many cases.
What a schema is for
A test case schema is the fixed set of fields every case in your dataset carries. Each field exists because some later step needs it.
- Running the app needs an input.
- Grading needs a reference answer or a rubric.
- Per-slice reporting needs tags.
- Splitting and deduplication need a stable id.
- Debugging and maintenance need provenance, meaning a record of where the case came from.
If a field has no consumer, leave it out. If a consumer has no field, you will end up rebuilding it from memory or from guesswork later.
A minimal case
Store the dataset as JSONL, which is one JSON object per line. Line-based files diff cleanly in version control, can be appended to without rewriting, and can be streamed.
One line of the dataset looks like this (shown on one line, as it appears in the file):
{"id": "refund-001", "input": "Can I return a laptop after 45 days?", "reference": "No. Returns are accepted within 30 days of delivery.", "tags": ["returns", "policy"], "source": "production_log", "difficulty": "easy"}| Field | Purpose | Used by |
|---|---|---|
| `id` | Stable unique name for the case | Splitting, dedup, result joins |
| `input` | What the app receives | Running the eval |
| `reference` | Expected answer | Grading |
| `tags` | Slice labels | Per-slice reporting |
| `source` | Where the case came from | Auditing, leakage checks |
| `difficulty` | Rough expected hardness | Analysis of results |
Field design decisions
The id
The id must be unique, stable, and meaningless to the model. Unique means no two cases share it. Stable means it never changes once assigned, even if you edit the case text. Later chapters hash the id to assign a dev or test split, so an id that changes would move a case between splits and quietly leak test data into development.
Use a readable prefix plus a counter, such as refund-001. Do not derive the id from the input text. Fixing a typo in the input would then change the id.
Reject duplicates when you load the file. This is cheap, and it catches copy-and-paste mistakes at once:
import json
def load_cases(path):
with open(path, encoding="utf-8") as f:
cases = [json.loads(line) for line in f if line.strip()]
ids = [c["id"] for c in cases]
assert len(ids) == len(set(ids)), "duplicate case ids"
return casesThe input
Decide whether input is a string or an object. A string is fine for a single-turn question answerer. Many apps need more: a conversation history, a system prompt variant, retrieved documents, a user locale, or tool state. In that case make input an object and keep its shape consistent:
{"id": "chat-014", "input": {"messages": [{"role": "user", "content": "Hi"}, {"role": "assistant", "content": "Hello! How can I help?"}, {"role": "user", "content": "Cancel my order"}], "locale": "en-US"}, "reference": null, "rubric": ["Asks for the order number", "Does not claim the order is already cancelled"], "tags": ["orders", "multi_turn"], "source": "expert_written", "difficulty": "medium"}Store everything the app needs to reproduce the run. If the app's behaviour depends on a field that is not in the case, the result cannot be repeated.
The reference and the rubric
A reference is one expected answer. It works when the answer is short and close to unique, such as a category label, a number, or a fixed policy statement. Many tasks have no single correct text. For those, store a rubric: a list of checkable statements that a good output satisfies, as in the chat-014 case above.
Allow one or the other per case, and make the choice explicit. A null reference with a non-empty rubric is a clear signal to the grader. A case with neither cannot be graded and should fail validation. Chapter 7 covers writing both in detail. Here you only need to reserve the fields.
Tags
Tags are the slice labels. They let you report accuracy for "returns" separately from "shipping", or for "multiturn" separately from "singleturn". Keep these rules:
- Use a controlled vocabulary, defined in one place, not free text.
refundandrefundswould otherwise become two slices. - Allow several tags per case. A case can be both
returnsandadversarial. - Tag along the dimensions that you expect to behave differently: topic, input style, language, and risk level.
Validate tags against the allowed list at load time, so typos fail loudly.
Provenance
Provenance fields record where a case came from and how it was made. Useful fields are source (for example production_log, expert_written, synthetic), a creation date, and the author or generator. You need them for three reasons.
- Synthetic cases often behave differently from real ones, so you want to report them separately.
- If a case turns out to be wrong, provenance tells you who or what to check.
- Cases drawn from production may contain private data, and
sourcetells you which ones to review.
Difficulty and other optional metadata
difficulty is a human guess, not a measurement. It is still useful for sanity checks: if easy cases fail more than hard ones, something is wrong with the labels or the grader. Treat any field like this as optional, and do not build decisions on it until you have checked it against real results.
Validate the schema in code
A schema that is only written in a document will drift. Enforce it with a function that runs every time the dataset loads. This version checks the rules from this chapter:
import json
REQUIRED = {"id", "input", "tags", "source"}
ALLOWED_TAGS = {"returns", "policy", "shipping", "orders", "multi_turn", "adversarial"}
ALLOWED_SOURCES = {"production_log", "expert_written", "synthetic"}
def validate_case(case):
errors = []
missing = REQUIRED - case.keys()
if missing:
errors.append(f"missing fields: {sorted(missing)}")
if not case.get("reference") and not case.get("rubric"):
errors.append("needs a reference or a rubric")
bad_tags = set(case.get("tags", [])) - ALLOWED_TAGS
if bad_tags:
errors.append(f"unknown tags: {sorted(bad_tags)}")
if case.get("source") not in ALLOWED_SOURCES:
errors.append(f"unknown source: {case.get('source')!r}")
return errors
def validate_file(path):
problems = {}
with open(path, encoding="utf-8") as f:
for line_no, line in enumerate(f, start=1):
if not line.strip():
continue
case = json.loads(line)
errors = validate_case(case)
if errors:
problems[case.get("id", f"line {line_no}")] = errors
return problemsRun validate_file in your test suite or as a pre-commit check. An empty dictionary means the file is clean.
How the schema feeds later steps
The following diagram shows which fields each later activity reads.
The grading step and the per-slice report can be seen together in this short example. It grades with exact match and groups results by tag:
from collections import defaultdict
def grade(output, reference):
return output.strip().lower() == reference.strip().lower()
def run_eval(cases, app):
by_tag = defaultdict(list)
for c in cases:
ok = grade(app(c["input"]), c["reference"])
for tag in c["tags"]:
by_tag[tag].append(ok)
return {tag: sum(v) / len(v) for tag, v in by_tag.items()}Here app is any function that maps an input string to an output string. Exact match is a weak grader for most tasks, and a later chapter covers better ones. The point is that this loop only works because the schema supplies input, reference, and tags under predictable names.
Common errors
- Changing ids. Renaming or renumbering cases breaks result history and moves cases between splits. Retire an id rather than reuse it.
- Free-text tags. Inconsistent spelling fragments slices into groups too small to read. Use a controlled list.
- Hidden inputs. Context the app needs, such as a retrieved document or the current date, is kept outside the case. Results then change from run to run for reasons the dataset cannot explain.
- Mixing reference types silently. Some cases hold a label, others a paragraph, and the grader treats them all the same way. Make the grading method explicit, either by field or by an added
graderfield. - Over-building. A schema with thirty fields that nobody fills in is worse than six fields that are always correct.
Checklist before moving on
- Every case has a unique, stable id.
inputcontains everything needed to rerun the case.- Each case has a reference or a rubric, and the choice is explicit.
- Tags come from a controlled list and allow several per case.
- Provenance records the source of each case.
- A validation function runs on every load.
Exercise
A teammate fixes a typo in the input of case refund-001 and also renames the id to refund-001-fixed "to mark the change". The dataset splits cases into dev and test by hashing the id. Name two problems this causes, and say what they should have done instead.
Show answer
First, hashing the new id can move the case from one split to the other, so a case that was in test may now be in dev (or the reverse). This lets a case you tuned against appear in the test set, which leaks information and inflates test scores. Second, past results are keyed by the old id, so the case's history is broken and score comparisons across runs no longer line up. They should have kept the id refund-001 and fixed only the input text. If the change is worth recording, they should note it in the dataset's version history or a changelog.
Exercise
You are building a dataset for an app that summarizes support tickets. Would you use a reference or a rubric for each case, and which three fields beyond id and input would you include? Justify briefly.
Show answer
Use a rubric. Many different summaries can be correct, so exact comparison against one reference text would mark good summaries as wrong. Example rubric items are "mentions the customer's main complaint" and "does not invent an order number". Three useful fields are rubric (the grading criteria), tags (such as ticket type or language, for per-slice scores), and source (to separate production tickets from synthetic ones). A difficulty field is a reasonable fourth choice, but it is optional.