Skip to main content

Chapter 3. Test Cases and Cold-Start Data

Datasets and Test Case Design

Harbor & Pine is preparing Juniper for a new returns workflow, but the team has no customer logs: the feature has not launched, and the old support tool did not record structured examples. A product manager needs an evaluation set by Friday. A model can quickly generate 500 support questions and answers, yet that apparent abundance leaves a harder question unanswered: which action is actually correct for each order?

The team can begin with the return policy and the action each branch permits, then draft cases, check their expected outcomes, and mark anything the policy leaves unresolved. A useful evaluation dataset specifies not only the situations that matter, but also what the agent may do, which outcomes pass, and what evidence supports each label. These choices determine what every downstream metric can tell us: even a sophisticated judge cannot compensate for missing edge cases, answers exposed in the prompt, or labels built on the wrong policy.

This chapter builds that specification and the pipeline around it. The next chapter follows the cases into the environment where Juniper acts: an otherwise excellent test can still mislead if a mock omits important behavior or one run changes the state used by the next.

After this chapter you will be able to:

  • define a task case with input, initial state, expected outcome, constraints, taxonomy and provenance;
  • choose appropriate ground truth for verifiable, reference-based, rubric-based, preference and open-ended tasks;
  • represent valid outcomes without assuming one exact answer or one exact trajectory;
  • start a test set when there are no logs, users or labels;
  • combine synthetic generation, programmatic checks, weak labels and human verification responsibly;
  • build coverage across task types, edge cases and modalities;
  • split, version, audit and refresh evaluation data without hiding contamination or decay.

Illustrative material. Harbor & Pine, its policies and every dataset row in this chapter are fictional. The lab uses deterministic templates, not a model or customer data. It demonstrates a pipeline, not a sufficient production benchmark.

3.1 Anatomy of an agent test case

A request alone is not enough to test Juniper’s decision. “Refund this order” could call for a refund, a denial, or a request for clarification depending on the order and the policy. A good test case therefore gives the runner its task, the evaluator its checks, and a future maintainer its provenance. Agent cases usually need state, constraints, and source information alongside the input and expected outcome.

Field Purpose Juniper example
case_id Stable identity late_return-02
family_id Group related variants for splitting late_return
task_type Select the task-specific grader support_action
modalities Describe the input and output types ["text"]
input User request, transcript, or asset references Customer message
initial_state World state before the agent acts Order ID, ship status, delivery age
expected Checkable answer or outcome Deny refund; leave order unchanged
constraints Invariants and prohibited actions Do not refund outside policy
taxonomy Slices for coverage and analysis returns / outside_window
provenance Source, generator, policy version, reviewer status Fictional policy v1.0
split Intended use train, dev, or test

The initial state is essential for state-changing tasks: “Refund this order” is not a complete case if the order’s delivery date, prior refund status or amount changes the answer. Preserve a minimal state snapshot or a deterministic fixture reference so the same case can be replayed.

Use stable IDs that survive harmless text edits. Keep the content hash separately: the ID answers “which case?”, while the hash answers “which exact version of its contents?” A changed expected outcome should be a reviewed dataset change, not a silent edit under an unchanged file.

3.2 Ground truth by task type and modality

Once a case describes the situation, the next question is how to recognize success. Ground truth is the reference evidence used to judge a result. Depending on the task, it may be a state change, a source passage, or a set of acceptable answers—not necessarily a sentence to match. The representation should be as strong as the available evidence supports, but no stronger.

Task / modality Suitable ground truth Common mistake
Structured action or tool call Valid action and argument schema; expected environment state Checking only the natural-language confirmation
Fact extraction or classification One or more verified labels, with evidence span if useful Treating ambiguous cases as certain
Question answering or RAG Reference answer, supporting sources, acceptable variants, and abstention rule Scoring semantic similarity without checking faithfulness
Summarization or open-ended writing Rubric dimensions, required facts, forbidden claims, and sometimes preference judgments Pretending one reference string is uniquely correct
Image or document understanding Structured answers plus regions, boxes, or cited page locations Losing the link between a label and its source pixels
Audio or speech Transcript with time spans, speaker labels, and task-specific tolerances Using one transcript as exact ground truth despite disfluencies
Video understanding or generation Time-indexed events, frame/clip references, temporal constraints, human rubric Grading one sampled frame as if it represented the whole clip
Agent trajectory Preconditions, allowed transitions, invariants, and optional acceptable paths Requiring one exact sequence when several are safe
Preference or user experience Pairwise preference or anchored rating rubric with context Calling a subjective preference an objective fact

Task type and modality interact. For a voice bot, you may need separate evidence for transcript accuracy, turn-taking, task state, and user experience, while a RAG agent may take a screenshot or PDF and need to cite the correct page as well as answer the question. In either case, keep image, audio, and video references immutable and resolvable, and get permission before including private media in a benchmark.

For preference and rubric judgments, reasonable reviewers may disagree. Preserve each rating, the rubric version, and any adjudication outcome so the dataset records that uncertainty instead of hiding it in a forced consensus. Chapter 6 develops annotation and agreement practices; Chapters 23–25 cover modality- and system-specific evaluation.

3.3 Representing ground truth: outcomes, invariants, and alternatives

The table above describes several kinds of evidence; these can also be combined within a single case. A refund may require both a particular end state and a constraint on the path taken to reach it. Four useful forms of reference are:

  1. Exact value: a JSON field, action name, tool argument or extracted identifier. Use it when the correct value is unambiguous and normalizable.
  2. End state: a database state, file diff, ticket status or set of side effects. Use it for agents that act on tools. Specify both what must happen and what must not happen.
  3. Constraints and invariants: conditions every acceptable run must satisfy, such as “never refund a final-sale item” or “do not send email before approval.” These are often more important than a single golden trajectory.
  4. Rubric or set of valid answers: use when several answers can be correct. Define dimensions, anchors, evidence requirements and disqualifying errors. For an open task, a rubric can say that the answer must include the key facts, cite sources, and avoid unsupported claims without prescribing wording.

For an agent, one recorded trajectory should not be the only passing path unless the process itself is safety-critical. In a task to “find the order and refund it if eligible,” for example, checking the final state and policy constraints allows both lookup → refund and a safe cached lookup to pass, while refunding the wrong order fails. When sequence matters, specify acceptable transitions and grade those; raw text-log comparisons are too brittle.

Multiple valid answers should be explicit: store an accepted_values set, a canonicalization function, or a rubric with examples of acceptable and unacceptable outputs. A grader that uses fuzzy matching must document what it normalizes. Otherwise, a tolerance intended to forgive formatting differences can silently accept a changed meaning.

3.4 Sourcing cases: logs, experts, synthetic data, red-teaming

The form of a reference does not tell us where the case came from. Each source below reveals different behavior and introduces different blind spots, so a defensible portfolio usually draws on more than one.

  • Production logs reveal real wording, workflows and unexpected behavior. Obtain consent or another valid basis, minimize fields, redact personal information, control access, and retain only what the evaluation needs. Logs overrepresent users who reached the system, reported a problem, or used a particular language.
  • Subject-matter expert (SME) authoring provides policy coverage and rare but important cases. Give experts a taxonomy and ask for realistic inputs, state conditions, expected behavior, evidence and severity—not just “trick questions.”
  • Synthetic generation expands paraphrases and combinations quickly. Constrain it with a policy or schema, preserve the generation prompt/version, filter duplicates and invalid cases, and verify labels independently. A generated answer is a candidate label, not ground truth.
  • Red-teaming deliberately searches for failures, including policy conflicts, prompt injection, abusive inputs and unsafe tool sequences. Keep red-team cases in a separately tagged slice so their deliberate oversampling is visible.
  • External datasets can provide useful task families, but check license, consent, provenance, intended use and fit before incorporating them. A public download is not automatically suitable for a private product evaluation.

