IamBishal

Module 3Lesson 1 of 1Project

3.1 Ship it: a regression gate and production sampling

Build a CI regression gate. It replays the recorded claude-sonnet-5-5 drafts and claude-haiku-5-5 judgements from runs/calls.jsonl, checks each criterion against its own threshold in gate.json, and exits 0, 1 or 2 for PASS, FAIL or ERROR. A seeded regression proves it can fail, and CI runs it with no API key. A trace sampler feeds a JSON Lines review queue into the golden set, and a cost report puts one full eval run at $0.1031.

The suite works when you run it by hand. This lesson makes it hard to skip. It adds a gate that runs in CI on every pull request without an API key and fails the build when a criterion drops below its threshold. You'll prove the gate catches a seeded regression. You'll also add the online half of evaluation: a review queue that samples production traces and turns reviewed failures into new golden cases. Finally, you'll work out what one full eval run costs and what a green gate proves.

By the end you will be able to:

  • set per-criterion thresholds and run a gate that replays recorded judgements;
  • show the gate failing on a seeded regression, and erroring on a missing recording;
  • sample production traces into a review queue and promote a reviewed trace to the golden set;
  • report the cost of one full eval run.

Before you start. This lesson uses everything so far: Lesson 2's golden set, code graders, JSON Lines run files and FakeModel, Lesson 3's judge, and Lesson 4's view of what 40 cases can detect. It needs Python 3.12+ and uv 0.12. No API key is needed: everything replays recorded calls. Then:

bash
cd tutorials-code/build-an-llm-eval-suite/03-shipping/05-ship-it
uv sync
uv run python gate.py; echo "exit $?"     # ends with: gate: PASS / exit 0
uv run pytest tests                       # 53 passed

Record and replay, in one paragraph. Every real model call in this series was made once, with --live --record, and appended to runs/calls.jsonl. Each line holds a key, the model, the stop reason, the parsed answer and the token usage. The key is a hash of the model, both prompts, the schema and a repeat tag. ReplayModel answers a call by computing its key and looking it up. If the key isn't there, it raises NotRecorded instead of calling the API. The recording date, 2026-11-21, and the costs below come from those lines. FakeModel is the other stand-in: tests use it to build exact answers that no real run produced.

The companion folder is Lesson 4's code plus evals/gate.py, evals/sampling.py, gate.json, the gate, sampling and cost scripts, and a seeded regression, with 53 tests. Every number below comes from it, replaying the runs recorded on 2026-11-21.

1. Thresholds per criterion

gate.json gives every check its own threshold, and names the judge the gate uses:

json
{
  "judge_model": "claude-haiku-5-5",
  "criterion": "v2",
  "thresholds": {
    "schema_valid": 1.0,
    "escalation_correct": 0.95,
    "cites_required": 0.9,
    "numbers_supported": 0.95,
    "judge_pass": 0.9
  }
}

Read each threshold in cases: with 40 cases, one case is 2.5 points.

  • schema_valid 1.0. A draft the product can't parse is never acceptable, so no failures are allowed.
  • escalation_correct 0.95 allows 2 misses out of 40. Escalation is the policy failure that hurts most, and Lesson 2 replays v1 at 39/40.
  • numbers_supported 0.95 allows 2. The grader still finds false alarms now and then; Lesson 4 found one more.
  • cites_required 0.9 and judge_pass 0.9 allow 4 each. The judge is the noisiest check, and Lesson 4 showed Haiku failing one good v2 reply.

Why five thresholds and not one overall pass rate? An average lets a collapse in one criterion hide behind four healthy ones. The seeded regression below drops escalation to 77.5% while every other check stays at or near 100%. The average of its five rates is 95%, which looks healthy.

Lesson 4's table sets a limit on all of this. A gate on 40 cases catches a regression that breaks a category of tickets. It won't see a drop of a point or two.

2. The gate

run_gate grades a recorded candidate run with the code graders, then asks the judge about every reply, through ReplayModel:

python
def run_gate(
    rows: list[dict],
    cases: dict[str, Case],
    kb: dict[str, Article],
    judge_model: Model,
    config: dict,
) -> GateResult:
    thresholds = config["thresholds"]
    # A run that skips golden cases would pass on fewer cases: treat it as an error.
    missing = sorted(set(cases) - {r["case_id"] for r in rows})
    if missing:
        return GateResult([], error=f"run has no draft for {', '.join(missing)}; record them first")
    checks = []
    graded = {r["case_id"]: grade_all(cases[r["case_id"]], r["draft"], kb) for r in rows}
    for g in GRADERS:
        failing = [
            cid
            for cid, gs in graded.items()
            if not next(x for x in gs if x.name == g.__name__).passed
        ]
        checks.append(
            Check(g.__name__, len(rows) - len(failing), len(rows), thresholds[g.__name__], failing)
        )

    failing, usage = [], Usage()
    for r in rows:
        reply = (r["draft"] or {}).get("reply", "")
        try:
            verdict, c = judge(
                judge_model, cases[r["case_id"]].ticket_text(), reply, kb, config["criterion"]
            )
        except NotRecorded as exc:
            return GateResult(checks, error=f"{r['case_id']}: {exc}")
        usage = usage + c.usage
        if verdict != "PASS":
            failing.append(r["case_id"])
    checks.append(
        Check("judge_pass", len(rows) - len(failing), len(rows), thresholds["judge_pass"], failing)
    )
    return GateResult(checks, judge_usage=usage, judge_cost_usd=cost_usd(judge_model.name, usage))

The gate has three outcomes, each with its own exit code:

StatusExit codeMeaning
PASS0Every check meets its threshold
FAIL1At least one check is below its threshold: a quality failure
ERROR2The gate couldn't grade the run: a judgement was never recorded, or a golden case has no draft

ERROR is not FAIL, and it is never a PASS. Suppose a reply changes, or a golden case is added, without a recording. Then the gate stops and says so, instead of calling the API or quietly grading fewer cases. That rule is what lets CI run without a key: no code path in the gate can reach the API. Here are both ERROR paths, with exit codes:

A missing recording is ERROR, never a fall-through to the API.
text
$ head -n 39 runs/drafts-v2.jsonl > short.jsonl      # a run missing G40
$ uv run python gate.py short.jsonl; echo "exit $?"
check                  rate  needs  result
ERROR run has no draft for G40; record them first
gate: ERROR
exit 2

$ uv run python gate.py changed.jsonl; echo "exit $?"   # G01's reply edited by hand
check                  rate  needs  result
schema_valid         100.0%   100%  ok
escalation_correct   100.0%    95%  ok
cites_required       100.0%    90%  ok
numbers_supported    100.0%    95%  ok
ERROR G01: 'claude-haiku-5-5: no recorded call 050c01f29f4700cc471a9021; record it with a real run'
gate: ERROR
exit 2

3. Green on the recorded run

text
check                  rate  needs  result
schema_valid         100.0%   100%  ok
escalation_correct   100.0%    95%  ok
cites_required       100.0%    90%  ok
numbers_supported    100.0%    95%  ok
judge_pass            97.5%    90%  ok
gate: PASS

That is prompt v2's recorded run from Lesson 4, with Haiku's one failure, G10.

4. Red on a seeded regression

A gate that has never failed is a gate you haven't tested. scripts/simulate_regression.py takes the recorded v2 drafts and stops the security and promise-bait tickets from escalating. That is what deleting escalation rules 1 and 2 from the prompt might do. The reply text stays the same, so every recorded judgement still applies:

python
DROPPED = {"security", "promise_bait"}

def regress(rows: list[dict]) -> list[dict]:
    out = []
    for r in rows:
        r = copy.deepcopy(r)
        if r["category"] in DROPPED and r["draft"] is not None:
            r["draft"]["escalate"] = False
        out.append(r)
    return out
text
$ uv run python scripts/simulate_regression.py
wrote runs/drafts-regressed.jsonl (9 drafts changed)
$ uv run python gate.py runs/drafts-regressed.jsonl
check                  rate  needs  result
schema_valid         100.0%   100%  ok
escalation_correct    77.5%    95%  FAIL G26, G27, G28, G29, G30, G31, G32, G33, G34
cites_required       100.0%    90%  ok
numbers_supported    100.0%    95%  ok
judge_pass            97.5%    90%  ok
gate: FAIL

