Catch a regression in the traces
About 21 minutes to read, with 7 examples in 7 sections.
Written with AI. Verified by people. How we make books
This book is open to contributions, so anyone can check it or correct it. Its repository · Report an error · How to fix one
Labs
Learn this chapter by doing it
Run every example exactly as the book did, change the code to see what happens, and try your own ideas on the book's code and data. Nothing to install, and your work is saved. Opens in about 30 seconds.
Run every example exactly as the book did, change the code to see what happens, and try your own ideas on the book's code and data. Nothing to install, and your work is saved. Labs runs it for you: 40 hours a month.
On your own machine, free: download the book's notebooks, with its code and data, from GitHub.
Chapter 1 of every book is read aloud for everyone; every chapter with Labs. See plans, or sign in.
Read by an AI voice, word for word from this edition's text. Code, output and tables are on the page.
Pocket TTS by Kyutai, voice alba, from Alba MacKenna's recordings, CC BY 4.0.Pocket TTS by Kyutai, voice eve, from VCTK corpus speaker p361, CSTR, University of Edinburgh, CC BY 4.0, adapted by Kyutai.
Your browser can translate this page from its menu, and the code stays as the book has it.
Or read it with your AI assistant:
Running your code on the book's versions
By the end of this chapter you can say whether a release moved a number, by how much, and whether that move is bigger than the day's noise. You can also write the rule that stops a release from shipping when it moves too far. Four changes to the assistant wait to ship, and each claims to change nothing that matters. One adds six routing examples to the route prompt. One swaps the 4B model, Qwen3-4B-Instruct-2507, for the smaller Qwen3-0.6B. One retrieves more articles for the routes that retrieve, and one turns the prompt cache off. Which of them moved latency, tokens, cost, errors or route accuracy? And would a gate catch the ones that did, without stopping a normal day?
The question has two parts, and the second is the harder one. A release can move a number on the messages it was measured on and still sit inside what an ordinary day would show. So the comparison has to run both releases on the same messages, and it has to say how far the difference could move. The chapter builds a comparison of the two releases on the same messages, and turns it into a gate with fixed limits. It marks each trace with its release so a query can split them, pairs the releases message by message, and puts an interval beside every difference.
Release markers in the spans
A comparison can only split traces by release if each trace says which release made it. Chapter 2 put the markers in place. The resource carries service.version, which names the release, and each inference span carries gen_ai.prompt.version, which names the prompt it was sent with (who made the span, and the requirement levels, where the prompt pair appears). A release is marked by service.version on the resource and gen_ai.prompt.version on the inference span, so a query can split traces by release.
The marker does more than label. Without it, a query over a week of traces would mix the releases into one average, and no release would show its own movement. With it, the same query returns one row per release. Below, the same 60 messages are replayed under the baseline and under each of the four changes, and every span of the five replays goes into one file. Each replay keeps its own markers, and the span IDs come from one sequence, so no two replays share an ID.
1"""Replay the same 60 messages under each of the five releases, export every span to one store, and query the release2markers: the resource's service.version and the inference span's gen_ai.prompt.version. Each release's markers are the3only thing that tells its traces apart, so the query must give five distinct pairs. The span IDs come from one sequence,4so no two releases share an ID in the store."""5from lib.assistant import RELEASES6from lib.case import load_messages7from lib.export import write_jsonl8from lib.gate import release_spans9from lib.query import connect10from lib.report import fmt_int1112import tempfile13from pathlib import Path1415DAY = "2026-12-08"16FOLDERS = {"r0": "baseline-day-1", "r1": "release-prompt-v2", "r2": "release-model-swap",17 "r3": "release-top-8", "r4": "release-cache-off"}18PAIRED = {m.message_id for m in load_messages("2026-12-08-paired")} # the 60 messages, in every release's recording19rows = release_spans(DAY, FOLDERS, PAIRED)20with tempfile.TemporaryDirectory() as folder:21 rows_file = Path(folder) / "spans.jsonl" # the stored rows, as a file a query can read22 write_jsonl(rows_file, rows)23 db = connect(rows_file)24 markers = db.execute(25 "WITH inference AS (SELECT json_extract_string(resource, '$.\"service.version\"') AS version, "26 "json_extract_string(attributes, '$.\"gen_ai.prompt.version\"') AS prompt, "27 "json_extract_string(attributes, '$.\"gen_ai.prompt.name\"') AS name, trace_id FROM spans "28 "WHERE json_extract_string(attributes, '$.\"gen_ai.operation.name\"') = 'chat') "29 "SELECT version, prompt, name, count(*), count(DISTINCT trace_id) FROM inference "30 "GROUP BY version, prompt, name ORDER BY version, prompt, name").fetchall()31 per_version = db.execute(32 "SELECT json_extract_string(resource, '$.\"service.version\"') AS version, count(DISTINCT trace_id) "33 "FROM spans GROUP BY version ORDER BY version").fetchall()3435for version, prompt, name, calls, traces in markers:36 print(f"service.version {version}, gen_ai.prompt.version {prompt}, {name}: {fmt_int(calls)} inference spans")37for version, traces in per_version:38 print(f"service.version {version}, messages (traces): {fmt_int(traces)}")39pairs = {(version, prompt) for version, prompt, _, _, _ in markers}40assert pairs == {(r.service_version, r.prompt_version) for r in RELEASES.values() if r.name in FOLDERS}41assert all(traces == len(PAIRED) for _, traces in per_version) # every release answered every paired message
python release-markers-query.pyservice.version 1.0.0, gen_ai.prompt.version p1, ambrewick.answer: 33 inference spans
service.version 1.0.0, gen_ai.prompt.version p1, ambrewick.route: 60 inference spans
service.version 1.1.0, gen_ai.prompt.version p2, ambrewick.answer: 33 inference spans
service.version 1.1.0, gen_ai.prompt.version p2, ambrewick.route: 60 inference spans
service.version 1.2.0, gen_ai.prompt.version p1, ambrewick.answer: 16 inference spans
service.version 1.2.0, gen_ai.prompt.version p1, ambrewick.route: 60 inference spans
service.version 1.3.0, gen_ai.prompt.version p1, ambrewick.answer: 33 inference spans
service.version 1.3.0, gen_ai.prompt.version p1, ambrewick.route: 60 inference spans
service.version 1.4.0, gen_ai.prompt.version p1, ambrewick.answer: 33 inference spans
service.version 1.4.0, gen_ai.prompt.version p1, ambrewick.route: 60 inference spans
service.version 1.0.0, messages (traces): 60
service.version 1.1.0, messages (traces): 60
service.version 1.2.0, messages (traces): 60
service.version 1.3.0, messages (traces): 60
service.version 1.4.0, messages (traces): 60
Updated from duckdb 2.0.0 to 2.0.1 in Edition 2026.11.2.
Find where the release name lives
+10 proofsFrom Release markers in the spans, chapter 10Read it again
Builds on attribute, from chapter 1, “Spans by hand”
Builds on inference span, from chapter 2, “Span types for each step”
Builds on resource, from chapter 1, “Spans by hand”
A new edition changed what this practised. What changed in Edition 2026.11.2
Line 25 reads the release name from the span's attributes, so every release prints as None and the pair check fails. Fix line 25 so the release name is read from where the section says it is marked.
Why it works
The query groups the inference spans by their two markers and counts them, and it counts the traces each release produced. Every release answers the same 60 messages, which is why the trace counts match. The run asserts that the five marker pairs are exactly the pairs the release table gives, and that every release answered every message, so a missing marker fails the run rather than thinning a row.
Each release produced 60 traces, one per message. The table shows what the markers separate, and the answer calls are the count to check: the model swap is the row that differs from its neighbours.
| Release | Prompt version | Answer calls |
|---|---|---|
| Baseline | p1 | 33 inference spans |
| Prompt change | p2 | 33 inference spans |
| Model swap | p1 | 16 inference spans |
| Top-8 release | p1 | 33 inference spans |
| Cache-off release | p1 | 33 inference spans |
Under the model swap there are fewer answer calls than under the baseline, on the same 60 messages. An answer call is the model call that writes the reply, and a message routed to fallback makes none. The model swap makes fewer of them because it routes more messages to fallback. The CI gate counts the routes that changed later in this chapter. Without the markers the five rows would collapse into one, and nothing in the table would say which release made which call.
Working rule: Mark every trace with its release and its prompt version, and split each query by both before you read a number.
Paired comparison on messages
Two releases measured on different messages differ for two reasons: the release, and the messages. A day's messages vary a great deal. Some are long requests, some route to the fallback reply, and some wait on a slow tool. Run both releases on the same messages and the second reason drops out of each difference, because each message serves as its own control. A paired comparison runs two releases on the same messages and summarises, for each message, the release's value minus the baseline's.
The method is the one that Evaluating LLM Applications calls a paired comparison. That book subtracts verdicts; this one subtracts the values it reads from traces. Every latency here comes from the recording machine, a 4-vCPU Intel Xeon at 2.10 GHz, as chapter 1 describes, and the replays run on the virtual clock. Message time is the sum of the recorded durations of a message's model calls and contacts-tool calls, which is the number chapter 7 counts. The gaps the recorder left between calls are not in it.
Each measure has its own statistic. For message time, input tokens, cost, errors and route accuracy, the statistic is the mean of the per-message differences. The percentile is different, and the text says which statistic each difference is. For the 95th percentile, the book takes the difference of the two p95s, and it resamples the messages jointly: each resample draws the same messages for both releases and takes the 95th percentile on each side. The interval around every difference is chapter 7's percentile bootstrap, run on the messages and resampled as pairs. For a mean, the statistic is the mean of the per-message differences, and for the p95 it is the difference of the two p95s. The unit resampled is the message and never the span. Chapter 7 built that bootstrap for one release's percentile, and here the same resampling runs on pairs.
Input tokens here are the recorded counts, and chapter 6 says where each count comes from.
Next, the example sets each change beside the baseline on the messages that change recorded.
1"""Compare each release with baseline r0 on the same messages, in message time and input tokens: the mean of the per-message differences, and the p95 difference with the two p95s resampled jointly (PL-6). Each interval is a bootstrap of 2,000 resamples at 95 %, seed 20261207. The unpaired width for the input tokens is printed beside the paired one: the messages' own lengths cancel out of the paired difference."""2from lib.gate import measured, paired, paired_report34DAY, MODEL = "2026-12-08", "Qwen3-4B-Instruct-2507"5RELEASES_TO_COMPARE = [ # name, the release's recording folder, the model it ran6 ("r1", "release-prompt-v2", MODEL), # p2: six routing examples in the route prompt7 ("r2", "release-model-swap", "Qwen3-0.6B"),8 ("r3", "release-top-8", MODEL), # top 8 articles instead of 39 ("r4", "release-cache-off", MODEL), # a fresh state per call, so no cached prefix10]11base = measured("baseline-day-1", DAY, MODEL) # r0, the cache on, on all 200 messages of baseline day 112for name, folder, model in RELEASES_TO_COMPARE:13 _, before, after = paired(base, measured(folder, DAY, model)) # the messages this release recorded14 paired_report(name, before, after)
python paired-latency-and-tokens.pyr1, messages (paired with r0): 60
r1, r0 p95 message time on these messages: 17,128.2 ms
r1, message time, mean difference: 726.1 ms (95% interval 79.8 ms to 1,333.3 ms)
r1, message time, p95 difference: -345.3 ms (95% interval -495.9 ms to 2,301.0 ms)
r1, input tokens per message, mean difference: 90 (95% interval 70 to 115)
r1, input tokens, interval width paired: 45
r1, input tokens, interval width if unpaired: 276
r1, cost per 1,000 messages, mean difference: $0.006281 (95% interval $0.003197 to $0.009519)
r1, error rate, mean difference: +0.0% (95% interval +0.0% to +0.0%)
r1, route accuracy, mean difference: +3.3% (95% interval +0.0% to +8.3%)
r2, messages (paired with r0): 200
r2, r0 p95 message time on these messages: 18,351.2 ms
r2, message time, mean difference: -6,750.9 ms (95% interval -7,599.5 ms to -5,921.4 ms)
r2, message time, p95 difference: -14,109.1 ms (95% interval -16,749.8 ms to -12,105.6 ms)
r2, input tokens per message, mean difference: -200 (95% interval -258 to -148)
r2, input tokens, interval width paired: 110
r2, input tokens, interval width if unpaired: 137
r2, cost per 1,000 messages, mean difference: -$0.033156 (95% interval -$0.037326 to -$0.029012)
r2, error rate, mean difference: +0.0% (95% interval +0.0% to +0.0%)
r2, route accuracy, mean difference: -21.0% (95% interval -28.0% to -14.5%)
r3, messages (paired with r0): 60
r3, r0 p95 message time on these messages: 17,128.2 ms
r3, message time, mean difference: 2,222.5 ms (95% interval 1,099.6 ms to 3,462.8 ms)
r3, message time, p95 difference: 7,618.8 ms (95% interval 1,914.5 ms to 12,517.7 ms)
r3, input tokens per message, mean difference: 115 (95% interval 60 to 179)
r3, input tokens, interval width paired: 119
r3, input tokens, interval width if unpaired: 337
r3, cost per 1,000 messages, mean difference: $0.012542 (95% interval $0.006844 to $0.018909)
r3, error rate, mean difference: +0.0% (95% interval +0.0% to +0.0%)
r3, route accuracy, mean difference: +0.0% (95% interval +0.0% to +0.0%)
r4, messages (paired with r0): 60
r4, r0 p95 message time on these messages: 17,128.2 ms
r4, message time, mean difference: 2,881.5 ms (95% interval 2,209.1 ms to 3,677.3 ms)
r4, message time, p95 difference: 2,128.9 ms (95% interval 1,839.2 ms to 16,968.2 ms)
r4, input tokens per message, mean difference: 0 (95% interval 0 to 0)
r4, input tokens, interval width paired: 0
r4, input tokens, interval width if unpaired: 280
r4, cost per 1,000 messages, mean difference: $0.023233 (95% interval $0.018860 to $0.028303)
r4, error rate, mean difference: +0.0% (95% interval +0.0% to +0.0%)
r4, route accuracy, mean difference: +0.0% (95% interval +0.0% to +0.0%)
Why pairing narrows the prompt change's token interval
+10 proofsFrom Paired comparison on messages, chapter 10Read it again
Builds on input tokens, from chapter 6, “Three counts for each call”
Builds on interval, from chapter 7, “Tail percentiles with intervals”
Builds on prompt version, from chapter 10, “Release markers in the spans”
A new edition changed what this practised. What changed in Edition 2026.11.2
The prompt change's input-token interval is 45 wide when paired and 276 wide if unpaired. Pick the reason that pairing narrows it this much.
Why it works
Pairing narrows the prompt change's token interval from 276 tokens wide to 45. On its 60 paired messages, input tokens per message rise by 90 (95% interval 70 to 115), and that rise is the change the gate has to see.
Its mean message time rises by 726.1 ms (95% interval 79.8 ms to 1,333.3 ms), and its 95th percentile moves the other way, by -345.3 ms (95% interval -495.9 ms to 2,301.0 ms). The mean and the p95 disagree in sign, and the p95's interval runs from below zero to far above it. On 60 messages the tail cannot say which way it moved. The p95 is printed here and not gated, and what the gate misses says why.
Cost per 1,000 messages rises by $0.006281 (95% interval $0.003197 to $0.009519), priced at the book's price table, version book-2026-11-02, as chapter 6 sets out. The error rate does not move: +0.0% (95% interval +0.0% to +0.0%). The route accuracy difference is +3.3% (95% interval +0.0% to +8.3%). Its interval starts at zero, so this release has not been shown to change routing.
The model swap is the line with the most movement, and its comparison carries a caveat that applies to every line in it. The 0.6B's prompt carries /no_think as well as the smaller model, so the swap is not a pure model swap, as prompt versions explains. Its prompt version still reads p1. Mean message time changes by -6,750.9 ms (95% interval -7,599.5 ms to -5,921.4 ms). Route accuracy changes by -21.0% (95% interval -28.0% to -14.5%), and that change is the model and the suffix together. The swap ran all 200 messages of the baseline day. Its cost line rests on the 0.6B's row in the price table. The book wrote that row, and it has no source. The cost difference of -$0.033156 (95% interval -$0.037326 to -$0.029012) is therefore only as firm as that assumed rate.
The top-8 release retrieves more articles on the three routes that retrieve. Chapter 7 measured the prefill that comes with the extra context. Here its input tokens rise by 115 (95% interval 60 to 179), and its mean message time by 2,222.5 ms (95% interval 1,099.6 ms to 3,462.8 ms).
The cache-off release is the one that should not move input tokens, and it does not. Its input total differs by 0 (95% interval 0 to 0), because the prompt the model reads is the same. Its cost rises by $0.023233 (95% interval $0.018860 to $0.028303), and its mean message time by 2,881.5 ms (95% interval 2,209.1 ms to 3,677.3 ms). The printed lines give the input total and the cost, not the cached count, so the cost line is the evidence here. Chapter 6 explains how the cached count is derived.
Figure 10.1 draws the two differences for each release, the p95 message time on the left and input tokens per message on the right, each with its interval. The zero line is the reference. The prompt change's p95 interval crosses it, which is the tail's uncertainty in one picture. The token intervals for the prompt change, the model swap and the top-8 release lie clear of zero, and the cache-off release's token interval sits on it, as its input total says.
1"""Draw each release's paired difference from baseline r0 on the same messages, in p95 message time and in input tokens per message, each with its interval. A line that crosses the zero line is a difference the interval cannot rule out; the p95 uses messages resampled jointly, and the token mean uses per-message differences."""2from lib.gate import P95, measured, paired3from lib.figures import ACCENT, INK, MUTED, new_figure, save4from lib.report import fmt_int, fmt_ms5from lib.stats import paired_interval, paired_mean_difference6from matplotlib.ticker import FuncFormatter78DAY, MODEL = "2026-12-08", "Qwen3-4B-Instruct-2507"9RELEASES_TO_DRAW = [ # name, the row's label as the prose gives it, the recording folder, the model; each against r010 ("r1", "Prompt change", "release-prompt-v2", MODEL),11 ("r2", "Model swap", "release-model-swap", "Qwen3-0.6B"),12 ("r3", "Top-8 release", "release-top-8", MODEL),13 ("r4", "Cache-off release", "release-cache-off", MODEL),14]15def show(line, point, low, high, fmt):16 """Print one difference with its 95% interval."""17 print(line, fmt(round(point)), f"(interval {fmt(round(low))} to {fmt(round(high))})")1819base = measured("baseline-day-1", DAY, MODEL)20fig, (left, right) = new_figure(height=3.2, columns=2, sharex=False)21ticks = []22for row, (name, label, folder, model) in zip(range(len(RELEASES_TO_DRAW))[::-1], RELEASES_TO_DRAW): # the top row first23 ids, before, after = paired(base, measured(folder, DAY, model))24 time_p, (time_low, time_high) = paired_interval([m["time"] for m in before], [m["time"] for m in after], P95)25 token_p, (token_low, token_high) = paired_interval([m["tokens"] for m in before], [m["tokens"] for m in after],26 paired_mean_difference)27 show(f"{name}, p95 message time, difference:", time_p, time_low, time_high, fmt_ms)28 show(f"{name}, input tokens per message, difference:", token_p, token_low, token_high, fmt_int)29 left.hlines(row, time_low / 1e6, time_high / 1e6, color=MUTED, linewidth=3)30 left.scatter([time_p / 1e6], [row], color=ACCENT, zorder=3)31 right.hlines(row, token_low, token_high, color=MUTED, linewidth=3)32 right.scatter([token_p], [row], color=ACCENT, zorder=3)33 ticks.append((row, f"{label} (n = {len(ids)})"))34for axis in (left, right):35 axis.axvline(0, color=INK, linewidth=0.8) # no difference: a release that changed nothing36 axis.set_yticks(*zip(*ticks))37right.tick_params(axis="y", labelleft=False) # the rows are named once, on the left38left.set_xlabel("difference in p95\nmessage time (ms)")39left.set_xticks([-10_000, 0, 10_000])40left.xaxis.set_major_formatter(FuncFormatter(lambda ms, _: f"{ms:,.0f}".replace("-", "−"))) # thousands separators41right.set_xlabel("mean difference in input\ntokens per message")42right.set_xticks([-200, 0, 200])43save(fig, "paired-differences")
python figure-paired-differences.pyr1, p95 message time, difference: -345.3 ms (interval -495.9 ms to 2,301.0 ms)
r1, input tokens per message, difference: 90 (interval 70 to 115)
r2, p95 message time, difference: -14,109.1 ms (interval -16,749.8 ms to -12,105.6 ms)
r2, input tokens per message, difference: -200 (interval -258 to -148)
r3, p95 message time, difference: 7,618.8 ms (interval 1,914.5 ms to 12,517.7 ms)
r3, input tokens per message, difference: 115 (interval 60 to 179)
r4, p95 message time, difference: 2,128.9 ms (interval 1,839.2 ms to 16,968.2 ms)
r4, input tokens per message, difference: 0 (interval 0 to 0)
figure: figures/paired-differences.svg
Working rule: Subtract the baseline's value for each message before you summarise. Resample the messages jointly for a percentile, and print each difference with its count and its interval.
Prompt versions
The releases differ in their prompts, and one of them differs in its model as well, so this section says what changed in each prompt before the gate judges the numbers. The baseline's prompt is p1. The prompt change is p2, which adds six routing examples to the route prompt. The six examples add 86 tokens to every route call, and every message makes one. The rest of the prompt change's rise, 4 tokens per message, and the width of its paired interval come from the 2 messages whose route changed, as the paired comparison shows. The markers confirm that both prompts make one route call per message, on the same 60 messages. The top-8 release keeps p1's template, and only its retrieved context grows.
The model swap keeps p1 as its prompt version, and this is the point to read carefully. Its prompt is not the baseline's, because it carries /no_think. Qwen3-0.6B is hybrid-thinking, and its model card at the pinned commit says that with thinking enabled the model always writes a <think>...</think> block, whose content may be empty when thinking is turned off. The recording script adds the suffix to the prompts. We decided that the release carries it, and that its prompt version stays p1. The release marker cannot show the suffix, so a query that splits by prompt version would count the model swap as the baseline's prompt. Under the suffix, the recording's model replies open with an empty block in 256 of their 257, and the assistant's parser drops that block from each reply. The pair still costs output tokens: on average, each route call's output grows by 4 tokens. One answer reply writes its reasoning into its block instead, and the parser drops that as well.
That matters for the token comparison. The two models share one Qwen3 tokenizer. The book checked that on three texts, and the 4B and the 0.6B give identical token IDs for each, so their input counts compare directly. The check covers three texts, not every message, and the chapter claims no more than that. The model swap's token difference is therefore the smaller model and the suffix together. The model-swap gate prints the split: the suffix adds 4 tokens to each route call, and the answer calls change it by -204 tokens per message, since the messages routed to fallback make no such call.
Working rule: Read a release's prompt version with the prompt's differences beside it. Say beside any model comparison whether the prompt changed as well.
The CI gate
A comparison gives numbers, and a gate turns them into a decision. A regression gate is a check in CI that stops a release from merging when a number read from its traces has moved past its threshold, judged against its paired interval. A regression is a release's change that makes a trace-derived number worse than its limit allows, judged by the end of its interval nearest the limit. The limits are set below. The interval is the one chapter 7 builds for a number measured on a day's messages. Evaluating LLM Applications shares that rule, a rule that stops a change from merging, and Business Intelligence with Agents' regression gate uses a different one. Evaluating LLM Applications also describes a naive gate, which fails on the point estimate alone. This gate waits for the interval.
The gate has one job here: catch the prompt change without flagging the baseline's second day, with the same rules for both. The five rules are fixed in code, and the gate prints every line it judges. Message time, input tokens and cost may each rise by a tenth of the baseline's mean on the same messages, which is why the limits differ on 60 and 200 messages. The error rate may rise by two points, and route accuracy may fall by five points. Each rule reads the interval of the release's difference, and a rule flags a release when the end of that interval nearest the limit lies past the limit. For a rise, that is the lower end. For a fall in route accuracy, it is the upper end. So a flag means the release is worse than its limit, beyond its 95% interval. A release whose interval merely reaches past the limit is not flagged.
We set these limits, and the chapter applies them as printed rather than tuning them to these recordings. The relative limits scale with the baseline's mean. The error rate's baseline is zero, so a relative limit would leave it no room, and its limit is two points. Route accuracy is a share of messages, so it moves in points, and its limit is five. The rules read traces, never an answer's text. For route accuracy, the gate reads the route the reply names and checks it against the scenario table.
The error rule uses the definition chapter 8 gives. A reply cut at its token cap, or a route reply that names no route, is not an error under that definition. Chapter 8 counts those as quality findings, and route accuracy already counts the second.
The gate has to pass a normal day, or a team would stop reading it. Gating baseline day 2 against day 1 shows whether it does, with the same rules and limits.
1"""Gate baseline day 2 against baseline day 1, both on release r0, with the same rules and limits as the prompt release's gate. The two days share no message, so each interval resamples each day on its own. The day is a normal day with no incident, and the gate must pass it, or a gate that flags every normal day would never reach CI."""2from lib.gate import judge, measured3from lib.report import fmt_int45DAY, MODEL = "2026-12-08", "Qwen3-4B-Instruct-2507"6before = measured("baseline-day-1", DAY, MODEL) # r0 on all 200 messages of baseline day 17after = measured("baseline-day-2", "2026-12-10", MODEL) # r0 again, on 80 other messages, two days later8print("messages, baseline day 1:", fmt_int(len(before)))9print("messages, baseline day 2:", fmt_int(len(after)))10print("messages shared by the two days:", fmt_int(len(set(before) & set(after)))) # no message is in both11verdict, flagged = judge("baseline day 2 against day 1", list(before.values()), list(after.values()), paired=False)12assert verdict == "pass" and flagged == [] # the same release on a normal day must pass the same gate
python gate-on-baseline-day-two.pymessages, baseline day 1: 200
messages, baseline day 2: 80
messages shared by the two days: 0
baseline day 2 against day 1, message time, mean: 168.8 ms, limit 801.9 ms (95% interval -1,599.0 ms to 1,895.0 ms)
baseline day 2 against day 1, message time, mean, flagged: no
baseline day 2 against day 1, input tokens per message, mean: -5, limit 52 (95% interval -108 to 99)
baseline day 2 against day 1, input tokens per message, mean, flagged: no
baseline day 2 against day 1, cost per message, mean, per 1,000 messages: $0.000545, limit $0.003781 (95% interval -$0.007950 to $0.008940)
baseline day 2 against day 1, cost per message, mean, flagged: no
baseline day 2 against day 1, error rate: +0.0%, limit +2.0% (95% interval +0.0% to +0.0%)
baseline day 2 against day 1, error rate, flagged: no
baseline day 2 against day 1, route accuracy: -3.3%, limit -5.0% (95% interval -14.5% to +7.8%)
baseline day 2 against day 1, route accuracy, flagged: no
baseline day 2 against day 1, gate verdict: pass
Pair releases only when messages overlap
+10 proofsFrom The CI gate, chapter 10Read it again
Builds on interval, from chapter 7, “Tail percentiles with intervals”
Builds on prompt version, from chapter 10, “Release markers in the spans”
A new edition changed what this practised. What changed in Edition 2026.11.2
Line 11 judges the two baseline days as paired, because both are release r0 on the same model. The two days share no message, so change line 11 so the gate judges them the way their messages allow.
Why it works
Why message time is not flagged
+10 proofsFrom The CI gate, chapter 10Read it again
Builds on interval, from chapter 7, “Tail percentiles with intervals”
A new edition changed what this practised. What changed in Edition 2026.11.2
The gate does not flag message time on baseline day 2, although its interval runs past the limit at one end. Which reason from the section explains that verdict for the rule?
Why it works
The two days share 0 messages, so the intervals are unpaired. Message time rises by 168.8 ms, limit 801.9 ms (95% interval -1,599.0 ms to 1,895.0 ms), and the lower end of that interval is far below the limit, so the rule does not flag. The other rules pass as well, and the verdict is pass.
Paired, the prompt change should fail on tokens; unpaired, the same 60 messages should pass. Both judgements run on the same messages, and the run asserts both results.
1"""Gate the prompt-change release r1 against r0 on the same 60 messages, with the gate's own rules. The gate reads the traces only: message time, input tokens, cost, errors and route accuracy. A rule flags a release when the end of its interval nearest the limit lies past the limit. The prompt change adds tokens to every route call, and the gate catches it only because the messages are paired: the same 60 messages judged as unrelated samples pass."""2from lib.gate import judge, measured, paired, tokens_by_step3from lib.report import fmt_int4from lib.stats import mean_of, paired_interval, paired_mean_difference56DAY, MODEL = "2026-12-08", "Qwen3-4B-Instruct-2507"7before = measured("baseline-day-1", DAY, MODEL)8after = measured("release-prompt-v2", DAY, MODEL)9ids, base, release = paired(before, after) # the paired 60: r0 has every one of them10print("messages (paired):", fmt_int(len(ids)))11verdict, flagged = judge("r1 against r0", base, release, paired=True)12assert verdict == "fail" and flagged == ["input tokens per message, mean"] # the prompt change, and only its tokens13assert "message time, mean" not in flagged # its message time is not flagged: the interval's end stays under the limit14# The same 60 messages, judged as if they were two unrelated samples: the same release passes.15unpaired, unpaired_flagged = judge("r1 against r0, unpaired", base, release, paired=False)16assert unpaired == "pass" and unpaired_flagged == [] # without the pairing, the gate misses the change it must catch17steps0, steps1 = tokens_by_step("baseline-day-1", DAY, MODEL), tokens_by_step("release-prompt-v2", DAY, MODEL)18def change(steps, step):19 """r1 minus r0 in input tokens, for each message, in one step's calls; zero where the message made no such call."""20 return {i: steps[i].get(step, {"input": 0})["input"] - steps0[i].get(step, {"input": 0})["input"] for i in ids}21route_in, answer_in = change(steps1, "route"), change(steps1, "answer")22changed = {i for i in ids if before[i]["route"] != after[i]["route"]}23assert len(set(route_in.values())) == 1 # the six examples add the same tokens to every route call24assert all(answer_in[i] == 0 for i in ids if i not in changed) # only a message whose route changed gets another answer call25route_share, answer_share = mean_of(list(route_in.values())), mean_of(list(answer_in.values()))26assert route_share + answer_share == mean_of([m["tokens"] for m in release]) - mean_of([m["tokens"] for m in base])27print("r1 against r0, route call input tokens per call, mean difference:", fmt_int(round(route_share)))28print("r1 against r0, messages whose route changed:", fmt_int(len(changed)))29print("r1 against r0, input tokens per message, answer calls' share:", fmt_int(round(answer_share)))30tokens_base, tokens_release = [m["tokens"] for m in base], [m["tokens"] for m in release]31_, (token_low, _) = paired_interval(tokens_base, tokens_release, paired_mean_difference)32print("r1 against r0, input tokens per message, low end of interval:", fmt_int(round(token_low)))33print("r1 against r0, input tokens per message, limit:", fmt_int(round(mean_of(tokens_base) / 10)))
python gate-on-prompt-release.pymessages (paired): 60
r1 against r0, message time, mean: 726.1 ms, limit 737.3 ms (95% interval 79.8 ms to 1,333.3 ms)
r1 against r0, message time, mean, flagged: no
r1 against r0, input tokens per message, mean: 90, limit 49 (95% interval 70 to 115)
r1 against r0, input tokens per message, mean, flagged: yes
r1 against r0, cost per message, mean, per 1,000 messages: $0.006281, limit $0.003453 (95% interval $0.003197 to $0.009519)
r1 against r0, cost per message, mean, flagged: no
r1 against r0, error rate: +0.0%, limit +2.0% (95% interval +0.0% to +0.0%)
r1 against r0, error rate, flagged: no
r1 against r0, route accuracy: +3.3%, limit -5.0% (95% interval +0.0% to +8.3%)
r1 against r0, route accuracy, flagged: no
r1 against r0, gate verdict: fail
r1 against r0, unpaired, message time, mean: 726.1 ms, limit 737.3 ms (95% interval -1,627.6 ms to 3,141.5 ms)
r1 against r0, unpaired, message time, mean, flagged: no
r1 against r0, unpaired, input tokens per message, mean: 90, limit 49 (95% interval -45 to 231)
r1 against r0, unpaired, input tokens per message, mean, flagged: no
r1 against r0, unpaired, cost per message, mean, per 1,000 messages: $0.006281, limit $0.003453 (95% interval -$0.005244 to $0.018074)
r1 against r0, unpaired, cost per message, mean, flagged: no
r1 against r0, unpaired, error rate: +0.0%, limit +2.0% (95% interval +0.0% to +0.0%)
r1 against r0, unpaired, error rate, flagged: no
r1 against r0, unpaired, route accuracy: +3.3%, limit -5.0% (95% interval -10.0% to +16.7%)
r1 against r0, unpaired, route accuracy, flagged: no
r1 against r0, unpaired, gate verdict: pass
r1 against r0, route call input tokens per call, mean difference: 86
r1 against r0, messages whose route changed: 2
r1 against r0, input tokens per message, answer calls' share: 4
r1 against r0, input tokens per message, low end of interval: 70
r1 against r0, input tokens per message, limit: 49
The token rise clears its limit even at the low end of its interval: 70 tokens against a limit of 49. The rule flags, and the release's verdict is fail. The flag belongs to the input tokens alone.
Message time rises by 726.1 ms, limit 737.3 ms (95% interval 79.8 ms to 1,333.3 ms), which is under its limit, and the nearer end of its interval is under it too. The upper end runs past the limit, but the rule reads the end nearer the limit, so the rule does not flag. Cost rises by $0.006281, limit $0.003453 (95% interval $0.003197 to $0.009519) per 1,000 messages. Its lower end is under its limit, so cost is not flagged either, though tokens rise on the same messages.
Judged as unrelated samples, the same 60 messages pass. The token rise is still 90, limit 49 (95% interval -45 to 231), but its interval runs from below zero to above the limit, its nearer end is under the limit, and the verdict is pass. The interval widths in the paired comparison are why. The shared messages hold the interval narrow enough to see the change through, and the unpaired interval is too wide to see it. The gate catches the change only because the messages are paired.
Working rule: Pair the releases whenever their messages overlap, and judge each rule on the end of its interval nearest the limit. Print every line, so a flag can be checked by eye.
Gating the other changes
Gating the model swap on all 200 messages shows a different failure. Its amounts fall, which the rules pass, and its routes fall, which one rule catches.
1"""Gate release r2, the 0.6B model swap, against r0 on the same 200 messages, with the same rules and limits. Its route accuracy falls, and the gate flags it. Its message time, input tokens and cost fall too, and the rules for those amounts pass a fall. The fall comes from the answer calls: r2 routes more messages to the fallback reply, which makes no answer call. The suffix adds a few tokens to every route call. The gate reads each message's route reply against the route its scenario gives, never an answer."""2from lib.gate import judge, measured, paired, tokens_by_step, to_decimal3from lib.report import fmt_int, fmt_ms, fmt_usd4from lib.stats import mean_of56DAY, MODEL, SWAP = "2026-12-08", "Qwen3-4B-Instruct-2507", "Qwen3-0.6B"7before = measured("baseline-day-1", DAY, MODEL)8after = measured("release-model-swap", DAY, SWAP) # r2: the 0.6B model, on all 200 messages9ids, base, release = paired(before, after)10verdict, flagged = judge("r2 against r0", base, release, paired=True)11print("messages (paired):", fmt_int(len(ids)))12assert verdict == "fail" and flagged == ["route accuracy"] # the model swap is caught on route accuracy alone1314steps0, steps2 = tokens_by_step("baseline-day-1", DAY, MODEL), tokens_by_step("release-model-swap", DAY, SWAP)15def change(step, field):16 """r2 minus r0 for each message, in one step's calls; zero where the message made no such call."""17 return [steps2[i].get(step, {field: 0})[field] - steps0[i].get(step, {field: 0})[field] for i in ids]18answered0 = {i for i in ids if "answer" in steps0[i]}19answered2 = {i for i in ids if "answer" in steps2[i]}20print("messages answered by r0 and not by r2:", fmt_int(len(answered0 - answered2)))21print("messages answered by r2 and not by r0:", fmt_int(len(answered2 - answered0)))22route_in, answer_in = change("route", "input"), change("answer", "input")23assert len(set(route_in)) == 1 # every route call grew by the same amount: the suffix's tokens24route_share, answer_share = mean_of(route_in), mean_of(answer_in)25assert route_share + answer_share == mean_of([m["tokens"] for m in release]) - mean_of([m["tokens"] for m in base])26print("r2 against r0, route call input tokens per call, mean difference:", fmt_int(round(route_share)))27print("r2 against r0, route call output tokens per call, mean difference:",28 fmt_int(round(mean_of(change("route", "output")))))29print("r2 against r0, input tokens per message, route calls' share:", fmt_int(round(route_share)))30print("r2 against r0, input tokens per message, answer calls' share:", fmt_int(round(answer_share)))31print("r2 against r0, message time, answer calls' share:", fmt_ms(round(mean_of(change("answer", "time")))))32print("r2 against r0, cost per 1,000 messages, answer calls' share:",33 fmt_usd(to_decimal(mean_of(change("answer", "cost")) * 1000)))34replies = [text for i in ids for step in steps2[i].values() for text in step["replies"]]35empty = [text for text in replies if text.startswith("<think>\n\n</think>")]36assert all(text.startswith("<think>") for text in replies) # the 0.6B still writes its block under /no_think37print("r2, model replies:", fmt_int(len(replies)))38print("r2, model replies with an empty <think> block:", fmt_int(len(empty)))39print("r2, model replies with text in their <think> block:", fmt_int(len(replies) - len(empty)))
python gate-on-model-swap.pyr2 against r0, message time, mean: -6,750.9 ms, limit 801.9 ms (95% interval -7,599.5 ms to -5,921.4 ms)
r2 against r0, message time, mean, flagged: no
r2 against r0, input tokens per message, mean: -200, limit 52 (95% interval -258 to -148)
r2 against r0, input tokens per message, mean, flagged: no
r2 against r0, cost per message, mean, per 1,000 messages: -$0.033156, limit $0.003781 (95% interval -$0.037326 to -$0.029012)
r2 against r0, cost per message, mean, flagged: no
r2 against r0, error rate: +0.0%, limit +2.0% (95% interval +0.0% to +0.0%)
r2 against r0, error rate, flagged: no
r2 against r0, route accuracy: -21.0%, limit -5.0% (95% interval -28.0% to -14.5%)
r2 against r0, route accuracy, flagged: yes
r2 against r0, gate verdict: fail
messages (paired): 200
messages answered by r0 and not by r2: 59
messages answered by r2 and not by r0: 4
r2 against r0, route call input tokens per call, mean difference: 4
r2 against r0, route call output tokens per call, mean difference: 4
r2 against r0, input tokens per message, route calls' share: 4
r2 against r0, input tokens per message, answer calls' share: -204
r2 against r0, message time, answer calls' share: -5,706.8 ms
r2 against r0, cost per 1,000 messages, answer calls' share: -$0.027870
r2, model replies: 257
r2, model replies with an empty <think> block: 256
r2, model replies with text in their <think> block: 1
Keep every message in each step's change
+10 proofsFrom Gating the other changes, chapter 10Read it again
Builds on input tokens, from chapter 6, “Three counts for each call”
Builds on prompt version, from chapter 10, “Release markers in the spans”
Builds on token count, from chapter 6, “Three counts for each call”
A new edition changed what this practised. What changed in Edition 2026.11.2
Line 17 keeps only the messages that made the same call in both runs, so the step means leave out some messages. Fix it so every message in the paired set counts in each step's change.
Why it works
The amounts fall because the model swap leaves 59 messages without the answer call the baseline made. Those answer calls change the count by -204 tokens per message. The suffix adds 4 tokens to each route call, and the two together make the fall. The rules for those amounts flag a rise, so a fall passes them, and the gate's pass on them follows from its route failure, not from a cheaper model.
Route accuracy changes by -21.0%, limit -5.0% (95% interval -28.0% to -14.5%), and the upper end of its interval is past the limit, so that rule flags it and the release's verdict is fail. Choosing a smaller model is the subject of Small Open Models, which this chapter does not take up. The release is the 0.6B with /no_think, as prompt versions says, so the route change belongs to the model and the suffix together. The error rate does not move: +0.0%, limit +2.0% (95% interval +0.0% to +0.0%), which matches the other releases in this chapter.
The route check counts a route as wrong when it differs from the scenario table, and it does not read the answer that follows. A right route with a wrong answer passes this rule.
The top-8 release and the cache-off release get the same gate on the same 60 paired messages, and the example runs both.
1"""Gate the top-8 release r3 and the cache-off release r4 against r0, each on the same 60 paired messages, with the same rules and limits as the other gates. The top-8 release retrieves more articles, so its input tokens rise, and its time and cost rise with them. The cache-off release sends the same prompts, so its input total does not move, but its cost and time rise. The gate flags r3 on all three amounts and r4 on time and cost alone."""2from lib.gate import judge, measured, paired3from lib.report import fmt_int45DAY, MODEL = "2026-12-08", "Qwen3-4B-Instruct-2507"6before = measured("baseline-day-1", DAY, MODEL)7verdicts = {}8for name, folder in (("r3", "release-top-8"), ("r4", "release-cache-off")):9 ids, base, release = paired(before, measured(folder, DAY, MODEL))10 print(f"{name} against r0, messages (paired):", fmt_int(len(ids)))11 verdicts[name] = judge(f"{name} against r0", base, release, paired=True)12assert verdicts["r3"] == ("fail", ["message time, mean", "input tokens per message, mean", "cost per message, mean"])13assert verdicts["r4"] == ("fail", ["message time, mean", "cost per message, mean"]) # its input total does not move
python gate-on-retrieval-and-cache.pyr3 against r0, messages (paired): 60
r3 against r0, message time, mean: 2,222.5 ms, limit 737.3 ms (95% interval 1,099.6 ms to 3,462.8 ms)
r3 against r0, message time, mean, flagged: yes
r3 against r0, input tokens per message, mean: 115, limit 49 (95% interval 60 to 179)
r3 against r0, input tokens per message, mean, flagged: yes
r3 against r0, cost per message, mean, per 1,000 messages: $0.012542, limit $0.003453 (95% interval $0.006844 to $0.018909)
r3 against r0, cost per message, mean, flagged: yes
r3 against r0, error rate: +0.0%, limit +2.0% (95% interval +0.0% to +0.0%)
r3 against r0, error rate, flagged: no
r3 against r0, route accuracy: +0.0%, limit -5.0% (95% interval +0.0% to +0.0%)
r3 against r0, route accuracy, flagged: no
r3 against r0, gate verdict: fail
r4 against r0, messages (paired): 60
r4 against r0, message time, mean: 2,881.5 ms, limit 737.3 ms (95% interval 2,209.1 ms to 3,677.3 ms)
r4 against r0, message time, mean, flagged: yes
r4 against r0, input tokens per message, mean: 0, limit 49 (95% interval 0 to 0)
r4 against r0, input tokens per message, mean, flagged: no
r4 against r0, cost per message, mean, per 1,000 messages: $0.023233, limit $0.003453 (95% interval $0.018860 to $0.028303)
r4 against r0, cost per message, mean, flagged: yes
r4 against r0, error rate: +0.0%, limit +2.0% (95% interval +0.0% to +0.0%)
r4 against r0, error rate, flagged: no
r4 against r0, route accuracy: +0.0%, limit -5.0% (95% interval +0.0% to +0.0%)
r4 against r0, route accuracy, flagged: no
r4 against r0, gate verdict: fail
Both releases fail. The top-8 release is caught on all three amounts, and its input tokens rise by 115, limit 49 (95% interval 60 to 179) per message. The cache-off release is caught on time and cost alone, because its input stays the same, and its cost rises by $0.023233, limit $0.003453 (95% interval $0.018860 to $0.028303) per 1,000 messages.
| Comparison | Messages | Verdict | Rule flagged |
|---|---|---|---|
| Baseline day 2 against day 1, unpaired | 80 | pass | None |
| Prompt change against baseline, paired | 60 | fail | Input tokens |
| Prompt change against baseline, unpaired | 60 | pass | None |
| Model swap against baseline, paired | 200 | fail | Route accuracy |
| Top-8 release against baseline, paired | 60 | fail | Message time, input tokens and cost |
| Cache-off release against baseline, paired | 60 | fail | Message time and cost |
Each of the four changes moved something the gate reads, and the gate flags each one: the prompt change through its tokens, the model swap through its routes, the top-8 release on all three amounts, and the cache-off release on time and cost. The normal day passes, and no release moved the error rate. That answers the question at the top of the chapter, with the rules the gate was given.
Working rule: Check each flagged rule against the amount it reads, and ask what in the release moved that amount.
What the gate misses
A gate passes whatever it does not read. The five rules read message time, input tokens, cost, the error rate and route accuracy, and a release can change other things the gate never sees. Four of these matter in this chapter.
The first is quality. The gate reads traces, not answers. A release can route every message correctly, keep its tokens and its time, and still write worse replies, and this gate passes it. Judging a reply is a different job. Evaluating LLM Applications gives it a code check, which reads a reply's text against the item's own reference answer. A regression in quality needs a check of that kind, run on the same messages with the same paired comparison, and this chapter does not run one. The book judges no answer's quality.
The second is the tail. The 95th percentile is printed and not gated. On the 60 paired messages the prompt change's p95 difference points down while its mean points up, and the p95's interval is much wider than the mean's, as the paired comparison shows. The gate reads the mean because, on 60 messages, the mean's interval is the narrower of the two. A release whose tail grew could still pass this gate on its mean.
The third is the interval itself. A rule flags only when the end of the interval nearest the limit passes it, so a real rise can pass. The prompt change's message time is the example. Its mean sits under the limit, and its interval's upper end reaches past it. The gate cannot say whether that release moved time past its limit. It can only decline to flag it.
The fourth is the record. In production, two releases rarely meet the same messages, and comparing them on live traffic is the subject of Evaluating LLM Applications' variants on traffic. Every release in this chapter is a replay of calls the book recorded, and a replay answers only the calls its recording holds. A change that sends different calls cannot be gated here, because nothing answers them. Two more gaps follow from the same place. The error rate of the prompt change changes by +0.0% (95% interval +0.0% to +0.0%), and the baseline's own count of ERROR spans on its replay is 0, the status that chapter 8 explains. The error rule is in the gate, but these recordings do not trip it, so the chapter cannot show it catch an error. The cost lines rest on the book's price table. Chapter 6 says that a self-hosted model is billed by its machine and not by its tokens, so the dollar figures compare token prices and do not compare bills.
Working rule: Name in each gate's report what it does not read, beside its verdict, so a pass is not taken for a clean release.
The decisions this chapter made
- The prompt change is gated on its 60 paired messages, the model swap on all 200, the top-8 and cache-off releases on their 60, and the normal day on two unpaired days. The paired messages are the ones the baseline and the release share.
- We set the limits; the error rule is chapter 8's. The chapter applies them as printed and does not tune them to these recordings.
- The 95th percentile is printed and not gated, and the gate judges the mean of message time.
- The model swap's amounts are split into the suffix and the answers it lost, and its route accuracy is the model and the suffix together. Its cost rests on a price row with no source, and the chapter says so beside the cost line.
- The gate reads recorded calls, not live traffic, so every verdict here describes the recordings.
A difference means little without its interval, and the same messages are what keep the interval narrow enough to read. On 60 paired messages the prompt change's token difference is visible. The same 60 judged unpaired would hide it. That is why the chapter pairs every comparison it can, and why a reader who copies this gate should keep the pairing before the limits: the same limits, judged unpaired, pass the prompt change.
Working rule: Read a difference only with its interval beside it, on the same messages, and with the gate's blind spots printed beside its verdict.
This chapter, in this edition
Edition 2026.11.2Examples passed Nov 23, 20267 of 7 examples in this chapter pass
This book is open to contributions, so anyone can check it or correct it. Found something wrong? Report it with the section's ID, the last part of the link beside each heading, or fix it yourself with a pull request.