The “best” source is therefore not necessarily the one with the most rows, but the one that closes a known coverage gap while preserving enough information to interpret and audit each case.

3.5 The cold-start playbook

Returning to Harbor & Pine’s Friday deadline, the absence of logs is a constraint rather than a reason to postpone every test. The team still has product requirements, policies, interfaces, failure costs and people who understand the domain. The following sequence turns those materials into an initial evaluation while keeping its limitations visible:

The map follows the steps clockwise. After the launch baseline and collection plan, reviewed production findings can inform the next version of the contract and cases; keep the protected holdout separate from tuning and refresh work. The pilot collects feedback, but the holdout must be frozen before tuning the agent. Scroll horizontally to see the complete cycle on a narrow screen.

  1. Write the task contract
  2. Build a decision taxonomy
  3. Author boundary cases
  4. Create a gold seed set
  5. Generate controlled variants
  6. Run a sandbox pilot
  7. Freeze a holdout before tuning
  8. Set a baseline and collection plan
  1. Write the task contract. Define the user goal, success state, safety constraints, permitted tools and abstention/escalation behavior.
  2. Build a taxonomy from decisions. List policy branches, input conditions, user intents, task types, modalities, difficulty and consequence. Include both routine and high-impact cases.
  3. Author boundary cases with SMEs. For each rule, write a positive example, a near-miss that should not qualify, an ambiguous case, and an adversarial or conflicting instruction.
  4. Create a small gold seed set. Have qualified reviewers independently label a manageable set, then resolve disagreements and clarify the rules. Preserve original labels and adjudication.
  5. Generate controlled variants. Paraphrase wording, vary irrelevant details and combine conditions only when the expected outcome remains known. Keep variants linked to their seed family.
  6. Run an agent pilot in a sandbox. Collect failures and ask intended users or support staff to review whether the cases are realistic. Do not treat synthetic coverage as observed production coverage.
  7. Freeze a holdout before tuning. Keep cases or whole scenario families out of prompt/model iteration. Add a time-based holdout once traffic exists.
  8. Set a launch baseline and a collection plan. Define what telemetry may be collected, how it will be reviewed, and how production cases become new, consent-compliant tests.

Cold start is not permission to invent certainty, so mark which cases are expert-authored, generated, programmatically verified, human-reviewed or unresolved. A small, well-understood set can guide a pilot, but it cannot establish broad population performance.

Reusable prompt: generate cold-start candidate cases

Use a model to propose cases, not to establish policy truth. Give it only approved source material, ask it to quote the rule behind each case, and require an explicit unresolved status when the source is insufficient. A qualified reviewer must verify every expected outcome before the case enters a gold or release set.

You are helping an evaluation team draft candidate test cases for an AI agent.
You are a case generator, not a policy author or final labeler.

TASK CONTRACT
- Agent task: [describe the user goal and permitted actions]
- Allowed tools and state changes: [list them, or "none"]
- Required safety and escalation behavior: [describe]
- Case families or slices to cover: [list]

APPROVED SOURCE MATERIAL
[Paste the exact, versioned policy, product contract, or interface specification.
Do not use outside knowledge.]

Generate candidate cases for these coverage roles:
1. A routine case where the rule clearly applies.
2. A boundary case at or near a stated threshold.
3. A near-miss where one relevant condition changes the correct outcome.
4. An ambiguous or incomplete-evidence case that may require clarification or escalation.
5. A conflicting or adversarial instruction that must not override the approved rule.

For every case:
- Change only the stated condition when making a paired near-miss.
- Cite the exact source passage that supports the expected outcome.
- Do not infer missing policy, invent facts, or write a gold label if the source
  does not determine the answer. Set review_status to "unresolved" instead.
- Keep personal data synthetic and use fictional identifiers.
- Mark whether the case is model-generated and give it a shared family_id when
  it is a variant of another case.

Return valid JSON only, as an array of objects with:
case_id, family_id, task_type, input, initial_state, expected_outcome,
required_invariants, prohibited_outcomes, source_quote, source_version,
changed_factor, coverage_tags, ambiguity, review_status.
Set review_status to "unresolved" when the source does not determine the answer;
otherwise set it to "needs_independent_review". Every case requires review.

For example, a returns team can paste the approved return policy and ask for cases around the eligibility window, final-sale exclusion, and missing delivery date. The model may suggest a case for the last eligible day and a paired case for the next day, but the policy owner still confirms the boundary convention and both outcomes. Store the generated prompt, source version, model/version, and reviewer decisions as provenance; generated variants belong to their seed family for splitting.

3.6 Scalable ground-truth generation pipelines

The seed cases are useful, but a growing product will need more than a one-off authoring exercise. Scaling the workflow, rather than merely the number of generated rows, means separating candidate creation, labeling, verification, triage and release:

policy / logs / SME seeds
        ↓
candidate generation → normalize → deduplicate → schema/privacy checks
        ↓
programmatic labels + weak labels + model-assisted prelabels
        ↓
confidence / disagreement triage → independent human review → adjudication
        ↓
coverage audit → family-aware splits → versioned release + manifest
        ↖                                      ↓
       errors, drift, appeals, policy changes ← audit and monitoring

Different labels need different evidence. A programmatic oracle is excellent for “the resulting order ID equals the requested ID” when the test fixture fully specifies the expected state, but it cannot decide whether a response is empathetic. A weak labeling function, meanwhile, is a heuristic that covers some examples, may abstain on others, and can be wrong. Systems such as Snorkel combine noisy labeling functions and model their accuracy and correlations for training labels [1]; an evaluation gold set still needs independently validated references. Model-assisted pre-labeling can reduce reviewer effort, but reviewers must see the source evidence, be able to correct the label, and not be anchored into accepting the suggestion.

For synthetic data, a useful pipeline follows generation with validation and filtering, as in instruction-data work such as Self-Instruct [2]. For an evaluation set, add stricter controls: verify expected outcomes against an independent policy oracle or qualified review; record the generator and policy version; detect near-duplicates; and maintain a held-out set that is never used to prompt-tune the generator or agent.

Reusable prompt: suggest a label for human review

Use this prompt to create a pre-label for an existing case. It does not create a gold label. Keep the approved reference separate from the candidate behavior, expose the source version, and send abstentions and sampled agreements to independent review.

You are proposing a candidate annotation for an evaluation case.
Your output is a pre-label for a qualified reviewer, not ground truth.

Label task:
[State one observable question and its unit, such as whether the final order
state matches the requested authorized action.]

Allowed labels and definitions:
- pass: [observable requirements that must all hold]
- fail: [observable conditions that violate a requirement]
- insufficient_evidence: the supplied evidence cannot determine the result
- not_applicable: the criterion does not apply to this case