The judge's 97.5% is unchanged, and by construction it has to be: the seeded regression changes only the escalate flag, the judge reads only the reply text, and its criterion is about promises and answers, not escalation. That is the point. Only the per-criterion escalation check could catch this, and it did. That is why the gate keeps the code graders and the judge as separate checks.

5. In CI, with no key

The repository's workflow already runs each changed series folder's tests, with no secrets:

yaml
- name: Test (no live calls, no keys)
  run: uv run --directory "${{ matrix.folder }}" pytest

The gate's tests make those tests a gate:

  • test_the_gate_passes_the_recorded_v2_run expects PASS, with only G10 failing the judge.
  • test_the_gate_fails_the_seeded_regression expects FAIL, with exactly those 9 cases failing escalation.
  • test_an_unrecorded_judgement_is_an_error_not_a_pass appends a promise to one reply and expects ERROR.
  • test_a_run_that_misses_a_golden_case_is_an_error drops one case and expects ERROR.

Those tests check the gate against fixed recordings. To gate your feature's own changes, add a step that runs the gate on the run file the pull request commits. Any exit code other than 0 fails the build:

yaml
- name: Eval gate (replays recorded calls, no key)
  run: uv run --directory build-an-llm-eval-suite/03-shipping/05-ship-it python gate.py runs/drafts-v2.jsonl

The workflow never needs ANTHROPIC_API_KEY. When a prompt, the knowledge base or the golden set changes, a person re-records on their own machine. uv run --env-file .env python compare_versions.py --live --record re-drafts the golden set with prompt v2 and re-runs both judges and the pairwise comparison. The cost report below prices one drafter-plus-gate-judge run, the part the gate needs. They commit runs/calls.jsonl and the run file with the change.

Keeping recordings honest

Replaying recorded calls makes CI fast, free and repeatable. It also means CI grades what the model said on the day you recorded, not what it would say today. Three habits keep that from going stale:

  • Re-record on every change that reaches the model. That means a new prompt, a new model ID, a changed criterion, an edited article or a new golden case. Be clear about what the gate enforces. It grades the drafts in the run file you give it. A prompt change alone doesn't change that file, so a stale run would still pass. The gate's ERROR catches a reply, an article or a criterion that no longer matches a recorded judgement, and a golden case with no draft. Re-drafting after a prompt change is a step in your process; make it part of the pull request checklist. A model's behaviour can also drift under an unchanged ID, so re-record on a schedule too.
  • Review the recording like code. runs/drafts-v2.jsonl and runs/calls.jsonl change in the same pull request as the prompt. A reviewer can read the drafts that justified the green build, and spot a draft that passed every check and is still wrong.
  • Keep the recorder out of CI. --live needs a key and costs money. A build that records whenever a recording is missing would quietly turn ERROR into a fresh, unreviewed PASS.

None of this needs a service. The recordings are JSON Lines files in the repository, and git log is their history.

6. Online: a review queue

Everything so far is offline: it grades a fixed set before you ship. Real traffic brings tickets the golden set doesn't have. You can't run the offline graders on it, because production traces have no expected answers. Only checks that need no reference can run on every trace.

python
def online_checks(trace: dict, kb: dict[str, Article]) -> list[str]:
    """Names of the reference-free checks this trace fails."""
    case = Case(
        trace["trace_id"], "production", trace["plan"], trace["subject"], trace["body"], False, ()
    )
    failed = []
    for check in (schema_valid, numbers_supported):
        if not check(case, trace["draft"], kb).passed:
            failed.append(check.__name__)
    return failed

def sample_for_review(
    traces: list[dict], kb: dict[str, Article], rate: float = 0.1, seed: int = 0
) -> list[dict]:
    rng = random.Random(seed)
    queue = []
    for t in traces:
        failed = online_checks(t, kb)
        if failed:
            reason = "check failed: " + ", ".join(failed)
        elif (t["draft"] or {}).get("escalate"):
            reason = "escalated"
        elif t.get("feedback") == "down":
            reason = "thumbs down"
        elif rng.random() < rate:
            reason = "random sample"
        else:
            continue
        queue.append({**t, "reason": reason})
    return queue

The queue takes every trace a check flags, every escalation, every thumbs-down and a random 10% of the rest. The random share is how the queue finds failures that no check knows about yet.

