Regression and contract tests
Test an AI system at several levels
AI testing checks whether an implementation satisfies a defined contract and behavior specification. Regression testing detects loss of previously verified behavior after a change. Chapter 47 defined success labels and uncertainty; this lesson turns those labels into repeatable checks. A unit test isolates a function; a contract test verifies an interface across components. Integration tests check interacting components, and end-to-end tests exercise the full user journey in an isolated environment. Human acceptance evaluates usefulness and appropriateness with a documented rubric. In this example, an adapter contract requires exactly status, answer and citations. An answer must be nonblank with nonempty citation IDs; abstention must have null answer and no citations. A schema change from answer to text fails even if the prose is correct. This is an explicit toy contract, not a universal schema.
def valid_response(response): # Exact local adapter contract, not a provider API schema. if type(response) is not dict or set(response) != {"status", "answer", "citations"}: return False status, answer, citations = response["status"], response["answer"], response["citations"] if type(citations) is not list or any(type(x) is not str or not x.strip() for x in citations): return False if status == "answer": return type(answer) is str and bool(answer.strip()) and bool(citations) if status == "abstain": return answer is None and not citations return False
print(valid_response({"status":"answer", "answer":"Blue", "citations":["p1"]}))print(valid_response({"status":"answer", "text":"Blue", "citations":["p1"]}))print(valid_response({"status":"abstain", "answer":None, "citations":[]}))Choose the right assertion
Check exact values for deterministic functions, field types, allowed states and IDs. For free-form generation, define factual support, valid citations, acceptable refusal and task completion; do not demand a single sentence. Structural checks cannot establish factual support. For integration, simulate a retriever timeout and ensure the adapter does not report success with missing evidence. Use real integration tests in a sandbox when dependencies are available. For end-to-end, test a full authorized question through retrieval, response rendering and logging; verify the user sees an appropriate answer or an explicit error. These are test designs, not executed live integrations in this lesson. A unit test that mocks every component cannot establish network or UI compatibility.
Compare a frozen golden set
A golden set contains stable case IDs, inputs, evidence versions, expected outcomes and rubric versions. Store it separately from development fixtures; lock its digest before changing prompts. Compare baseline and candidate on exactly the same cases. The example receives already-reviewed Boolean outcomes rather than raw generated prose. It identifies cases that were previously passing and now fail, and refuses to compare different case sets. Both versions pass two cases, but g1 regressed while g2 improved. Aggregate improvements cannot excuse critical regressions. Record model, prompt, data, adapter and evaluator versions, runtime and run ID. Missing runs are errors, not silently omitted cases. For stochastic generation, repeat paired tests, define tolerances and report uncertainty rather than assuming identical outputs.
def regressions(baseline, candidate): # Maps of fixed case IDs to already-reviewed Boolean outcomes. if set(baseline) != set(candidate): raise ValueError("case sets differ") if any(type(v) is not bool for v in list(baseline.values())+list(candidate.values())): raise ValueError("outcomes must be Boolean") return sorted(k for k in baseline if baseline[k] and not candidate[k])
before = {"g1":True, "g2":False, "g3":True}after = {"g1":False, "g2":True, "g3":True}print(regressions(before, after))print(sum(before.values()), sum(after.values()))Use metamorphic checks and release gates
A metamorphic test compares behavior across a controlled input transformation when a single oracle is difficult. For a case-insensitive lookup, changing case should preserve the same canonical ID; for access-controlled retrieval, changing document ownership to another tenant should remove the document from the authorized result. Only assert transformations justified by the contract. Paraphrasing a question may change meaning, so verify equivalence first. Set critical gates before evaluation: zero observed critical boundary failures, required contract checks pass, and documented human acceptance. Passing a sample is not proof of safety. Preserve redacted failure artifacts and link them to the regression case. Do not update expected outputs merely to make a failed test green; review intentional changes and version the fixture.
Practice a change review
Use the frozen regression fixture in the Chapter 48 project. Run the contract checks, compare baseline and candidate IDs, explain the identical aggregate score, and decide whether the changed adapter should advance. Add one documented metamorphic relation and describe the integration and end-to-end cases that remain unexecuted. Reference: ref-ai-regression-and-contract-tests. Next: defensive adversarial tests.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Regression and contract tests quiz
Assess regression testing, interface contracts and defensive refusal evaluation.
Which test detects a renamed required adapter field?
What does a unit test isolate?
Both versions pass two cases, but a previously passing case now fails. What happened?
Which metamorphic relation is justified for a case-insensitive lookup?
Why freeze a holdout before prompt tuning?