Authoritative rubric or policy (version: [ID]):
[Paste only the approved rule needed for this decision.]

Case:
[Case ID and relevant user request, initial state, and constraints.]

Observed behavior and evidence:
[Candidate output, trace events, and authoritative state with stable evidence IDs.]

Instructions:
1. Apply only the supplied rubric and evidence; do not use outside knowledge.
2. Do not treat the candidate's claims as proof of the underlying state.
3. Cite evidence IDs for every finding. Do not invent IDs or events.
4. If evidence conflicts, is missing, or does not settle the rule, use
   insufficient_evidence and name what is needed.
5. Preserve uncertainty; do not force a pass/fail label.
6. Do not infer sensitive attributes or add facts not required by the task.

Return valid JSON with exactly:
{
  "candidate_label": "pass | fail | insufficient_evidence | not_applicable",
  "evidence_ids": ["..."],
  "rationale": "One concise explanation tied to the evidence.",
  "missing_evidence": ["..."],
  "confidence": "low | medium | high",
  "review_required": true
}

Validate the output schema and evidence IDs mechanically, then compare pre-labels with independent human labels on a sample that includes both model disagreements and model agreements. Report correction rates by source and slice; where feasible, reviewers should see the source evidence and the model’s rationale only after forming their independent label, to reduce anchoring.

Triage is often more valuable than blanket review, so route cases to people when labeling functions disagree, abstain, or have a known low-precision slice. Also sample cases where the rules agree, because correlated heuristics can agree and still be wrong. The review rate, correction rate by source and slice, adjudication rate, and fraction of cases with no independent evidence help show whether the pipeline is scaling responsibly.

3.7 Taxonomy-driven coverage and edge cases

Even a well-reviewed pipeline can produce hundreds of examples from a narrow part of the task. Coverage asks a different question: which decisions does the dataset actually exercise? For Juniper, the team can organize that question around factors that change the product decision:

Factor Values or examples
Intent Track, return, exchange, address change, warranty, cancel
Policy condition In window, late, final sale, shipped, not shipped
Evidence Complete, missing, contradictory, stale
Risk Read-only, reversible write, irreversible or costly action
Conversation Single turn, clarification needed, correction, escalation
Input form Direct, paraphrased, typo, multilingual, image/document, voice
Difficulty Routine, boundary, compound, adversarial

Use the taxonomy to create a coverage matrix: rows are test families; columns are factors or meaningful combinations. Mark “not applicable” separately from “not yet covered.” Pairwise combinations can reveal interactions without attempting every possible combination, but safety-critical intersections may need explicit tests. Keep counts and metrics by slice; a large routine slice must not wash out a small but high-impact edge case.

Map every new incident to an existing taxonomy item or use it to justify a new one. If the same failure appears under several phrasings, keep the shared family link so you can see whether coverage has broadened or you have simply added paraphrases of one scenario.

Experimental design: from claim to task families

The taxonomy describes possible cases, but the claim determines which cases and comparisons are needed. An evaluation set is an instrument for testing that claim, not a bucket of interesting prompts, so before writing cases, state the claim in a form that could be contradicted:

For [population and task], under [tools, data, and operating conditions], the agent achieves [outcome] at [acceptable quality and risk], compared with [baseline].

For example: “On previously unseen customer-support policy families, the candidate resolves eligible return requests at least as reliably as the current workflow, without increasing unauthorized refunds.” The claim names the population, what must generalize, the baseline, and a safety condition the average cannot obscure.

Use the following design sequence:

  1. Name the decision and estimand. State what a pass would authorize and what quantity you want to estimate: success on a target traffic mix, robustness within known task families, or generalization to new families are different claims. Define the unit of analysis—task, conversation, episode, repository, dataset, or research problem—and the intended population.
  2. Choose the sampling frame. Decide whether cases should represent expected use, deliberately cover rare/high-risk strata, or probe a capability limit. Record the source population, exclusions, sampling weights, and oversampling. A balanced challenge set is useful for diagnosis but does not estimate production prevalence without valid weights.
  3. Choose comparisons and controls. Use paired cases when the same task can be run against candidate and baseline systems; keep tools, initial state, and grading fixed. For stochastic agents, predeclare run counts or seeds and keep task-family clustering visible. Chapter 2 covers uncertainty and comparisons; do not treat paraphrases as independent task samples.
  4. Specify the oracle before generating variants. Record the expected outcome, allowed alternatives, forbidden outcomes, evidence source, and ambiguity policy. For open-ended work, define a rubric or claim-level evidence criteria rather than writing one “gold” answer and calling all deviations wrong.
  5. Choose the split to match the claim. Group related variants by their seed, source document, repository, dataset-generating process, or conversation. Hold out entire groups to test generalization; reserve a time-based set for future distribution shift. Keep development data distinct from a sealed milestone test.
  6. Predeclare analysis and decision rules. Identify primary outcomes, safety gates, slice analyses, run aggregation, missing-run handling, uncertainty method, and thresholds before seeing candidate results. Report exploratory findings as exploratory, not as confirmation of the original claim.

Build cases with deliberate contrasts

Once the claim and oracle are clear, deliberate contrasts make it easier to understand why an agent passed or failed:

Technique Construction What it reveals Main caveat
Decision table Enumerate policy conditions and their required outcomes Missing branches and inconsistent labels A table can encode the wrong policy; obtain domain review
Equivalence classes and boundaries Choose representative in-class values and values just below, at, and above a threshold Off-by-one errors and decision-boundary failures Boundary cases do not estimate how often the condition occurs
Counterfactual pair Hold the case fixed and change one decisive fact, such as shipped vs. not shipped Whether the agent responds to the causal condition rather than wording If several fields change, the contrast is confounded
Metamorphic relation Transform an input in a way that should preserve or predictably change the result Invariance to irrelevant formatting, paraphrase, row order, or units The relation must be valid for the task; not every transform is semantics-preserving
Pairwise / combinatorial coverage Select combinations that exercise interactions among factors Interaction bugs without enumerating the full Cartesian product Pairwise coverage is not a substitute for explicit high-risk combinations
Adversarial challenge Include realistic conflicts, missing evidence, injected instructions, or tool failures Whether safeguards and recovery hold under stress Deliberate oversampling is diagnostic, not representative of prevalence

Inject faults to test recovery

Not every failure begins with an unusual user request: a tool can time out, a record can change mid-task, or two sources can conflict. Fault injection checks whether the agent and its harness remain safe under such conditions, so keep each injected fault explicit and reset the environment between trials. Score both task outcome and the required safe response; a timeout that is recorded as a missing run can hide a reliability failure.

Injected condition Example Evidence to inspect Expected behavior to specify
Timeout or unavailable tool Search returns a timeout before the task deadline Retry count, elapsed time, tool trace, final state Retry only within the budget; otherwise stop or escalate without claiming success
Malformed or partial response Tool omits a required field or returns invalid data Raw response, parser result, subsequent action Validate before acting; request repair, use a safe fallback, or stop
Stale or conflicting data Two sources report different policy versions or account states Source version/time, provenance, chosen evidence Prefer the authoritative current source or surface the conflict; do not silently guess
Mid-task state change A record is updated by another actor between lookup and write Before/after state, identity, precondition check Revalidate preconditions and avoid overwriting a conflicting change
Changed or contradictory user intent User corrects the target or adds a conflicting constraint Turn history, maintained goal/state, action target Confirm material ambiguity and apply the latest authorized instruction