The companion folder has no production traffic, so scripts/make_traces.py builds a simulated log of 80 traces from the recorded drafts. It treats the v1 drafts as last week and the v2 drafts as this week, and adds a thumbs-down where a draft missed an escalation. It is an illustration, not real traffic:

text
$ uv run python sample_traces.py
32 of 80 traces queued for review
   29  escalated
    2  random sample
    1  thumbs down

The thumbs-down is T-v1-G26, the credit request from Lesson 1. A person reviews each queued trace in runs/review-queue.jsonl. When a trace shows a failure the golden set doesn't cover, to_golden_case turns it into a new case, with the expected values the reviewer set:

python
def to_golden_case(trace: dict, review: dict, existing_ids: list[str]) -> dict:
    """A reviewed trace becomes a golden case with the expected values the reviewer set."""
    next_id = f"G{max(int(i[1:]) for i in existing_ids) + 1:02d}"
    return {
        "id": next_id,
        "category": review["category"],
        "plan": trace["plan"],
        "subject": trace["subject"],
        "body": trace["body"],
        "expected": {"escalate": review["escalate"], "must_cite": review["must_cite"]},
        "source": f"production trace {trace['trace_id']}",
    }

The reviewer fills in the expected values, and the function does the rest:

text
>>> to_golden_case(trace, {"category": "promise_bait", "escalate": True, "must_cite": []}, ["G01", "G40"])
{"id": "G41", "category": "promise_bait", "plan": "enterprise",
 "subject": "We want a service credit",
 "body": "Your API was down for three hours last Tuesday. We expect a service credit on this month's invoice.",
 "expected": {"escalate": true, "must_cite": []},
 "source": "production trace T-v1-G26"}

Here the simulated trace came from the golden set, so a real reviewer would reject it as a duplicate of G26. The call shows the shape. Once a genuinely new case is appended to data/golden.json, the gate returns ERROR ("run has no draft for G41") until someone records a draft and a judgement for it. The new case can't be skipped.

A promoted case stops the gate until its draft and judgement are recorded.

Two practical cautions. Real tickets contain customer data, so redact a trace before it becomes a committed golden case. And queueing every escalation, 29 of the 80 traces here, may be more than your reviewers can read. Sample escalations too once you trust that check.

7. What one eval run costs

cost_report.py adds up the recorded usage of one full run: 40 drafts with prompt v2 and 40 judgements by the gate's judge.

json
{
  "cases": 40,
  "drafter": {"model": "claude-sonnet-5-5",
              "usage": {"input_tokens": 3246, "output_tokens": 5321, "cache_read": 57728, "cache_write": 14432},
              "cost_usd": 0.1015},
  "judge": {"model": "claude-haiku-5-5",
            "usage": {"input_tokens": 7328, "output_tokens": 561, "cache_read": 59080, "cache_write": 0},
            "cost_usd": 0.0016},
  "total_usd": 0.1031,
  "per_case_usd": 0.00258
}

One full run costs about ten cents, a quarter of a cent per case. Nearly all of it is the drafter. Haiku costs $0.10 per million input tokens and $0.50 per million output tokens, so judging costs almost nothing.

The drafter's 14,432 cache-write tokens are 8 writes of the 1,804-token system prompt, and the other 32 calls read it from the cache. The run sent 8 requests at once, so all 8 missed the cache before the first write landed. Cache writes cost $2.50 per million on claude-sonnet-5-5, against $0.10 for a read, so a run that warms the cache with one request before going parallel saves a little more.

Recording a run isn't urgent, so it doesn't need answers in seconds. The Message Batches API halves the price, at the cost of waiting for the batch. CI then replays the recording for free.

8. What a green gate proves

A green gate proves that this recorded run of these 40 cases met these thresholds under these graders. It doesn't prove:

  • that the drafter got better. Lesson 4 showed 40 cases can't see a small change.
  • that the graders are right. Lessons 2 and 4 each found a false alarm in a code grader, and Lesson 3 found a wrong label.
  • that the judge catches subtle failures. It was calibrated on blatant planted defects.
  • that a judge-measured change is the real size. A judge with TPR + TNR − 1 below 1 shrinks every change it measures (Lesson 4). Haiku's factor of 1.00 was measured on 60 easy items.
  • that production looks like the golden set. That's what the review queue is for.
  • that it will stay green honestly. Keep tuning the prompt against the same 40 cases and you will pass them without getting better. That's Goodhart's law. Grow the set from the review queue, and keep some cases you don't tune against.

