Mental model
Reliable AI engineering follows a stratified testing pyramid: validate every system invariant at the cheapest, fastest, most deterministic software layer capable of falsifying it. Run sub-second deterministic unit and contract checks over deterministic code (tenant ACL predicates, Pydantic/Zod tool argument parsers, MDX AST safety, dollar-cost and turn budget counters), execute statistical golden-set evaluations across retrieval and generation components (Recall@K, nDCG@10, calibrated rubrics), run seeded isolated sandbox trajectories for multi-step agents (pass^3 reliability across clean vs noisy fixtures), and wrap production telemetry into adversarial injection tests plus locked permanent incident regressions.
Learning outcomes
- Assign AI verification obligations deliberately to deterministic software assertions, statistical offline component evals, or sandbox trajectory suites based on failure semantics.
- Design graders matching the underlying claim (exact SQL state assertions for tool mutations, rank metrics for retrievers, human-calibrated rubrics with inter-annotator checks for free-form prose).
- Build leak-free holdout evaluation slices segmented cleanly by risk cohort rather than relying on misleading single aggregate means.
- Convert live customer failures cleanly into sanitized, immutable CI regression suites without benchmark data contamination.
Theory
Teams routinely stall AI delivery from two symmetric mistakes: either treating prompts like ordinary CRUD endpoints (three unit tests with mocked strings and zero statistical evaluations), or routing every invariant through slow, non-deterministic LLM-as-a-judge calls costing minutes and dollars per pull request. Mapping every failure class cleanly onto a four-tier verification stack keeps pull-request feedback rapid (under 30 s) while surfacing silent quality drift before launch:
| Verification Tier | Defects Falsified | Canonical Grader & Oracle | Cadence & Cost Discipline |
|---|---|---|---|
| 1. Deterministic Unit & Contract Tests | Broken auth scopes, missing ACL filters, partial JSON parse bugs, MDX math/Acorn breaks, runaway token budgets | Exact Vitest / pytest assertions over mocked HTTP streams and fixed fixtures | Every git commit (seconds, USD 0.00 token spend) |
2. Component Evals (RAG & Classifiers) | Retriever misses (Recall@50), cross-encoder nDCG@10 drops, router mis-routing, structured output schema invalid rate | Versioned golden qrels, confusion matrices, stratified rare-cohort slices | Every prompt, chunker, or model config PR (30–90 s) |
| 3. Seeded End-to-End Agent Trajectories | Real tool loops interacting with ephemeral SQLite/Postgres containers; multi-trial stability (pass^3) | Out-of-band SQL database state diffs, repo git diff + unit tests, policy assertions | Pre-release candidate & nightly builds (minutes) |
| 4. Adversarial Chaos & Red-Team Probing | Indirect prompt injection hidden in web pages/PDFs, HTTP 429/503 retry loops, split UTF-8 SSE chunks | Fuzz payload corpus + network fault proxy (toxiproxy latency/drop injection) | Weekly & prior to major base model upgrades |
Avoiding Assertion Brittleness, Unstratified Means, and Holdout Contamination
Never assert verbatim phrasing (assert response == "Your refund is complete") against live generative models in CI; natural paraphrases vary across temperatures and provider checkpoints while remaining completely valid. Grade deterministic capabilities by state outcomes and schema contracts (table.refund_status == 'ISSUED', valid clickable source IDs strictly matching retrieved passages) and grade nuanced subjective quality only with explicit rubrics whose automated judge agreements are calibrated periodically against blinded human domain experts (Cohen's kappa ). Equally crucial, report quality per risk stratum rather than a single blurred dataset average: if 85% of traffic is easy greeting FAQs (99% pass rate) and 15% involves high-liability billing exceptions (30% pass rate), reporting "88.6% overall accuracy" conceals broken production risk.
For multi-turn agent trajectories in Tier 3, measure both single-attempt pass@1 and strict multi-trial consistency pass^k (requiring k = 3 or k = 5 independent seeded runs to succeed without mutating wrong database rows or calling unauthorized tools), catching flaky prompt regressions that happen to pass once by luck. Finally, partition corpora into an active development tuning split and a strictly blinded frozen release holdout split never exposed inside few-shot examples or prompt optimization loops (anti-contamination), and convert every post-launch customer escalation into a PII-redacted permanent CI fixture capturing the exact retrieved snippets and initial state.
pythonfrom dataclasses import dataclass@dataclass(frozen=True)class ReleaseGatePolicy:max_critical_acl_failures: int = 0min_retrieval_recall_20: float = 0.88min_schema_parse_rate: float = 0.99min_seeded_e2e_pass_k: float = 0.90min_rare_cohort_pass_rate: float = 0.85def evaluate_release_gates(critical_acl_failures: int,retrieval_recall_20: float,schema_parse_rate: float,seeded_e2e_pass_k: float,rare_cohort_pass_rate: float,policy: ReleaseGatePolicy = ReleaseGatePolicy(),) -> dict[str, object]:"""Enforce deterministic policy invariants alongside stratified component & trajectory checks."""blockers: list[str] = []if critical_acl_failures > policy.max_critical_acl_failures:blockers.append(f"critical_acl_failures={critical_acl_failures}")if retrieval_recall_20 < policy.min_retrieval_recall_20:blockers.append(f"recall_20={retrieval_recall_20:.3f} < {policy.min_retrieval_recall_20}")if schema_parse_rate < policy.min_schema_parse_rate:blockers.append(f"schema_parse={schema_parse_rate:.3f} < {policy.min_schema_parse_rate}")if seeded_e2e_pass_k < policy.min_seeded_e2e_pass_k:blockers.append(f"seeded_e2e={seeded_e2e_pass_k:.3f} < {policy.min_seeded_e2e_pass_k}")if rare_cohort_pass_rate < policy.min_rare_cohort_pass_rate:blockers.append(f"rare_cohort={rare_cohort_pass_rate:.3f} < {policy.min_rare_cohort_pass_rate}")return {"promote": len(blockers) == 0, "blockers": blockers}
Alternatives and trade-offs
- Stratified Pyramid (Unit Contracts + Retrieval Evals + Sandbox Trajectories): Keeps day-to-day code iterations instantaneous cleanly via fast mocked deterministic tests while guarding genuine statistical quality, injection resilience, and multi-turn side effects across real snapshots. Maintaining separate suites requires active curation discipline around versioned
qrels, realistic seed snapshots, periodic kappa recalibration against blind human graders, and stratified risk slice tags so high-volume low-risk traffic never hides broken critical workflows. - Full Live End-to-End Integration Suites Only: Maximizes execution fidelity across real external endpoints, model snapshots, and tokenizers, yet runs agonizingly slowly (
10–30 min), burns noticeable upstream quota per commit, flakes unpredictably on third-party rate limits (HTTP 429), and struggles cleanly to pinpoint whether retrieval ranking, tool serialization, or synthesis regressed. - Deterministic Mocked Unit Tests Without Offline Statistical Evals: Delivers instant green CI builds with zero token expense while silently missing chunker-boundary truncation bugs, degraded hybrid vector recall across newly ingested tables, broken structured-output drift on rare enums, and indirect prompt injection payloads leaking through real search hits.
- Shadow Production Replay Alone Without Pre-Release Gates: Mirrors authentic live traffic shapes without synthetic distribution drift, yet offers weak pre-merge coverage unless scrubbed of PII, deterministic in tool execution side effects (
read-only or sandboxed dry-run), and paired cleanly with strict blocking Tier 1/Tier 2 release gates before promoting aliases.
Failure modes and misconceptions
- Testing Only Happy-Path Mocked JSON Streams: Stubbing
llm.complete = lambda _: valid_jsonproves serialization syntax while leaving retrieval misses, indirect document injections, and real provider429/504disconnects untested until customers hit them. - Grading Agent Mutations Solely by Self-Reported Chat Answers: Allowing an agent's final sentence (
"Done, updated!") to pass tests without asserting underlying PostgreSQL row diffs or filesystem tests turns hallucinated success claims into false-positive CI passes. - Self-Referential Judge Loops Without Human Calibration: Using the same model family un-anchored as sole scorer amplifies verbosity bias and shares identical failure blind spots unless audited periodically against human gold labels.
- Overfitting Few-Shot Prompt Examples Directly on Test Cases: Inspecting failing test answers and pasting exact phrasing fixes into production prompts inflates offline eval scores into
98%while overfitting generalization cleanly (holdout leakage).
Decision scenario
Your SaaS customer-operations agent handles policy Q&A and stateful billing adjustments, recently shipping a prompt refactor that passed 40 fast mocked Vitest tests yet broke rare multi-state tax refund calculations and allowed an untrusted web-scraped ticket note to trigger unauthorized lookups. Restructure CI into four explicit gates: (1) deterministic sub-second Vitest/pytest checks enforcing ACL isolation, budget caps, and strict Zod output schemas (0 token cost); (2) retrieval Recall@20 + rare-policy slice component evals per prompt/indexer edit; (3) isolated containerized PostgreSQL sandbox runs checking pass^3 environment state diffs; and (4) nightly indirect-injection + fault-proxy tests plus sanitized permanent regression fixtures derived from every customer incident.
Trade-offs
Tiered AI testing prevents slow, noisy, budget-draining CI pipelines by isolating software contracts from probabilistic inference while preserving statistical and security rigor before production promotion, at the ongoing engineering investment of maintaining stratified golden sets, sandbox fixtures, and human judge calibration.