These are diagnostic scenarios, not a representative sample of how often faults occur. For each one, define whether the agent should retry, ask, recover, or stop, and check that retries do not duplicate non-idempotent actions.

For example, a 30-day return policy should have distinct cases at day 29, day 30, and day 31. A counterfactual pair can keep the request text and order constant while changing only the delivery age from 30 to 31; the expected action changes because the policy condition changed. A metamorphic variant can change the order ID format only if the product contract says that formatting is irrelevant. In each case, preserve a common family_id, record the changed factor, and verify labels against the explicit policy.

Build a portfolio, not one blended benchmark

These cases need not all answer the same question. A deliberately difficult fault-injection suite and a sample of ordinary traffic are both valuable, but blending them into a single unqualified rate would obscure what either tells us. Keep the following suites identifiable and report them separately:

Suite Primary purpose Sampling / split strategy Report
Representative Estimate behavior on the intended task population Sample from a defined frame; preserve weights or strata Weighted estimates, exclusions, and uncertainty
Regression core Detect known failures and protect required behavior Stable, versioned cases; keep critical failures even if rare Per-case and per-family regressions; never call it a traffic estimate
Capability / frontier Measure progress on tasks the agent does not yet handle reliably Select difficult, decision-relevant cases with room to improve; version the task families Per-family success, repeated-run reliability, and uncertainty; not a population estimate
Challenge / red-team Explore boundaries, rare risks, and failure mechanisms Deliberately oversample; tag the source and risk Failure rates by challenge category and severity
Generalization holdout Test new task families or sources Hold out families, documents, repositories, or data-generation processes Family-level performance and uncertainty
Freshness / time holdout Detect drift and performance on later cases Freeze a time window after development; monitor policy/version changes Time-sliced results and changes in population

Capability and regression suites answer different questions. A capability suite asks what the agent can learn to do next, so select tasks with meaningful headroom; a low pass rate is useful only when the cases are relevant and the measurement is sound. A regression suite, by contrast, asks whether established behavior still works, so protect critical cases and investigate any loss. When a capability becomes reliable and matters to users, promote reviewed cases into the regression core, while keeping the original capability results and suite versions so progress remains interpretable. Never merge the suites into one score without a justified target mix.

Keep the suites separate unless you can justify the target mixture and its weights in advance. A high score on paraphrases of a few seeds is evidence about wording robustness, not broad task generalization. Report both case count and independent family/source count. Calculate uncertainty at the level that matches the claim; treating near-duplicate rows as independent exaggerates the evidence.

Capability profiles for applied science

Juniper’s return workflow illustrates the design process, not its only application. Other agents require different task units and oracles even when they use the same general approach:

Profile Example claim / unit Useful oracle and evidence Split and coverage risks
Scientific research agent Reproduce or critically assess a finding; unit is a research question or paper Claim-level evidence ledger, source provenance, executable artifacts, and predeclared numerical tolerances Hold out papers, source corpora, or research domains; repeated questions about one paper are not independent research tasks
Data-analysis agent Answer an analytical question from a dataset; unit is a question–dataset pair Known-generating-process truth where possible, executable code, data/query lineage, and checks for leakage and statistical validity Hold out datasets or generating processes; paraphrased questions over one dataset do not establish dataset generalization
Embodied / robotics agent Complete a physical task safely; unit is an episode with initial state and environment Goal state, safety constraints, intervention/recovery trace, and simulator-to-real comparison Vary layouts, objects, and dynamics; simulator-only success does not establish real-world performance
Enterprise workflow agent Complete an authorized cross-system workflow; unit is a transaction or case State diffs across systems, permission/approval evidence, audit record, and rollback status Split by workflow family and tenant/data source; test partial failure and inconsistent system state
Real-time voice agent Resolve a spoken task in a live conversation; unit is a session Task state plus transcript/audio timing, interruption handling, latency, and escalation evidence Vary speakers, noise, accents, and turn patterns; transcript accuracy alone does not measure task completion

Research benchmarks such as PaperBench illustrate end-to-end research-replication tasks. They are useful design references, not substitutes for a product-specific sampling frame, domain oracle, or evidence that a system generalizes to your scientific workflow.

For a data-analysis agent, make “correct answer” decomposable: was the input data identified correctly, was the analysis executable and statistically appropriate, does the result support the stated conclusion, and can another analyst reproduce it? A synthetic dataset with a known generating process is useful for checking specific statistical properties; pair it with realistic, independently sourced datasets because success on synthetic data alone may reward assumptions built into the generator.

3.8 Splits, contamination, and holdouts

A promising portfolio can still give an overly optimistic result if closely related examples influence both development and testing. A split controls which examples can influence development and which remain evidence. If five paraphrases of one policy case land in both train and test, the held-out score may reflect family memorization, not generalization.

  • Group split by conversation, customer, source document, policy case or synthetic seed family.
  • Time split when the production question is performance on future traffic or changing policies.
  • Stratify to preserve important task categories across splits where group constraints permit; record where a rare family is held out entirely.
  • Keep a sealed test set away from prompt, model and rubric iteration. Use dev data for decisions and reserve the test for milestone checks.
  • Measure contamination from public benchmarks, known training examples, copied synthetic prompts and retrieval corpora. Near-duplicate search is a flag for investigation, not proof of leakage or intent.

There is a trade-off: grouping entire families out of test is a stronger generalization test, but with few families it leaves little test coverage, while row-level stratification gives more balanced categories but risks leakage. The right split therefore depends on the claim you need to make. Keep separate suites when you need both “does it solve known workflows?” and “does it generalize to unseen scenario families?”

3.9 Versioning, provenance, lineage, and lifecycle

Once the team has assembled and split the cases, someone must be able to reconstruct what was evaluated months later. Treat a dataset release like a software artifact. Every version should have:

  • a stable version ID and schema version;
  • immutable case IDs and content hashes;
  • source and consent/licensing status;
  • generator, labeling-function, rubric and policy versions;
  • reviewer and adjudication status;
  • split definitions and taxonomy version;
  • creation/update time, owner and change log;
  • intended use, known limitations and retention/access controls.

Keep the lineage graph: a case derived from a production incident should point to the redacted source record; a synthetic variant should point to its seed and generator; a label should point to the policy or rubric version and the evidence used to validate it. If the source must be deleted, lineage lets you identify all derived records for review or removal.

Datasheets for Datasets recommend documenting motivation, composition, collection and recommended uses [3]. Data Statements emphasize documenting linguistic populations and context so claims about generalization do not silently exceed the dataset [4]. For agent evaluations, extend that documentation to tools, initial state, outcomes, task families, graders and side effects.

Do not silently edit a released test case. Fix a typo in a new patch release if it cannot affect meaning; change labels, policies, expected states or split membership in a new version with a migration note and score-impact report. Keep old versions available long enough to reproduce reported results, subject to privacy and retention obligations.

3.10 Dataset quality audits and decay

Versioning makes change visible; auditing tells the team whether the changed dataset is still fit for its claim. Before each release and on a schedule, examine at least:

  • schema validity, required fields and resolvable media references;
  • duplicate IDs, exact duplicates and near-duplicate clusters;
  • label validity and reviewer agreement/disagreement by slice;
  • taxonomy coverage, split counts and family leakage;
  • missing, stale or inconsistent policy facts;
  • privacy, licensing, consent and access-control status;
  • generator and weak-labeler error rates on independently reviewed samples;
  • score movement caused by dataset changes, reported separately from agent changes.