9. The checklist, closed

GapClosed in
No written expectation per ticketLesson 2: 40 golden cases
No mechanical checksLesson 2: four code graders
Prose: answers the question, promises nothing unsupportedLesson 3: a judge calibrated to TPR 1.00 and TNR 1.00 on 60 labels
"v2 looks better" is an opinionLesson 4: paired comparison, intervals, sample size
Nothing stops a regression; nobody looks at real trafficLesson 5: a gate in CI with no key, and a review queue

10. Common problems

  • The gate prints ERROR ... no recorded call. A prompt, a criterion or a reply changed since the run was recorded. Record again with --live --record, commit runs/calls.jsonl and the run file, and re-run the gate.
  • The gate prints ERROR run has no draft for G41. A case was added to the golden set without recording a draft for it. Record the run again.
  • CI passes locally but fails on the runner. runs/ must be committed. The tests replay runs/calls.jsonl, runs/drafts-v2.jsonl and data/production-traces.jsonl.

11. Exercise

A run file with the same case twice would grade one case double and still look complete. Make run_gate return ERROR, with a message naming the case, when a case_id appears more than once, before any grading. Add a test that duplicates G01's row in the recorded v2 run.

Verify. uv run python gate.py still exits 0 on the recorded run, your duplicate run exits 2, and uv run pytest tests reports 54 passed.

12. Where to go from here

You now have the whole loop: a golden set and code graders, a judge you have measured, comparisons that don't overclaim, a gate that can't be skipped, and a queue that keeps the golden set honest. To point it at your own feature, keep the structure and rebuild the contents. That means your feature in place of the drafter, a golden set from your own policy, graders for your own criteria, a judge calibrated against your own labels, and thresholds sized to your set. The plumbing carries over unchanged: record and replay, the runner, the paired comparison, the gate's three outcomes and the review queue.

Key Takeaways

  • Explain record-and-replay: real drafter and judge calls are recorded once in runs/calls.jsonl with model, date and cost, then ReplayModel serves them back and raises NotRecorded for any call that was never recorded, which is why CI needs no API key.
  • Write gate.json with one threshold per criterion and justify each threshold from what 40 cases can detect, where one case is 2.5 points.
  • Explain why the gate checks every criterion on its own instead of using one averaged pass rate or a single overall threshold.
  • Build a gate script that imports the graders, judge and runner from earlier lessons, replays the v2 drafts and the claude-haiku-5-5 criterion v2 judgements, and exits 0 for PASS, 1 for FAIL and 2 for ERROR.
  • Prove the gate can fail: it passes on the recorded v2 run (judge_pass 97.5%, G10 failing), then exits 1 when a seeded regression drops escalation_correct to 77.5%.
  • Run the gate in CI through uv run pytest with no API key, using 53 tests that cover the gate's PASS, FAIL and ERROR paths.
  • Treat missing evidence, such as an unrecorded judgement or a golden case with no recorded draft, as ERROR with exit 2. It is neither a quality FAIL nor a pass.
  • Sample production traces into a JSON Lines review queue by taking every escalated trace, a 10% random sample and every thumbs-down, which queues 32 of the 80 simulated traces.
  • Turn a reviewed failure into a new golden case, and record a fresh run before the gate can grade it.
  • Produce a cost report from the recorded costs: $0.1031 for 40 drafts plus 40 judgements, or $0.0026 per case.
  • State what a green gate proves and what it doesn't, covering Goodhart's law, the 40-case detection limit and judge shrinkage.

Discussion

Ask questions, share what you learned, and help others.

    Loading discussion…

    Bishal SahaLet's build together

    Have a system to design, or an AI feature to get right?

    Tell me about the problem. You'll get a clear, honest view of the best way forward.

    • Reply within 24 hoursOn business days, with my honest view and a next step.
    • Accepting select engagementsArchitecture, AI features and full builds.
    • Remote, worldwideWorking with startups, SMEs and enterprises.