Data decays as policies change, products disappear, tools change schemas, users adopt new language, and public examples leak into training. For that reason, track each case’s age and policy version. When a case no longer reflects current policy, retire it or mark it historical; do not silently change its expected outcome.

When refreshing from production, sample both routine traffic and failure/low-confidence slices. Avoid allowing only reported complaints to define the evaluation distribution. Preserve a stable core regression set and add a rotating freshness set; report them separately so new traffic does not obscure regressions on known critical behavior.

3.10.1 Dataset coverage guarantees

Coverage and statistical precision are related, but they are not the same. A team can deliberately include a critical group without having enough independently sampled cases to estimate its success rate precisely. Let \(\mathcal{T}\) be the task space, \(\mathcal{G}=\{g_1,\dots,g_K\}\) a partition into task groups, and \(\mathcal{D}=\{(x_i,y_i)\}_{i=1}^N\) the evaluation dataset with group membership \(g(x_i)\in\mathcal{G}\).

Group coverage. The fraction of cases in group \(k\) is \[C_k = \frac{|\{i: g(x_i)=g_k\}|}{N}, \qquad \sum_{k=1}^K C_k = 1.\]

Minimum group coverage bounds under-representation of rare but critical slices: \[C_{\min} = \min_{k=1,\dots,K} C_k.\]

A dataset with \(C_{\min}<\epsilon\) risks under-representing groups that may drive safety or business decisions. Report \(C_k\) by slice alongside all aggregate metrics.

PAC evaluation guarantee. With probability at least \(1-\delta\), the true success rate \(\theta\) is within \(\epsilon\) of the empirical estimate \(\hat\theta\) if: \[N \geq \frac{\log(2/\delta)}{2\epsilon^2}.\]

For group-specific guarantees with Bonferroni correction across \(K\) groups: \[N_k \geq \frac{\log(2K/\delta)}{2\epsilon_k^2} \qquad \text{for each group } k.\]

Each group needs its own sufficient sample for the desired confidence width; a rare group may therefore require substantial oversampling. These bounds apply to a fixed agent and prespecified analysis with independent, representative binary outcomes within the population being estimated. Reusing the same sample to select or tune an agent invalidates the simple fixed-agent interpretation.

Worked example: coverage and sample-size guarantees

Suppose a 100-case candidate set has four mutually exclusive task groups: 55 routine questions, 25 order-status questions, 15 eligible-return questions, and 5 policy-exception questions. The group coverage values are \(C_k=n_k/N\): \(0.55\), \(0.25\), \(0.15\), and \(0.05\), which sum to \(1\). The minimum group coverage is therefore \(C_{\min}=0.05\). If the team’s declared coverage floor is \(\epsilon_{\text{coverage}}=0.10\), the current set fails that representation target because the policy-exception group contributes only \(5/100\) cases. This floor is a portfolio-design rule, not a confidence guarantee; the five cases do not support a precise estimate of exception success.

For a separate overall success-rate estimate, choose a desired absolute error \(\epsilon=0.10\) and failure probability \(\delta=0.05\). The Hoeffding/PAC bound gives \[ N\geq\frac{\log(2/0.05)}{2(0.10)^2} =\frac{\log 40}{0.02} =184.45\ldots, \] so round up to at least 185 independent, representative cases for a 95% guarantee within 10 percentage points. This is a conservative planning bound, not a claim that the 100 deliberately composed cases above are representative.

If the team wants the same \(\epsilon_k=0.10\) guarantee separately for each of the \(K=4\) groups, use the Bonferroni-adjusted bound for each group: \[ N_k\geq\frac{\log(2K/0.05)}{2(0.10)^2} =\frac{\log 160}{0.02} =253.82\ldots, \] or at least 254 independent cases per group (1,016 total across four groups if all are sampled to that target). This stronger bound protects simultaneous claims across the groups; it is not a requirement to make every test suite that large. Targeted high-risk cases can be oversampled to test boundaries and invariants, but those cases do not estimate traffic prevalence unless selected under a defensible sampling design.

from math import ceil, log

counts = {
    "routine": 55,
    "order_status": 25,
    "eligible_return": 15,
    "policy_exception": 5,
}
total = sum(counts.values())
coverage = {group: count / total for group, count in counts.items()}
minimum_coverage = min(coverage.values())

delta = 0.05
epsilon = 0.10
overall_n = ceil(log(2 / delta) / (2 * epsilon**2))
group_n = ceil(log(2 * len(counts) / delta) / (2 * epsilon**2))

print("coverage:", coverage)
print(f"minimum coverage: {minimum_coverage:.2f}")
print(f"overall cases for 95% +/- 0.10: {overall_n}")
print(f"cases per group for simultaneous bound: {group_n}")
coverage: {'routine': 0.55, 'order_status': 0.25, 'eligible_return': 0.15, 'policy_exception': 0.05}
minimum coverage: 0.05
overall cases for 95% +/- 0.10: 185
cases per group for simultaneous bound: 254

The bound assumes independent binary outcomes sampled from the population whose success rate is being estimated. Consequently, repeated paraphrases from one seed, cases from the same user or policy family, or a hand-selected challenge set do not become independent representative samples by being counted as separate rows. For clustered or weighted designs, use an uncertainty method that reflects those dependencies and sampling weights; preserve group counts and family counts alongside \(N\).

3.10.2 Item difficulty and discrimination

Coverage counts do not tell us whether a case distinguishes systems at the capability level of interest. Item-response models offer one way to examine that question, provided a single latent capability is an appropriate approximation and the model has been fitted and checked against a sufficiently diverse set of agents. Let \(\theta\in\mathbb{R}\) denote that model’s capability parameter (higher \(\theta\) = more capable), \(Y_i\in\{0,1\}\) the binary outcome on case \(i\), and \(p_i(\theta)=P(Y_i=1\mid\theta)\).

Baseline difficulty proxy: \(b_i=-\log P(Y_i=1\mid\theta=0)\). Larger \(b_i\) means the case is harder at the model’s reference capability level. This is a chosen proxy, not the conventional item-response-theory difficulty parameter, often defined as the capability at which an item’s success probability reaches a specified level.

Item discrimination: \(D_i=\frac{\partial P(Y_i=1\mid\theta)}{\partial\theta}\). A large positive derivative means success probability changes steeply with modeled capability at that particular \(\theta\); it is not automatically a model-independent measure of how well the case separates every pair of agents.

Dataset Fisher information for agent capability \(\theta\): \[\mathcal{I}(\theta)=\sum_{i=1}^N \frac{1}{p_i(\theta)(1-p_i(\theta))}\left(\frac{\partial p_i(\theta)}{\partial\theta}\right)^2.\]

This sum assumes conditionally independent Bernoulli outcomes under the fitted model, with probabilities strictly between zero and one. It describes total information at the specified capability level, not information per case; divide by \(N\) for a per-case average. Model fit, item dependence, and the range of agents used for calibration matter. In particular, retain low-discrimination cases when they test essential safety invariants: ranking agents is not the only purpose of an evaluation.

3.10.3 Label uncertainty and inter-annotator agreement

For \(A\) annotators labeling \(N\) items into \(C\) categories, let \(n_{ij}\) be the count of annotators assigning category \(j\) to item \(i\), and \(p_j=\frac{1}{NA}\sum_i n_{ij}\).

Per-item label uncertainty (entropy): \[U_i=-\sum_{j=1}^C \hat p_{ij}\log\hat p_{ij}, \qquad \hat p_{ij}=\frac{n_{ij}}{A}.\]

High \(U_i\) flags disagreement worth investigating, but it does not by itself prove the case is ambiguous: the cause may be ambiguous evidence, inconsistent instructions, differing expertise, or genuine differences in judgment. Use \(0\log 0=0\) in this calculation.

Fleiss’ kappa (any number of raters): \[\bar P=\frac1N\sum_{i=1}^N\frac{1}{A(A-1)}\sum_{j=1}^C n_{ij}(n_{ij}-1), \qquad \bar P_e=\sum_{j=1}^C p_j^2,\] \[\kappa_F=\frac{\bar P-\bar P_e}{1-\bar P_e}.\]

Krippendorff’s alpha accommodates incomplete annotations and a suitable disagreement distance \(\Delta\). Unlike the fixed-\(A\) notation above, let \(R_i\) be the number of ratings on item \(i\), and use only items with \(R_i\geq2\) in the coincidence counts. For categories \(j,k\), define \[o_{jk}=\sum_{i:R_i\geq2}\frac{n_{ij}(n_{ik}-\mathbb{I}\{j=k\})}{R_i-1},\qquad n_j=\sum_k o_{jk},\qquad n=\sum_j n_j.\] Then, when the expected disagreement is nonzero, \[\alpha=1-\frac{D_o}{D_e},\qquad D_o=\frac{1}{n}\sum_{j,k}o_{jk}\Delta(c_j,c_k),\qquad D_e=\frac{1}{n(n-1)}\sum_{j,k}n_j(n_k-\mathbb{I}\{j=k\})\Delta(c_j,c_k).\]

Fleiss’ kappa as written requires the same number of ratings per item; alpha’s distance and missing-data assumptions should be specified. Both coefficients can be undefined when their expected disagreement is zero. Report agreement by slice as well as overall, together with counts, raw agreement, and the annotation design. A high global value can hide low agreement on safety-critical slices, and agreement alone does not establish label correctness.

3.10.4 Dataset contamination detection

Even accurate labels cannot make a held-out test independent if its examples have already influenced development. Contamination occurs when evaluation examples or meaningfully related material appear in training data or model pretraining corpora.

Nearest-neighbor contamination score. For eval case \(x\in\mathcal{D}_{\text{eval}}\), compute embedding similarity to training cases: \[\text{contam}(x)=\max_{x'\in\mathcal{D}_{\text{train}}} s(\phi(x),\phi(x')),\] where \(s\) is cosine similarity and \(\phi\) is an embedding model.

Contamination rate: \[\rho=\frac{1}{|\mathcal{D}_{\text{eval}}|}\sum_{x\in\mathcal{D}_{\text{eval}}}\mathbb{I}\{\text{contam}(x)>\tau\},\] with threshold \(\tau\) chosen and validated for the embedding model and task. This is the fraction flagged against the accessible comparison corpus, not the proven contamination rate. Similarity can produce false positives and miss relevant overlap; proprietary or unknown pretraining data may not be searchable at all. Report the corpus, threshold, and review results alongside the flagged fraction, and investigate affected cases.

3.10.5 Dataset drift and representativeness

An uncontaminated test may still describe a different population from the one Juniper will encounter. Let \(P_{\text{eval}}(x)\) be the evaluation data distribution and \(P_{\text{prod}}(x)\) the production traffic distribution.

Importance weight: \[w(x)=\frac{P_{\text{prod}}(x)}{P_{\text{eval}}(x)}.\]

Effective sample size: \[\text{ESS}=\frac{(\sum_{i=1}^N w(x_i))^2}{\sum_{i=1}^N w(x_i)^2},\qquad \rho_{\text{rep}}=\frac{\text{ESS}}{N}.\]

This ratio measures weight concentration, not representativeness itself. A value below 0.5 can be a useful warning threshold, but even a value of 1 does not establish representative sampling or correct weights. Importance weighting requires production support wherever the target has mass, reliable weights, and assumptions appropriate to the outcome; it cannot repair missing regions or unmeasured shifts automatically. Combine it with feature-level drift checks, such as PSI or MMD from Chapter 21.

Worked example: weighting and effective sample size

Suppose four sampled cases receive production-to-evaluation importance weights \([4,1,1,1]\). Their effective sample size is \[ \operatorname{ESS}=\frac{(4+1+1+1)^2}{4^2+1^2+1^2+1^2} =\frac{49}{19}=2.58, \] and \(\rho_{\mathrm{rep}}=2.58/4=0.645\). The denominator for the ratio is the four sampled cases; the ESS summarizes how concentrated their weights are.

weights = [4.0, 1.0, 1.0, 1.0]
ess = sum(weights) ** 2 / sum(weight ** 2 for weight in weights)
ratio = ess / len(weights)
print(f"ESS: {ess:.2f} of {len(weights)}; representativeness ratio: {ratio:.3f}")
ESS: 2.58 of 4; representativeness ratio: 0.645

One case contributes more than half of the total weight, so under simplifying assumptions, the weight-based ESS suggests a variance comparable to roughly 2.6 equally weighted observations. It is not a literal count of independent cases or a general variance calculation. Inspect the highly weighted slice and use uncertainty methods that respect the weighting and task clusters. If overlap is poor, collect cases from underrepresented production regions; do not claim that reweighting alone repaired the gap.

3.10.6 Interpreting a failing coverage scorecard

The preceding measures answer different questions, and some depend on models or assumptions that may not hold for a particular suite. A scorecard can organize the investigation, but it is not a universal pass/fail grade. The following fictional thresholds illustrate a team’s local decision process rather than prescribing thresholds for every product.

Step 1 — Read the scorecard left to right

Run all six checks and record which fail:

Check What a failure means Primary risk if ignored
Min group coverage Some task family is underrepresented Silent failures on rare but high-impact cases
Representativeness (ESS) Weights are concentrated Weighted estimates may be unstable; representativeness requires further checks
Contamination Potential overlap is flagged in an accessible corpus Leakage can overstate performance; investigate matches
Label agreement Agreement is low under the chosen measure Labels or instructions may need investigation
Item discrimination Cases separate modeled capability levels weakly Some comparisons may be insensitive; critical invariants can still matter
Fisher information A fitted model reports little information at a capability level Model-based estimates there may be imprecise

A dataset can pass four checks and still be unusable if the fifth is safety-critical. For example, 95% coverage overall with 0% coverage on safety-critical escalation cases means you cannot make a release decision.

Step 2 — Prioritize by decision impact, not alphabetical order

Not all failures are equal. Rank remediation by the cost of a wrong decision:

  1. Potential contamination. Investigate flagged overlap and its effect on the intended claim; quarantine confirmed leakage or report it with a restricted interpretation.
  2. Label agreement. A locally chosen warning level, such as \(\kappa < 0.6\), calls for examination of disagreements, prevalence, rubric clarity, and reviewer sampling—not an automatic conclusion that every label is noise.
  3. Minimum coverage. If \(C_{\min} < \epsilon\) on a high-risk slice, add relevant, verified cases and check whether they support the intended inference.
  4. Weight concentration. If the ESS ratio is low, inspect overlap and weights; collect or resample cases where feasible rather than assuming reweighting is sufficient.
  5. Discrimination. If modeled \(D_i\) is low, inspect the model and consider additional boundary or adversarial cases. Retain tests of critical requirements even when all agents pass them.

Step 3 — Write the remediation plan

A remediation plan has four parts:

Part Content Example
Gap Which check failed and by how much “Warranty coverage: 2% vs. 5% minimum; \(\kappa = 0.24\) on escalation”
Root cause Why the gap exists “Warranty cases were never authored; escalation rubric has ambiguous ‘goodwill’ criterion”
Action Specific, measurable step “Author 30 warranty cases; add 3 anchor examples to escalation rubric; re-label disputed items”
Success criterion How you will know it is fixed “Warranty \(C_k \geq 0.05\); investigate escalation disagreement; review all flagged overlap”

Step 4 — Re-run the scorecard

After remediation, recompute all six metrics. Do not assume the fix worked: - New cases may introduce new contamination. - Rubric changes may shift label agreement in unexpected directions. - Reweighting may change weighted group contributions even though raw group counts stay the same.

Report the before/after scorecard in your release documentation.

Example: Harbor & Pine warranty slice

Suppose Harbor & Pine’s initial 100-case dataset has 30 cases flagged by the similarity check, none in the warranty slice. The team investigates those matches and, for this illustration, replaces all 30 with independently reviewed cases. It also adds four new warranty cases, bringing the revised set to 104 cases. The following values illustrate the resulting scorecard; agreement and weight ratios would need their own documented samples and calculations in a real audit.

Check Before After remediation
Warranty coverage 2% (2 of 100 cases) 5.8% (6 of 104 cases)
Escalation \(\kappa\) 0.24 0.68
Similarity-flagged fraction \(\rho\) 30% (30 of 100) 0% against the checked corpus
ESS ratio 0.41 0.62

The team also adds three anchor examples to the escalation rubric and reassesses the sampling weights. These changes improve the illustrated checks, but they do not prove that the labels are correct, that unknown training corpora contain no overlap, or that production performance will match the scorecard. A release decision still requires the other evidence and safeguards in the evaluation contract.

Red flags that mean “do not release”

The following are reasons to pause and investigate before relying on the relevant claim:

  • Unresolved overlap flags on a safety-critical slice or confirmed leakage that undermines the claim.
  • Low label agreement, such as \(\kappa < 0.4\) under a team’s chosen warning rule, on a safety or legal slice.
  • Minimum coverage \(C_{\min} = 0\) on a slice that can trigger irreversible actions (refunds, account changes, data deletion).
  • Fisher information near zero across the capability range in a validated model used for that claim.

The appropriate response depends on the claim and risk. Some gaps require new evidence before release; others narrow what can be inferred. No single diagnostic threshold is a universal precondition for every metric.

3.11 From case to decision: the evaluation contract

A dataset becomes useful when its cases support a specific decision. For every important quality claim, preserve the complete chain from the situation being tested to what the team will do with the result:

Step Question to answer Record
Case Which task, initial state, user slice, and conditions are in scope? Versioned case IDs, sampling basis, and exclusions
Observable evidence What behavior or state can be inspected without guessing at hidden reasoning? Output, trace spans, tool calls, state diffs, and run metadata
Oracle What evidence or rule establishes acceptable behavior? Source of truth, deterministic invariant, or rubric with provenance and limits
Metric How are observations aggregated, and what is the denominator? Metric definition, slices, uncertainty, missingness, and evaluator version
Decision What action follows, who owns it, and which failures cannot be averaged away? Predeclared thresholds, safety gates, decision owner, and exception process
Failure analysis What is the earliest supported explanation for a miss, and what evidence would confirm it? Failure category, trace links, uncertainty, corrective owner, and regression candidate

Keep the steps distinct when you review a result: the oracle defines acceptable behavior, the metric summarizes observations, and the release threshold turns that measurement into a decision. A judge score alone does not establish that the agent behaved correctly, so if the oracle is uncertain, carry that uncertainty into the decision instead of forcing a confident pass or fail. The capability chapters apply this contract to different agent types, while the lifecycle chapters map evidence to development and deployment stages.

Chapter summary

The dataset determines which claims the team can investigate and how confidently it can interpret the results. The main lessons are:

  • An agent test case includes task, initial state, expected result, constraints, taxonomy, provenance and split—not only a prompt and answer.
  • Ground truth depends on the task: exact values, end states, invariants, references, rubrics, preferences and multimodal annotations all have different needs.
  • Define acceptable alternatives and forbidden outcomes; do not require one exact trajectory unless the process itself is critical.
  • At cold start, derive cases from product contracts, policy branches and SME-authored edge cases, then generate controlled variants and collect production evidence responsibly.
  • Synthetic data, weak labels and model prelabels are candidate-generation or triage mechanisms; disagreement and agreement both need independent quality checks.
  • Split by related family or source to prevent leakage, and maintain both representative and sealed holdout sets.
  • Design the case portfolio around a falsifiable claim; report representative, regression, challenge, generalization, and freshness suites separately.
  • Use boundary, counterfactual, metamorphic, and combinatorial designs to make coverage interpretable; count independent families separately from variants.
  • Adapt the task unit, oracle, and holdout to the capability: scientific research, data analysis, robotics, enterprise workflow, and voice agents need different evidence.
  • Version data, policies, generators, labels and splits together with hashes and lineage.
  • Audit coverage, validity, privacy, duplication and decay before release and during operation.
  • Connect every material quality claim to observable evidence, an oracle, a metric, a decision, and a failure-analysis path.

For product managers. Before approving an evaluation dataset, ask: (1) What claim is this set meant to support? (2) Which user/task slices are absent? (3) Who verified the labels and under which policy version? (4) Are synthetic or weakly labeled cases clearly marked? (5) Can related cases leak across splits? (6) Who owns refresh, privacy and licensing review?

Hands-on lab: Datasets and test cases

The runnable pipeline is code/ch05/lab_ground_truth.py; its ch05 directory is a retained legacy lab ID, and its reusable schema and audits are in bookkit.dataset_pipeline. The generator creates 24 fictional customer messages from six authored policy families, with expected actions drawn from the fictional family table. No real people, production logs, external model or human-review results are represented.

The fixture intentionally simplifies state: it assigns a fixed delivery age by family even when a variant’s message says a different age. Its oracle checks the expected action against the same authored family table, not whether every message and state field agree or independently follow a complete policy. Treat it as a pipeline demonstration, not a validated test suite; resolve such contradictions before using real cases.

Create one case with structured provenance and end-state invariants:

record = make_case(
    "late_return", 1,
    "I want a refund for order HP-8201. It arrived 45 days ago.",
).to_dict()
print(record["expected"])
print(record["taxonomy"], record["split"])
{'action': 'deny_request', 'order_id': 'HP-8201', 'state_invariants': ['target_order_not_refunded']}
{'policy_area': 'returns', 'edge_case': 'outside_window', 'case_role': 'seed', 'input_mode': 'text'} train

The record can be checked against a schema and the authored family table, subject to the limitations above. Next, two weak labeling functions pre-label the messages. They are intentionally imperfect: agreement is not assumed to be truth.

print(f"programmatic schema and policy-oracle checks passed: {len(records)}/{len(records)}")
print(f"weak-label disagreements: {len(weak_disagreements)}")
print(f"weak-label abstentions: {len(weak_abstentions)}")
print(f"agreed labels sampled for independent audit: {len(agreement_audit)}")
print(f"weak-label agreements that are both wrong: {weak_errors}")
print(f"total review queue: {len(review_queue)}")
programmatic schema and policy-oracle checks passed: 24/24
weak-label disagreements: 0
weak-label abstentions: 3
agreed labels sampled for independent audit: 6
weak-label agreements that are both wrong: ['final_sale-04', 'address_unshipped-01']
total review queue: 9

The review queue contains the three abstentions and one agreed case per family for independent audit. The weak labelers have no disagreements in this run, yet their agreements differ from the authored expected actions on two cases. The script writes candidate labels and empty human/adjudication fields to a JSONL queue; nobody is simulated as having reviewed it. The “policy oracle” only checks generated rows against the lab’s own authored family table; it does not independently certify that policy or validate human labels.

The split is by family, so no paraphrase of a held-out family leaks into training:

report = audit_dataset(records)
print("split counts:", report["split_counts"])
print("action coverage:", dict(sorted(Counter(
    r["expected"]["action"] for r in records
).items())))
print("audit issues: invalid={}, duplicate IDs={}, family leakage={}".format(
    len(report["invalid_records"]),
    len(report["duplicate_case_ids"]),
    len(report["split_leakage_families"]),
))
split counts: {'dev': 4, 'test': 4, 'train': 16}
action coverage: {'deny_request': 8, 'escalate_to_human': 4, 'issue_refund': 4, 'start_warranty_claim': 4, 'update_address': 4}
audit issues: invalid=0, duplicate IDs=0, family leakage=0

The test split holds out one family and four variants, enough to demonstrate the audit but not to support a release claim. The script writes the dataset, review queue and manifest under build/ch05/. The manifest records policy and generator versions, content digest, split counts, review status and limitations. The digest for this run is:

c765cd2f62e96644be71202148cb5ff87eb7e723832e873b78d060dc91bcc74a

The generated manifest also states that the set is illustrative rule-checked data, not human-approved gold. Before using an open-source dataset in a real project, add license and intended-use checks to the same release gate; this lab does not import external data.

The lab tags the first authored prompt in each family as a seed, its other prompts as paraphrase, and every case as text input. It then audits a small, predeclared coverage plan:

coverage_plan = {
    "return_seed_cases": {"policy_area": "returns", "case_role": "seed"},
    "return_boundary_cases": {"policy_area": "returns", "case_role": "boundary"},
    "return_counterfactual_pairs": {
        "policy_area": "returns", "case_role": "counterfactual"
    },
    "audio_input": {"input_mode": "audio"},
}
coverage = audit_coverage(
    records, coverage_plan, not_applicable={"audio_input"}
)
for cell_id, result in coverage.items():
    print(f"{cell_id}: {result['status']} "
          f"(cases={result['case_count']}, families={result['family_count']})")
return_seed_cases: covered (cases=3, families=3)
return_boundary_cases: gap (cases=0, families=0)
return_counterfactual_pairs: gap (cases=0, families=0)
audio_input: not_applicable (cases=0, families=0)

The two zero-count return cells show that the cases have not been authored; they say nothing about agent performance. Audio is outside this text-only claim, so the plan marks it not applicable instead of counting it as a gap. To fill the return cells, add verified day-29/30/31 boundary cases and a paired 30-vs-31 counterfactual, retain their shared seed/family ID, and keep that family in one split. Because the audit reports both prompt count and distinct family count, paraphrases cannot inflate the apparent task coverage.

For an applied-science project, adapt the same exercise to the claim you want to test. For a data-analysis agent, create a small matrix over dataset source, missingness mechanism, and analysis type; include known-truth simulations for correctness checks and real datasets for external validity. For a research agent, define units by research question or paper, record claim-level evidence and reproduction artifacts, and hold out entire papers or domains. In both cases, state which cells are representative, challenge, or held out before running the agent.

Exercises

  1. (Design review) Write one falsifiable claim for a data-analysis agent. Specify target population, task unit, estimand, comparison, primary outcome, safety/validity gates, and what the result would not establish.
  2. (Hands-on) Extend the support policy with day-29, day-30, and day-31 cases. Define the boundary rule, create a counterfactual pair that changes only delivery age, validate expected actions against the rule, and keep the family in one split.
  3. (Hands-on) Add required cells for boundary and counterfactual coverage to the lab plan. Confirm the audit reports gaps before adding cases and covered cells afterward; mark a genuinely out-of-scope cell as not applicable.
  4. (Applied science) Design a data-analysis agent suite with at least two dataset-generating processes and one real dataset source. Separate correctness tests on known truth from external-validity tests; split by source/process, not by paraphrased question.
  5. (Applied science) Design a research-agent task family for reproducing a paper result. Specify the evidence ledger, executable artifacts, numerical tolerance, provenance fields, and what counts as an independent held-out family.
  6. (Hands-on) Add a third labeling function that labels only cases with an explicit numeric delivery age. Measure coverage, abstentions, and error rate against independently verified labels.
  7. (Hands-on) Modify the data so a family appears in two splits, confirm the audit catches leakage, and fix it. Then compare case count with distinct family count.
  8. (Discussion) You have no launch logs and a Friday deadline. What is the smallest defensible cold-start suite for a limited pilot? Which claims cannot it support, and what telemetry and review plan should follow?

Further reading

  • Datasheets for Datasets, on documenting motivation, composition, collection and intended use [3].
  • Data Statements for Natural Language Processing, on documenting populations, language context and limits on generalization [4].
  • Snorkel, on weak supervision and combining noisy labeling functions [1].
  • Self-Instruct, on generating and filtering synthetic instruction data; use its pipeline as an example of candidate generation, not evidence that synthetic labels are automatically gold [2].
  • Chapter 2 of this book, for sampling, uncertainty and paired comparisons on the resulting dataset.
[1]
A. Ratner, S. H. Bach, H. Ehrenberg, J. Fries, S. Wu, and C. Ré, “Snorkel: Rapid training data creation with weak supervision,” Proceedings of the VLDB Endowment, vol. 11, no. 3, pp. 269–282, 2017, doi: 10.14778/3157794.3157797.
[2]
Y. Wang et al., “Self-instruct: Aligning language models with self-generated instructions,” in Proc. 61st annual meeting of the association for computational linguistics (ACL), volume 1: Long papers, 2023, pp. 13484–13508. doi: 10.18653/v1/2023.acl-long.754.
[3]
T. Gebru et al., “Datasheets for datasets,” Communications of the ACM, vol. 64, no. 12, pp. 86–92, 2021, doi: 10.1145/3458723.
[4]
E. M. Bender and B. Friedman, “Data statements for natural language processing: Toward mitigating system bias and enabling better science,” Transactions of the Association for Computational Linguistics, vol. 6, pp. 587–604, 2018, doi: 10.1162/tacl_a_00041.