How to Test a Flaky AI Agent in CI: Build a Pass-Rate Gate in Python, Size It With Exact Binomial Math, and Catch a Regression a Single Run Would Miss
Learn to decide whether a new build of an AI agent is really worse than the old one: build an exact pass-rate gate in Python, work out how many runs it needs, and try it on a real local model.
You changed a prompt, swapped a model, or edited a tool, and now you want to know one thing: is the agent worse than it was yesterday? With ordinary code you run the tests and read the colour. With an AI agent the same input can pass on one run and fail on the next, so a single green or red build tells you very little. In this tutorial you will build a small Python pass-rate gate: a script that runs an agent many times on each build, compares the two pass counts with an exact statistical test, and fails the build only when the drop is bigger than run-to-run luck would explain.
Table Of Content
- What you will build
- Prerequisites
- The idea in plain words
- Step 1: See why one run is not a verdict
- Step 2: Turn two pass counts into a yes or no
- Step 3: Measure how often the gate lies
- Step 4: Work out how many runs you need
- Step 5: Why power can dip when you add runs
- Step 6: Add judge noise to the plan
- Step 7: Know what the gate cannot see
- Step 8: Put the gate behind a command
- Step 9: Run the gate on a real agent
- Set up the model
- The agent and its outcome check
- Why one email repeated 20 times is not 20 runs
- Collect the runs
- Check the gate on the real runs
- Step 10: Run it in CI
- Test the gate itself
- Common mistakes
- Check that everything works end to end
- What I did not check
- Where to go next
- Sources
By the end you will be able to answer four questions that every team testing agents runs into: how often does a one-run check catch a real regression, how many runs does a trustworthy gate need, what does a noisy AI judge cost you, and what can no pass-rate gate ever see. You will also run the gate on a real agent, a 1.5-billion-parameter model on your own machine, and watch it catch a regression that was planted on purpose.
The topic comes from DigitalOcean’s conceptual article How to Test AI Agents Before Production (Vinayak Baranwal, November 23, 2026). It publishes run counts for agent gates, and I wanted to see whether I could rebuild the arithmetic from scratch and get the same numbers. I could: every run count and error rate it reports for the two-sample gate reproduces exactly, as you will see in Steps 3 to 6. Everything below, the code, the tests and the real-model experiment, is my own.
What you will build
Four small pieces, all in one folder:
gate.py, the library: an exact one-sided Fisher test, the exact false-alarm rate and power of that test, and a planner that tells you how many runs you need.agent_gate.py, a command-line gate that reads two files of run results and exits with a code your CI system understands.agent.py, a tiny agent on a local model, with an outcome check written in plain code.test_gate.py, a test suite for the gate itself, so you can trust the thing that is judging your agent.
Prerequisites
- Python 3.13 on any operating system. I ran everything on Windows 11 with Python 3.13.14, NumPy 2.5.2, SciPy 1.18.1 and pytest 9.1.1. The gate itself needs only NumPy; SciPy is used to cross-check it and pytest to test it.
- Basic Python: functions, lists, loops. You do not need to know statistics. I explain every term when it first appears.
- For Step 8 only: Ollama 0.32.9 with the models
qwen2.5:1.5bandqwen2.5:0.5bpulled, and about 4 GB of free memory. Steps 1 to 7 and 9 need no model at all.
Create an empty folder, open a terminal in it, and install the packages:
python -m venv .venv
# Windows: .venv\Scripts\activate macOS and Linux: source .venv/bin/activate
pip install numpy scipy pytest requests
The idea in plain words
A run is one complete attempt by the agent at one task. An outcome check is code that looks at the result and says pass or fail. The pass rate of a build is passes divided by runs. DigitalOcean puts it this way: “A test result for an agent is a pass rate over many runs of one scenario.” A regression is a pass rate that fell by more than luck can explain, and a gate is the rule that turns two pass counts into a build decision.
Every gate can go wrong in two ways. A false alarm fails a build that is really fine. A miss lets a really worse build through. The chance of catching a real drop of a given size is the gate’s power. You cannot make both mistakes impossible. What you can do is choose how many runs to pay for and know exactly what you bought. That is the whole job of this tutorial.
Step 1: See why one run is not a verdict
Start by measuring the thing most teams do today: run the agent once and fail the build if that run fails. Suppose a healthy build passes 95% of the time. A regression to 85% is a 10-point drop, a big one. How often does a one-run check catch it? Save this as step01_single_run.py:
# step01_single_run.py
"""Step 1: how much does one run of the agent tell you about a build?"""
import numpy as np
TRIALS = 10_000
rng = np.random.default_rng(1)
for label, pass_rate in (
("healthy build (true pass rate 95%)", 0.95),
("regressed build (true pass rate 85%)", 0.85),
):
red = rng.random(TRIALS) >= pass_rate # True when the single run fails its check
print(f"{label}: the one-run check goes red in {red.mean():.1%} of {TRIALS:,} simulated builds")
print(f"a red run is {0.15 / 0.05:.0f} times as likely from the regressed build as from the healthy one")
The script plays the build 10,000 times for each pass rate. rng.random(TRIALS) >= pass_rate is true exactly when the single run fails, and .mean() turns that into a share of builds. Run it:
python step01_single_run.py
healthy build (true pass rate 95%): the one-run check goes red in 5.2% of 10,000 simulated builds
regressed build (true pass rate 85%): the one-run check goes red in 14.9% of 10,000 simulated builds
a red run is 3 times as likely from the regressed build as from the healthy one
Read the two numbers together. The one-run check fails about 5% of healthy builds for nothing, and it catches only about 15% of builds that really regressed by 10 points. The other 85% sail through green. The exact values are 5% and 15%; the small differences are simulation noise. A red run is only three times as likely from the regressed build as from the healthy one, which is weak evidence. That is the case for measuring a pass rate over many runs.
Step 2: Turn two pass counts into a yes or no
Now run each build many times, say 126 runs each, and count passes. Suppose the baseline passed 118 and the candidate passed 99. Is that a regression or bad luck? The classic answer is Fisher’s exact test. The idea is easy to state: pretend both builds really have the same pass rate, hand out all the passes at random among all the runs, and count how often the candidate would end up this far behind. That share is the p-value. If it is small, luck is an unlikely explanation. We will fail the build when the p-value is at most alpha, a limit you choose; 0.05 is the usual one. The test is one-sided because we only care whether the candidate got worse, not better.
Create gate.py with the code below. It is the whole library, so it looks long, but we will use it one function at a time: fisher_p in this step, reject_matrix, binom_pmf, gate_rates and simulate_gate in Step 3, normal_runs and plan_runs in Step 4, the one_sample_* functions in Step 5, observed_rate in Step 6 and detectable_drop in Step 7.
# gate.py
"""gate.py - a pass-rate gate for non-deterministic AI agents.
Contents: an exact one-sided Fisher test, the exact false-alarm rate and power of that
test, a run-count planner and a few helpers. Needs numpy (pip install numpy).
fisher_p() itself uses only the standard library.
"""
import math
from statistics import NormalDist
import numpy as np
MAX_RUNS = 3000
_LOGFACT = np.concatenate(([0.0], np.cumsum(np.log(np.arange(1, 2 * MAX_RUNS + 2, dtype=float)))))
def fisher_p(base_pass, cand_pass, n_base, n_cand):
"""One-sided exact p-value for 'the candidate's pass rate is LOWER than the baseline's'.
Fix the total number of passes. If both builds share one true pass rate, every way of
handing those passes out to the 2n runs is equally likely, so we count ways.
"""
if not (0 <= base_pass <= n_base and 0 <= cand_pass <= n_cand):
raise ValueError("pass counts must lie between 0 and the number of runs")
passes = base_pass + cand_pass
ways_total = math.comb(n_base + n_cand, passes)
ways_as_bad = 0
for x in range(base_pass, min(n_base, passes) + 1): # baseline got x passes or more
if passes - x <= n_cand:
ways_as_bad += math.comb(n_base, x) * math.comb(n_cand, passes - x)
return ways_as_bad / ways_total
def _log_comb(n, k):
return _LOGFACT[n] - _LOGFACT[k] - _LOGFACT[n - k]
def reject_matrix(n, alpha=0.05):
"""R[a, b] is True when a baseline with a passes and a candidate with b passes
(n runs each) fails the gate, that is when fisher_p(a, b, n, n) <= alpha."""
if n > MAX_RUNS:
raise ValueError("n is above MAX_RUNS")
s = np.arange(2 * n + 1)[:, None] # total passes
x = np.arange(n + 1)[None, :] # baseline passes
y = s - x # candidate passes
ok = (y >= 0) & (y <= n)
y = np.where(ok, y, 0)
log_pmf = np.where(ok, _log_comb(n, x) + _log_comb(n, y) - _log_comb(2 * n, s), -np.inf)
pmf = np.exp(log_pmf)
tail = np.cumsum(pmf[:, ::-1], axis=1)[:, ::-1] # tail[s, x] = P(baseline >= x | s)
a = np.arange(n + 1)[:, None]
b = np.arange(n + 1)[None, :]
return tail[a + b, a] <= alpha
def binom_pmf(n, p):
k = np.arange(n + 1)
if p <= 0:
out = np.zeros(n + 1)
out[0] = 1.0
return out
if p >= 1:
out = np.zeros(n + 1)
out[n] = 1.0
return out
return np.exp(_log_comb(n, k) + k * np.log(p) + (n - k) * np.log1p(-p))
def gate_rates(n, p_base, p_cand, alpha=0.05, R=None):
"""Exact (false_alarm, power) of the gate with n runs per build."""
if R is None:
R = reject_matrix(n, alpha)
pa = binom_pmf(n, p_base)
false_alarm = pa @ R @ binom_pmf(n, p_base) # both builds are really the same
power = pa @ R @ binom_pmf(n, p_cand) # the candidate really is worse
return float(false_alarm), float(power)
def one_sample_cutoff(n, p_base, alpha=0.05):
"""Known baseline rate: fail the build when its passes are <= the returned cutoff
(the largest c with P(passes <= c | p_base) <= alpha), or -1 when no cutoff exists."""
cdf = np.cumsum(binom_pmf(n, p_base))
inside = np.nonzero(cdf <= alpha)[0]
return int(inside[-1]) if len(inside) else -1
def one_sample_rates(n, p_base, p_cand, alpha=0.05):
"""Exact (false_alarm, power) of the one-sample gate."""
c = one_sample_cutoff(n, p_base, alpha)
if c < 0:
return 0.0, 0.0
return float(binom_pmf(n, p_base)[: c + 1].sum()), float(binom_pmf(n, p_cand)[: c + 1].sum())
def normal_runs(p_base, p_cand, alpha=0.05, power=0.80):
"""Textbook normal-approximation run count per build (one-sided, pooled variance)."""
z_a = NormalDist().inv_cdf(1 - alpha)
z_b = NormalDist().inv_cdf(power)
p_bar = (p_base + p_cand) / 2
top = z_a * math.sqrt(2 * p_bar * (1 - p_bar)) + z_b * math.sqrt(
p_base * (1 - p_base) + p_cand * (1 - p_cand)
)
return math.ceil(top ** 2 / (p_base - p_cand) ** 2)
def plan_runs(p_base, p_cand, alpha=0.05, power=0.80, margin=40):
"""Exact run counts per build: (first_n, stable_n).
first_n is the first n that reaches the target power. Because pass counts are whole
numbers, power can dip below the target again for a while, so stable_n is the n after
the LAST dip that we see (we stop once `margin` consecutive sizes stay above target).
"""
n0 = normal_runs(p_base, p_cand, alpha, power)
n = max(5, int(0.9 * n0))
first = None
last_fail = None
streak = 0
while n <= min(MAX_RUNS, 4 * n0 + 100):
if gate_rates(n, p_base, p_cand, alpha)[1] >= power:
if first is None:
first = n
streak += 1
if streak >= margin:
return first, (last_fail + 1 if last_fail is not None else first)
else:
last_fail = n
streak = 0
n += 1
raise RuntimeError("target power not reached inside the search window")
def detectable_drop(n, p_base, alpha=0.05, power=0.80, step=0.0025):
"""Smallest drop (a multiple of `step`) the gate catches with the target power."""
R = reject_matrix(n, alpha)
pa = binom_pmf(n, p_base)
k = 1
while p_base - k * step >= 0:
if float(pa @ R @ binom_pmf(n, p_base - k * step)) >= power:
return round(k * step, 6)
k += 1
return None
def observed_rate(p, flip):
"""Pass rate a noisy judge reports when it flips a fraction `flip` of its verdicts."""
return p * (1 - flip) + (1 - p) * flip
def simulate_gate(n, p_base, p_cand, trials, seed, alpha=0.05):
"""Fraction of simulated builds that fail the gate (Monte Carlo, for cross-checks)."""
rng = np.random.default_rng(seed)
R = reject_matrix(n, alpha)
a = rng.binomial(n, p_base, trials)
b = rng.binomial(n, p_cand, trials)
return float(R[a, b].mean())
Look at fisher_p first. It uses only the standard library. math.comb(n, k) counts the ways to choose k items from n, so the function literally counts arrangements: the total number of ways to hand out the passes, and the number of ways in which the baseline gets at least as many as it did. The ratio is the p-value. Because Python integers have no size limit, the counts stay exact even at thousands of runs.
Save step02_fisher.py. It first counts a tiny case by hand and then runs the real size, checking itself against SciPy’s fisher_exact with alternative="greater", which asks whether the first row’s pass odds are higher:
# step02_fisher.py
"""Step 2: the exact test, first by counting a tiny case by hand, then at CI size."""
from math import comb
from scipy.stats import fisher_exact
from gate import fisher_p
# A tiny case: 6 runs per build. The baseline passed 6, the candidate passed 3.
n, a, b = 6, 6, 3
passes = a + b
total = comb(2 * n, passes)
print(f"{passes} passes handed out among {2 * n} runs: {total} equally likely ways")
tail = 0
for x in range(a, min(n, passes) + 1): # baseline got x passes, candidate got the rest
ways = comb(n, x) * comb(n, passes - x)
tail += ways
print(f" baseline gets {x}, candidate gets {passes - x}: {ways} ways")
print(f"p = {tail}/{total} = {tail / total:.4f} (fisher_p says {fisher_p(a, b, n, n):.4f})")
# CI size: 126 runs per build.
n, a, b = 126, 118, 99
mine = fisher_p(a, b, n, n)
theirs = fisher_exact([[a, n - a], [b, n - b]], alternative="greater")[1]
print(f"baseline {a}/{n}, candidate {b}/{n}: fisher_p = {mine:.6f}, scipy = {theirs:.6f}")
for b in (112, 108, 104, 100):
print(f"baseline {a}/{n}, candidate {b}/{n}: p = {fisher_p(a, b, n, n):.4f}")
python step02_fisher.py
9 passes handed out among 12 runs: 220 equally likely ways
baseline gets 6, candidate gets 3: 20 ways
p = 20/220 = 0.0909 (fisher_p says 0.0909)
baseline 118/126, candidate 99/126: fisher_p = 0.000417, scipy = 0.000417
baseline 118/126, candidate 112/126: p = 0.1321
baseline 118/126, candidate 108/126: p = 0.0303
baseline 118/126, candidate 104/126: p = 0.0052
baseline 118/126, candidate 100/126: p = 0.0007
In the toy case, 9 passes among 12 runs can be handed out in 220 ways, and only 20 of them give the baseline all 6 of its passes, so p is 20 out of 220, about 0.09. At CI size the p-value for 118 against 99 is 0.000417, and SciPy agrees to the last printed digit. The last four lines show where the line falls: with the baseline at 118 of 126, a candidate at 112 passes (p = 0.1321) and a candidate at 108 fails (p = 0.0303). The decision boundary sits between them, at a drop of about 7 points on these counts.
Check before moving on: your p-value for 118 against 99 should be 0.000417. If it is not, the most common cause is the direction: the tail must start at the baseline’s pass count, not the candidate’s.
Step 3: Measure how often the gate lies
A p-value rule is only useful if you know its error rates. The false-alarm rate is the share of identical builds the gate fails. The power is the share of really regressed builds it catches. Both can be computed exactly, with no simulation: for every possible pair of pass counts, decide whether the gate would fail it, then add up the binomial probabilities of the pairs that fail. reject_matrix builds that table of decisions, and gate_rates adds up the probabilities. Because that is a lot of arithmetic to trust, the script also simulates 10,000 builds as a cross-check. Save step03_rates.py:
# step03_rates.py
"""Step 3: the exact false-alarm rate and power of the gate, checked by simulation."""
import gate
for n, p_base, p_cand in ((126, 0.95, 0.85), (371, 0.95, 0.90)):
false_alarm, power = gate.gate_rates(n, p_base, p_cand)
sim_false = gate.simulate_gate(n, p_base, p_base, 10_000, seed=1)
sim_power = gate.simulate_gate(n, p_base, p_cand, 10_000, seed=2)
print(f"{n} runs per build, true pass rate {p_base:.0%} -> {p_cand:.0%}")
print(f" healthy builds failed (false alarms): exact {false_alarm:.4f}, 10,000 simulated builds {sim_false:.4f}")
print(f" regressed builds caught (power): exact {power:.4f}, 10,000 simulated builds {sim_power:.4f}")
python step03_rates.py
126 runs per build, true pass rate 95% -> 85%
healthy builds failed (false alarms): exact 0.0243, 10,000 simulated builds 0.0225
regressed builds caught (power): exact 0.8014, 10,000 simulated builds 0.7996
371 runs per build, true pass rate 95% -> 90%
healthy builds failed (false alarms): exact 0.0355, 10,000 simulated builds 0.0359
regressed builds caught (power): exact 0.8000, 10,000 simulated builds 0.8034
With 126 runs per build, a healthy build is failed 2.43% of the time and a 95%-to-85% regression is caught 80.14% of the time. With 371 runs, the numbers for a 95%-to-90% drop are 3.55% and 80.00%. The simulations land within noise of the exact values. These four figures are the same ones DigitalOcean’s harness output reports, to the printed digit, which is a good sign that two independent implementations agree.
Notice that the false-alarm rates are below the 5% you asked for. Pass counts are whole numbers, so an exact test cannot hit 5% precisely; it plays safe and stays under. You pay for that caution with a few extra runs.
Step 4: Work out how many runs you need
This is the question the whole approach exists to answer. Pick a baseline pass rate, the smallest drop you care about, and the power you want, and ask how many runs per build achieve it. The textbook shortcut is a normal approximation, a formula that treats pass counts as a smooth bell curve. normal_runs implements it. The exact planner, plan_runs, starts near the textbook answer and checks the true power of every size, one at a time, until it finds the first size that works. Save step04_sizing.py:
# step04_sizing.py
"""Step 4: how many runs per build? Textbook estimate, first n that works, and stable n."""
import time
import gate
BASE = 0.95
print("target power 80%, then 90%; alpha = 0.05; baseline pass rate 95%")
print("drop_to power textbook first_n stable_n false_alarm power_at_stable_n")
start = time.time()
for power in (0.80, 0.90):
for drop_to in (0.92, 0.90, 0.85):
textbook = gate.normal_runs(BASE, drop_to, power=power)
first, stable = gate.plan_runs(BASE, drop_to, power=power)
false_alarm, got = gate.gate_rates(stable, BASE, drop_to)
print(f"{drop_to:<8.2f} {power:<6.2f} {textbook:<9} {first:<8} {stable:<9} {false_alarm:<12.4f} {got:.4f}")
print(f"({time.time() - start:.0f} s)")
python step04_sizing.py
target power 80%, then 90%; alpha = 0.05; baseline pass rate 95%
drop_to power textbook first_n stable_n false_alarm power_at_stable_n
0.92 0.80 834 889 889 0.0396 0.8004
0.90 0.80 343 371 371 0.0355 0.8000
0.85 0.80 111 126 126 0.0243 0.8014
0.92 0.90 1155 1207 1207 0.0413 0.9002
0.90 0.90 474 503 503 0.0365 0.9000
0.85 0.90 153 165 165 0.0280 0.9011
(31 s)
C:\Claude\Cowork\Sxz.io\sxz-automations\tmp\sxz-publisher\lab\gate.py:48: RuntimeWarning: overflow encountered in exp
pmf = np.where(ok, np.exp(log_pmf), 0.0)
The exact run counts at 80% power are 889, 371 and 126 per build for drops from 95% to 92%, 90% and 85%, and 1,207, 503 and 165 at 90% power. They are the same figures DigitalOcean’s table lists, and the textbook numbers (834, 343 and 111 at 80%) are the ones its harness reports as the normal approximation. The textbook formula is too small by 6% to 12% here, so budget from the exact column. The search took about half a minute on my machine for all six plans.
Read the table as a price list. A 3-point drop needs about seven times as many runs as a 10-point drop (889 against 126), because the runs you need grow roughly with the inverse square of the gap you want to see. Halving the drop you care about costs roughly three times as many runs (126 for 10 points, 371 for 5 points). Decide the smallest drop that would matter to your users before you decide how many runs to pay for.
Step 5: Why power can dip when you add runs
You might expect that more runs always means more power. Not exactly. DigitalOcean notes: “Power does not rise smoothly with the run count, because successes are whole numbers.” The effect is easiest to see in a simpler gate, the one-sample gate, which compares the candidate with a baseline pass rate you already know instead of re-measuring the baseline. one_sample_cutoff finds the largest pass count that is still unlikely enough to fail the build, and one_sample_rates computes its error rates. Save step05_sawtooth.py:
# step05_sawtooth.py
"""Step 5: power does not climb smoothly with the number of runs (one-sample gate)."""
import gate
BASE, DROP_TO = 0.95, 0.90
rows = []
for n in range(150, 260):
false_alarm, power = gate.one_sample_rates(n, BASE, DROP_TO)
rows.append((n, gate.one_sample_cutoff(n, BASE), false_alarm, power))
first = next(n for n, _, _, power in rows if power >= 0.80)
stable = 1 + max(n for n, _, _, power in rows if power < 0.80)
print(f"known baseline 95%, drop to 90%: first n with power >= 80% is {first}; power stays above 80% from n = {stable}")
print("runs fail if passes <= false_alarm power")
for n, cutoff, false_alarm, power in rows:
if first - 2 <= n <= first + 5 or stable - 2 <= n <= stable + 1:
flag = " <-- below 80%" if power < 0.80 else ""
print(f"{n:<5} {cutoff:<18} {false_alarm:<12.4f} {power:.4f}{flag}")
# The two-sample gate dips too, for some pass rates.
first2, stable2 = gate.plan_runs(0.60, 0.45)
print()
print(f"two-sample gate, 60% -> 45%: first n with power >= 80% is {first2}; stable from n = {stable2}")
print("runs power")
for n in range(first2 - 1, stable2 + 1):
power = gate.gate_rates(n, 0.60, 0.45)[1]
print(f"{n:<5} {power:.4f}{' <-- below 80%' if power < 0.80 else ''}")
python step05_sawtooth.py
known baseline 95%, drop to 90%: first n with power >= 80% is 169; power stays above 80% from n = 191
runs fail if passes <= false_alarm power
167 153 0.0414 0.7924 <-- below 80%
168 154 0.0432 0.7994 <-- below 80%
169 155 0.0450 0.8063
170 156 0.0469 0.8129
171 157 0.0488 0.8194
172 157 0.0265 0.7479 <-- below 80%
173 158 0.0277 0.7557 <-- below 80%
174 159 0.0289 0.7633 <-- below 80%
189 173 0.0286 0.7923 <-- below 80%
190 174 0.0298 0.7989 <-- below 80%
191 175 0.0311 0.8054
192 176 0.0324 0.8117
two-sample gate, 60% -> 45%: first n with power >= 80% is 144; stable from n = 152
runs power
143 0.7976 <-- below 80%
144 0.8018
145 0.8059
146 0.7866 <-- below 80%
147 0.7852 <-- below 80%
148 0.7875 <-- below 80%
149 0.7902 <-- below 80%
150 0.7940 <-- below 80%
151 0.7981 <-- below 80%
152 0.8021
Follow the fail if passes <= column. The gate fails a build when its passes are at or below that number. At 171 runs the cutoff is 157 and the power is 81.94%. At 172 runs the cutoff is still 157, because the next whole number would push the false-alarm rate over 5%. The gate has become more cautious: its false-alarm rate fell from 0.0488 to 0.0265, and its power fell from 81.94% to 74.79%. As runs keep growing the cutoff eventually moves up again, and power climbs back. The first size that reaches 80% is 169, but the size from which power stays above 80% is 191 (within the 150 to 259 runs this script scans; DigitalOcean’s harness checks up to 1,500). Plan with the second number. These match the figures in DigitalOcean’s article (169, 81.9% at 171, 74.8% at 172, and 191).
The two-sample gate dips as well, for some pass rates. The end of the output shows a drop from 60% to 45%: power reaches 80.18% at 144 runs and 80.59% at 145, falls to 78.66% at 146, and does not stay above 80% until 152. For the six plans in Step 4 the first size that works and the stable size happened to coincide, but that is not guaranteed, so plan_runs keeps scanning until forty sizes in a row stay above the target and reports both numbers.
Step 6: Add judge noise to the plan
Some agent tests grade results with another AI model, a judge, instead of code. Judges make mistakes. Suppose a judge flips 5% of its verdicts, calling some real passes failures and some real failures passes. Then the pass rate you observe is not the true pass rate: it is pulled toward 50%. The function observed_rate computes that pull, and the planner can use the observed rates instead. Save step06_judge.py:
# step06_judge.py
"""Step 6: a noisy AI judge shrinks the drop you can measure."""
import gate
print("judge flips observed pass rates observed drop runs per build (first, stable)")
for flip in (0.0, 0.02, 0.05, 0.10):
base = gate.observed_rate(0.95, flip)
cand = gate.observed_rate(0.90, flip)
first, stable = gate.plan_runs(base, cand)
print(f"{flip:<13.0%} {base:.3f} -> {cand:.3f} {base - cand:.3f} {first}, {stable}")
python step06_judge.py
judge flips observed pass rates observed drop runs per build (first, stable)
0% 0.950 -> 0.900 0.050 371, 371
2% 0.932 -> 0.884 0.048 480, 480
5% 0.905 -> 0.860 0.045 670, 670
10% 0.860 -> 0.820 0.040 1085, 1085
C:\Claude\Cowork\Sxz.io\sxz-automations\tmp\sxz-publisher\lab\gate.py:48: RuntimeWarning: overflow encountered in exp
pmf = np.where(ok, np.exp(log_pmf), 0.0)
A drop from 95% to 90% is a 5-point gap in truth. Through a judge that flips 5% of verdicts, the same drop looks like 90.5% to 86.0%, a gap of 4.5 points, with more variance around it. The gate then needs 670 runs per build instead of 371, which is the figure DigitalOcean reports for this case. At a 10% flip rate you need 1,085. If you can write an outcome check in code, do it; if you must use a judge, measure its error rate first and budget for it. My earlier tutorial on calibrating an LLM judge against human ratings with Cohen’s kappa shows how to measure it.
Step 7: Know what the gate cannot see
A pass-rate gate answers one question: did the typical pass rate drop? It cannot promise that a rare failure is absent. If something goes wrong once in 1,000 runs, a 126-run gate sees it with only 11.8% probability. Zero failures in your sample is evidence, not proof, and the honest way to state it is an upper bound. With zero failures in n runs, the failure rate is below 1 - 0.05 ** (1 / n) with 95% confidence, which is very close to the “rule of three”, 3 divided by n. The same script also answers the question you should ask before every nightly run: what is the smallest drop my run count can see? Save step07_rare.py:
# step07_rare.py
"""Step 7: what a pass-rate gate cannot see - rare failures."""
import math
import gate
rare = 0.001 # a failure that happens once in 1,000 runs
for n in (126, 371, 1000, 2995):
print(f"{n:>5} runs: chance of seeing at least one 1-in-1,000 failure = {1 - (1 - rare) ** n:.1%}")
need = math.ceil(math.log(0.05) / math.log(1 - rare))
print(f"runs needed to see it with 95% probability: {need}")
print()
print("zero failures in n runs: the 95% upper bound on the true failure rate")
for n in (30, 126, 371, 1000):
exact = 1 - 0.05 ** (1 / n)
print(f"{n:>5} runs: exact bound {exact:.2%}, rule of three (3/n) {3 / n:.2%}")
print()
print("smallest drop from a 95% baseline that the gate catches 80% of the time")
for n in (30, 60, 126, 371, 889):
print(f"{n:>5} runs per build: {gate.detectable_drop(n, 0.95):.2%}")
python step07_rare.py
126 runs: chance of seeing at least one 1-in-1,000 failure = 11.8%
371 runs: chance of seeing at least one 1-in-1,000 failure = 31.0%
1000 runs: chance of seeing at least one 1-in-1,000 failure = 63.2%
2995 runs: chance of seeing at least one 1-in-1,000 failure = 95.0%
runs needed to see it with 95% probability: 2995
zero failures in n runs: the 95% upper bound on the true failure rate
30 runs: exact bound 9.50%, rule of three (3/n) 10.00%
126 runs: exact bound 2.35%, rule of three (3/n) 2.38%
371 runs: exact bound 0.80%, rule of three (3/n) 0.81%
1000 runs: exact bound 0.30%, rule of three (3/n) 0.30%
smallest drop from a 95% baseline that the gate catches 80% of the time
30 runs per build: 27.00%
60 runs per build: 16.25%
126 runs per build: 10.00%
371 runs per build: 5.00%
889 runs per build: 3.00%
To see a 1-in-1,000 failure with 95% probability you need 2,995 runs, far more than any gate. Rare, severe failures belong to runtime safeguards: allow lists, spending limits, human approval for risky actions. The bottom table is the most practical one: from a 95% baseline, 30 runs per build can only reliably catch a 27-point drop, 126 runs catch 10 points, 371 catch 5 points and 889 catch 3 points. If your gate runs 30 times and reports green, it has told you very little. The command-line gate below prints this warning for you.
Step 8: Put the gate behind a command
A function is not yet something a CI system can use. CI systems read one thing from a job: the exit code, where 0 means success and anything else means failure. agent_gate.py wraps the library in a command with four outcomes. RED (exit 1): the candidate’s pass rate is lower than noise explains. GREEN (exit 0): no regression found, and the run count is big enough to have seen a drop of the size you care about. AMBER (exit 3): no regression found, but the run count is too small to have seen that drop, so the green is not worth much. Exit 2 means the input could not be read. The AMBER state is the important one. “Not significant” and “no problem” are different statements, and the command refuses to blur them.
# agent_gate.py
"""agent_gate.py - decide whether a candidate agent build is worse than the baseline.
usage: python agent_gate.py BASELINE.jsonl CANDIDATE.jsonl [--alpha 0.05] [--drop 0.10]
Each input line is a JSON object with a boolean field "ok" (did the outcome check pass).
Exit codes: 0 no regression found (and enough runs to have seen a drop of --drop),
1 regression: the candidate's pass rate is lower than noise explains,
2 bad input,
3 inconclusive: no regression found, but too few runs to see a drop of --drop.
"""
import argparse
import json
import sys
import gate
def load(path):
passes = total = 0
with open(path, encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
if not line.strip():
continue
try:
ok = json.loads(line)["ok"]
except (ValueError, KeyError, TypeError):
raise ValueError(f"{path} line {number}: expected a JSON object with a boolean 'ok'")
if not isinstance(ok, bool):
raise ValueError(f"{path} line {number}: 'ok' must be true or false")
total += 1
passes += ok
if total == 0:
raise ValueError(f"{path}: no runs")
return passes, total
def main(argv=None):
ap = argparse.ArgumentParser()
ap.add_argument("baseline")
ap.add_argument("candidate")
ap.add_argument("--alpha", type=float, default=0.05)
ap.add_argument("--drop", type=float, default=0.10, help="smallest drop you care about")
args = ap.parse_args(argv)
try:
a, n_a = load(args.baseline)
b, n_b = load(args.candidate)
except (OSError, ValueError) as exc:
print(f"error: {exc}")
return 2
if n_a != n_b:
print(f"error: use the same number of runs per build ({n_a} against {n_b})")
return 2
p = gate.fisher_p(a, b, n_a, n_b)
print(f"baseline {a}/{n_a} = {a / n_a:.1%}")
print(f"candidate {b}/{n_b} = {b / n_b:.1%}")
p_text = f"{p:.4f}" if p >= 0.0001 else f"{p:.2e}"
print(f"one-sided Fisher p = {p_text} (fail at p <= {args.alpha})")
if p <= args.alpha:
print("RED: the candidate's pass rate is lower than run-to-run noise explains")
return 1
p_hat = a / n_a
power = gate.gate_rates(n_a, p_hat, max(0.0, p_hat - args.drop), args.alpha)[1]
if power < 0.80:
smallest = gate.detectable_drop(n_a, p_hat, args.alpha)
shown = "more than a 50-point drop" if smallest is None else f"a drop of about {smallest:.1%}"
print(f"AMBER: no regression found, but {n_a} runs per build catch a {args.drop:.0%} drop only {power:.0%} of the time")
print(f" at this size the gate can reliably see {shown} and nothing smaller")
return 3
print(f"GREEN: no regression found; {n_a} runs per build catch a {args.drop:.0%} drop {power:.0%} of the time")
return 0
if __name__ == "__main__":
sys.exit(main())
Two details are worth reading in the code. The loader insists that ok is a real JSON boolean, so a stray "true" string or a missing field stops the run instead of counting as a pass. And the power check uses the baseline’s measured pass rate together with the --drop you pass in (10 points by default), so the AMBER verdict reflects the build you actually have.
To try it without any model, save make_runs.py, which writes a results file with a chosen number of passes:
# make_runs.py
"""make_runs.py FILE PASSES TOTAL - write a made-up results file for trying agent_gate.py."""
import json
import sys
path, passes, total = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])
with open(path, "w", encoding="utf-8", newline="\n") as f:
for i in range(total):
f.write(json.dumps({"ok": i < passes}) + chr(10))
print(f"wrote {path}: {passes} passes in {total} runs")
mkdir out
python make_runs.py out/try_base.jsonl 118 126
python make_runs.py out/try_cand.jsonl 99 126
python agent_gate.py out/try_base.jsonl out/try_cand.jsonl
echo $?
On Windows PowerShell use $LASTEXITCODE instead of $?. I ran the last two commands three times, giving the candidate 99, 108 and 112 passes out of 126:
wrote out/try_base.jsonl: 118 passes in 126 runs
wrote out/try_cand.jsonl: 99 passes in 126 runs
$ python agent_gate.py out/try_base.jsonl out/try_cand.jsonl
baseline 118/126 = 93.7%
candidate 99/126 = 78.6%
one-sided Fisher p = 0.0004 (fail at p <= 0.05)
RED: the candidate's pass rate is lower than run-to-run noise explains
exit code 1
wrote out/try_cand.jsonl: 108 passes in 126 runs
$ python agent_gate.py out/try_base.jsonl out/try_cand.jsonl
baseline 118/126 = 93.7%
candidate 108/126 = 85.7%
one-sided Fisher p = 0.0303 (fail at p <= 0.05)
RED: the candidate's pass rate is lower than run-to-run noise explains
exit code 1
wrote out/try_cand.jsonl: 112 passes in 126 runs
$ python agent_gate.py out/try_base.jsonl out/try_cand.jsonl
baseline 118/126 = 93.7%
candidate 112/126 = 88.9%
one-sided Fisher p = 0.1321 (fail at p <= 0.05)
AMBER: no regression found, but 126 runs per build catch a 10% drop only 76% of the time
at this size the gate can reliably see a drop of about 10.8% and nothing smaller
exit code 3
With 99 passes the verdict is RED with p = 0.0004. With 108 passes it is still RED (p = 0.0303), but only just: this is the edge you met in Step 2. With 112 passes the p-value is 0.1321, so the gate does not fail the build, and it says AMBER because 126 runs per build catch a 10-point drop from this 93.7% baseline only 76% of the time. At a 95% baseline you saw 80% in Step 3; the baseline rate matters, because pass counts near the extremes carry less noise. The message tells you the smallest drop this run count can reliably see, about 10.8 points.
Step 9: Run the gate on a real agent
Everything so far used made-up numbers. Now let us point the gate at a real agent running on your own machine. The task is deliberately ordinary: read a customer email and return the order to refund and the amount, as JSON. The outcome check is code, not a judge, so there is no judge noise to budget for.
Set up the model
Install Ollama, then pull two small models. The first is the “good” build and the second is the cheaper model the regression will use:
ollama pull qwen2.5:1.5b
ollama pull qwen2.5:0.5b
Start the server with three parallel slots, so the script can send three runs at a time. In Git Bash or Linux or macOS run OLLAMA_NUM_PARALLEL=3 ollama serve; in PowerShell run $env:OLLAMA_NUM_PARALLEL = "3"; ollama serve. My tutorial on Ollama parallel requests explains what the setting does. I used Ollama 0.32.9 on Windows 11 with a 4 GB NVIDIA RTX A400.
The agent and its outcome check
Save agent.py. make_scenario invents an email with distractors, such as a phone number, a second order and a shipping fee, and remembers the right answer. ask sends the email to Ollama’s /api/chat endpoint with "format": "json" and a sampling temperature of 0.8, which is what makes runs differ. check is the outcome check: valid JSON, the right order id, and an amount that is a real number within half a cent of the right one. episode gives every run its own email and its own random seed. The build named routed is the regression: a cost-saving router that sends about one email in four to the 0.5-billion-parameter model.
# agent.py
"""agent.py - a tiny extraction agent on a local model (Ollama), plus its outcome check.
The task: read a customer email and return the order to refund and the amount.
The outcome check is plain code, so no AI judge is involved.
usage:
python agent.py runs LABEL BUILD N BASE # write out/runs_LABEL.jsonl
python agent.py seeds # what a fixed seed does to repeated runs
"""
import json
import random
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import requests
URL = "http://127.0.0.1:11434/api/chat"
OUT = Path(__file__).parent / "out"
PROMPT = (
'You read a customer email and reply with JSON only, shaped like {"order_id": "ORD-12345", "refund_usd": 12.5}. '
"order_id is the order the customer wants refunded. refund_usd is the amount of money the customer asks to get back, "
"without shipping fees. Ignore phone numbers, dates, shipping fees and other order numbers that are only "
"mentioned in passing."
)
# build name -> model. "routed" is the regression: a cost-saving router that sends
# about one email in four to the small model.
MODELS = {"good": "qwen2.5:1.5b", "tiny": "qwen2.5:0.5b"}
TEMPLATES = [
"Hi, my order {order} arrived damaged. I was charged ${amount:.2f} for the item plus ${fee:.2f} shipping. Please refund the item price. You can call me on {phone}. Thanks, Sam",
"Order {order} never showed up. I'd like my ${amount:.2f} back please. (My earlier order {other} was fine.) Reach me at {phone} after the {day}th.",
"Hello, I placed order {order} on March {day} and the headphones stopped working. Please send ${amount:.2f} back to my card. Order {other} is unrelated.",
"Refund request: order id {order}, amount ${amount:.2f}. Shipping was ${fee:.2f} and I know that is not refundable. Phone: {phone}.",
"Wrong size received for {order}. Keep the ${fee:.2f} shipping, just return ${amount:.2f} for the jacket. I also have {other} in transit, no problem there.",
"Hi team, could you refund {order}? The charge was ${amount:.2f}. My number is {phone}, best before {day} PM.",
]
def make_scenario(seed):
"""A made-up customer email with distractors, plus the answer the agent should give."""
rng = random.Random(seed)
s = {
"order": f"ORD-{rng.randint(10000, 99999)}",
"other": f"ORD-{rng.randint(10000, 99999)}",
"amount": rng.choice([12.50, 19.99, 24.00, 37.45, 42.00, 58.90, 64.25, 79.99, 120.00]),
"fee": rng.choice([4.99, 5.95, 7.50, 9.99]),
"phone": f"555-{rng.randint(100, 999)}-{rng.randint(1000, 9999)}",
"day": rng.randint(2, 27),
}
return {"text": rng.choice(TEMPLATES).format(**s), "order_id": s["order"], "refund_usd": s["amount"]}
def ask(model, scenario, seed, temperature=0.8):
body = {
"model": model,
"stream": False,
"format": "json",
"options": {"temperature": temperature, "seed": seed, "num_predict": 80, "num_ctx": 2048},
"messages": [
{"role": "system", "content": PROMPT},
{"role": "user", "content": scenario["text"]},
],
}
r = requests.post(URL, json=body, timeout=180)
r.raise_for_status()
return r.json()["message"]["content"]
def check(output, scenario):
"""Outcome check: valid JSON, the right order id, a number within half a cent of the right amount."""
try:
data = json.loads(output)
except ValueError:
return False
if not isinstance(data, dict):
return False
amount = data.get("refund_usd")
if isinstance(amount, bool) or not isinstance(amount, (int, float)):
return False
return data.get("order_id") == scenario["order_id"] and abs(amount - scenario["refund_usd"]) < 0.005
def episode(build, index, base):
seed = base * 100_000 + index # a different email AND a different sampling seed every run
scenario = make_scenario(seed)
name = build
if build == "routed":
name = "tiny" if random.Random(seed + 7).random() < 0.25 else "good"
output = ask(MODELS[name], scenario, seed)
return {"i": index, "seed": seed, "model": MODELS[name], "ok": check(output, scenario), "output": output}
def run_many(build, count, base, workers=3):
with ThreadPoolExecutor(workers) as pool:
return list(pool.map(lambda i: episode(build, i, base), range(count)))
def main(argv):
OUT.mkdir(exist_ok=True)
cmd = argv[1] if len(argv) > 1 else "seeds"
if cmd == "runs":
label, build, count, base = argv[2], argv[3], int(argv[4]), int(argv[5])
t0 = time.time()
rows = run_many(build, count, base)
with open(OUT / f"runs_{label}.jsonl", "w", encoding="utf-8", newline="\n") as f:
for r in rows:
f.write(json.dumps(r) + chr(10))
print(f"{label}: {sum(r['ok'] for r in rows)}/{count} passed, {time.time() - t0:.0f} s")
elif cmd == "seeds":
scenario = make_scenario(4242)
print("email:", scenario["text"])
print("expected:", scenario["order_id"], scenario["refund_usd"])
for label, seeds, temperature in (
("temperature 0.8, seed fixed at 7", [7] * 20, 0.8),
("temperature 0.8, seeds 1 to 20 ", list(range(1, 21)), 0.8),
("temperature 0.0, seed fixed at 7", [7] * 20, 0.0),
):
outputs = [ask(MODELS["good"], scenario, s, temperature) for s in seeds]
ok = sum(check(o, scenario) for o in outputs)
print(f"{label}: {len(set(outputs))} distinct outputs in 20 runs, {ok}/20 passed")
if __name__ == "__main__":
main(sys.argv)
Why one email repeated 20 times is not 20 runs
A tempting shortcut is to pick one email and run it 126 times. Try it:
python agent.py seeds
email: Order ORD-64485 never showed up. I'd like my $12.50 back please. (My earlier order ORD-27269 was fine.) Reach me at 555-488-6259 after the 10th.
expected: ORD-64485 12.5
temperature 0.8, seed fixed at 7: 1 distinct outputs in 20 runs, 20/20 passed
temperature 0.8, seeds 1 to 20 : 1 distinct outputs in 20 runs, 20/20 passed
temperature 0.0, seed fixed at 7: 1 distinct outputs in 20 runs, 20/20 passed
The 1.5-billion-parameter model gave one single output for all 20 runs of this email, even at temperature 0.8 with 20 different seeds. That suggests the model is nearly certain of every token for an easy email, so sampling hardly matters. Twenty runs of one email are one measurement, and the 20 out of 20 would tell you nothing about the other emails your agent will meet. The Ollama API documentation says: “For reproducible outputs, set seed to a number”. That is useful for debugging, but for a pass rate you want independent draws, so the runs in this lab vary the input as well as the seed.
Collect the runs
Collect 400 runs of the good build twice, with different emails and seeds, and 400 runs of the routed build. Each command writes one results file and prints a one-line summary:
python agent.py runs A1 good 400 1
python agent.py runs A2 good 400 2
python agent.py runs B routed 400 3
A1: 392/400 passed, 193 s
A2: 393/400 passed, 120 s
B: 358/400 passed, 123 s
The two good pools pass 98.0% and 98.2% of runs; the routed build passes 89.5%. The seconds are what my machine took and will differ on yours. Because the router sends only some emails to the small model, the damage is spread thin, which is exactly the kind of regression a single run misses.
Check the gate on the real runs
Save real_gate.py. It prints the pass counts, checks that runs behave like independent draws, runs the command-line gate on real files of 30, 126 and 400 runs, and then asks what the 126-run gate would do over thousands of CI runs.
# real_gate.py
"""real_gate.py - run the gate on the real agent runs saved by agent.py."""
import json
import subprocess
import sys
from pathlib import Path
import numpy as np
from scipy.stats import chi2
import gate
HERE = Path(__file__).parent
OUT = HERE / "out"
N = 126
def load(label):
with open(OUT / f"runs_{label}.jsonl", encoding="utf-8") as f:
return [json.loads(line)["ok"] for line in f]
def write_ci_file(path, runs):
with open(path, "w", encoding="utf-8", newline="\n") as f:
for ok in runs:
f.write(json.dumps({"ok": ok}) + chr(10))
a1, a2, b = load("A1"), load("A2"), load("B")
print("whole pools")
for label, runs in (("A1 good build", a1), ("A2 good build, fresh emails and seeds", a2), ("B routed build", b)):
print(f" {label}: {sum(runs)}/{len(runs)} passed = {sum(runs) / len(runs):.1%}")
with open(OUT / "runs_B.jsonl", encoding="utf-8") as f:
rows_b = [json.loads(line) for line in f]
for model in sorted({r["model"] for r in rows_b}):
sub = [r["ok"] for r in rows_b if r["model"] == model]
print(f" routed build, runs answered by {model}: {sum(sub)}/{len(sub)} passed")
print()
print(f"is a run really independent of the next? {len(a1) // 40} batches of 40 runs from each good pool")
batches = [sum(pool[i : i + 40]) for pool in (a1, a2) for i in range(0, 400, 40)]
p_hat = (sum(a1) + sum(a2)) / 800
stat = sum((x - 40 * p_hat) ** 2 for x in batches) / (40 * p_hat * (1 - p_hat))
print(f" passes per batch: {batches}")
print(f" binomial spread test: chi-square {stat:.1f} on {len(batches) - 1} degrees of freedom, p = {chi2.sf(stat, len(batches) - 1):.2f}")
print()
print("the command-line gate on real runs")
write_ci_file(OUT / "ci_baseline.jsonl", a1[:N])
write_ci_file(OUT / "ci_good_again.jsonl", a2[:N])
write_ci_file(OUT / "ci_routed.jsonl", b[:N])
write_ci_file(OUT / "short_baseline.jsonl", a1[:30])
write_ci_file(OUT / "short_routed.jsonl", b[:30])
write_ci_file(OUT / "full_baseline.jsonl", a1)
write_ci_file(OUT / "full_routed.jsonl", b)
for base, cand in (
("ci_baseline", "ci_good_again"),
("ci_baseline", "ci_routed"),
("short_baseline", "short_routed"),
("full_baseline", "full_routed"),
):
print(f"$ python agent_gate.py out/{base}.jsonl out/{cand}.jsonl")
done = subprocess.run(
[sys.executable, str(HERE / "agent_gate.py"), str(OUT / f"{base}.jsonl"), str(OUT / f"{cand}.jsonl")],
capture_output=True, text=True,
)
print(done.stdout.rstrip())
print(f"exit code {done.returncode}")
print()
print("what the gate would do over many CI runs (bootstrap draws of runs from the pools)")
rng = np.random.default_rng(5)
pa, pb = (sum(a1) + sum(a2)) / 800, sum(b) / 400
print(f"pass rates used: good {pa:.3f}, routed {pb:.3f}, drop {pa - pb:.3f}")
print("runs/build false alarms (good vs good) caught (good vs routed) exact power")
x_good = np.array(a1 + a2)
x_routed = np.array(b)
for n in (60, N, 250, 400):
R = gate.reject_matrix(n)
trials = 4000
fa = np.mean([R[rng.choice(x_good, n).sum(), rng.choice(x_good, n).sum()] for _ in range(trials)])
caught = np.mean([R[rng.choice(x_good, n).sum(), rng.choice(x_routed, n).sum()] for _ in range(trials)])
exact = gate.gate_rates(n, pa, pb, R=R)[1]
print(f"{n:<11} {fa:<26.3f} {caught:<24.3f} {exact:.3f}")
first, stable = gate.plan_runs(pa, pb)
print(f"runs per build for 80% power at this drop: {first} (stable from {stable})")
python real_gate.py
First the pools, the split of the routed build, and a check on independence:
whole pools
A1 good build: 392/400 passed = 98.0%
A2 good build, fresh emails and seeds: 393/400 passed = 98.2%
B routed build: 358/400 passed = 89.5%
routed build, runs answered by qwen2.5:0.5b: 61/95 passed
routed build, runs answered by qwen2.5:1.5b: 297/305 passed
is a run really independent of the next? 10 batches of 40 runs from each good pool
passes per batch: [39, 39, 37, 40, 40, 38, 40, 40, 39, 40, 40, 40, 39, 39, 40, 38, 39, 39, 40, 39]
binomial spread test: chi-square 18.7 on 19 degrees of freedom, p = 0.48
In the routed build, 95 of the 400 emails went to the small model, which passed 61 of them (64%); the other 305 went to the 1.5-billion-parameter model, which passed 297 (97%). The independence check cuts the 800 good runs into 20 batches of 40 and asks whether the batch-to-batch spread matches what independent runs would produce. The chi-square statistic is 18.7 on 19 degrees of freedom (p = 0.48), so nothing looks off. That is the check to run on your own agent before you trust a gate: if batches vary much more than the binomial spread predicts, your runs are not independent (for example because they share cached state), and every p-value in this tutorial is too optimistic.
Now the command-line gate on real files:
the command-line gate on real runs
$ python agent_gate.py out/ci_baseline.jsonl out/ci_good_again.jsonl
baseline 121/126 = 96.0%
candidate 125/126 = 99.2%
one-sided Fisher p = 0.9853 (fail at p <= 0.05)
GREEN: no regression found; 126 runs per build catch a 10% drop 84% of the time
exit code 0
$ python agent_gate.py out/ci_baseline.jsonl out/ci_routed.jsonl
baseline 121/126 = 96.0%
candidate 114/126 = 90.5%
one-sided Fisher p = 0.0649 (fail at p <= 0.05)
GREEN: no regression found; 126 runs per build catch a 10% drop 84% of the time
exit code 0
$ python agent_gate.py out/short_baseline.jsonl out/short_routed.jsonl
baseline 29/30 = 96.7%
candidate 27/30 = 90.0%
one-sided Fisher p = 0.3060 (fail at p <= 0.05)
AMBER: no regression found, but 30 runs per build catch a 10% drop only 18% of the time
at this size the gate can reliably see a drop of about 25.8% and nothing smaller
exit code 3
$ python agent_gate.py out/full_baseline.jsonl out/full_routed.jsonl
baseline 392/400 = 98.0%
candidate 358/400 = 89.5%
one-sided Fisher p = 2.73e-07 (fail at p <= 0.05)
RED: the candidate's pass rate is lower than run-to-run noise explains
exit code 1
Read these four verdicts one at a time, because each teaches something.
- Good against good, 126 runs (121 against 125 passes): p = 0.9853, GREEN. The second sample happened to do better, and a one-sided gate does not care.
- Good against routed, 126 runs (121 against 114 passes, 96.0% against 90.5%): p = 0.0649, GREEN. This is a miss. The real drop was 8.6 points, which 126 runs per build catch about 86% of the time (you will see that figure below), so roughly one CI run in seven gets through like this one. The first 126 baseline runs also happened to land at 96.0% instead of 98.1%, which shrank the visible gap to 5.5 points. One gate decision is one draw from a distribution; that is why the planning in Steps 3 and 4 matters.
- Good against routed, 30 runs (29 against 27 passes): p = 0.3060, AMBER, exit 3. At 30 runs per build the gate catches a 10-point drop only 18% of the time, and it tells you so.
- Good against routed, 400 runs (392 against 358 passes, 98.0% against 89.5%): p = 2.73e-07, RED, exit 1. With enough runs the same regression is unmistakable.
The last table answers “what would the 126-run gate do over many CI runs?” It draws n runs with replacement from the saved pools, 4,000 times for each size, and counts how often the gate fails the build. This is a bootstrap: it treats the measured pass rates as the truth. The last column is the exact power from gate_rates.
what the gate would do over many CI runs (bootstrap draws of runs from the pools)
pass rates used: good 0.981, routed 0.895, drop 0.086
runs/build false alarms (good vs good) caught (good vs routed) exact power
60 0.001 0.490 0.479
126 0.009 0.859 0.861
250 0.024 0.994 0.994
400 0.025 1.000 1.000
runs per build for 80% power at this drop: 110 (stable from 110)
The simulated and exact columns agree. At 126 runs per build the gate catches the routed build 85.9% of the time (exact: 86.1%) and falsely fails a good build 0.9% of the time. At 60 runs it catches the regression barely half the time (49%). At 250 runs it catches it 99.4% of the time. The planner says 110 runs per build would be enough for 80% power at this 8.6-point drop, because a 98% baseline is a quiet one.
Step 10: Run it in CI
A CI job can call the command directly, because its exit code is already the contract. Save this wrapper as ci_gate.sh. It maps every outcome to a message and a status, and it treats AMBER as a blocked build, because a gate that cannot see the drop you care about is not protecting you:
#!/usr/bin/env bash
# usage: bash ci_gate.sh BASELINE.jsonl CANDIDATE.jsonl
python agent_gate.py "$1" "$2" --drop 0.10
code=$?
case $code in
0) echo "ci: gate green, build may merge" ;;
1) echo "ci: regression, build blocked"; exit 1 ;;
3) echo "ci: too few runs to judge, build blocked"; exit 1 ;;
*) echo "ci: gate could not read its input"; exit 2 ;;
esac
bash ci_gate.sh out/ci_baseline.jsonl out/ci_good_again.jsonl
bash ci_gate.sh out/short_baseline.jsonl out/short_routed.jsonl
bash ci_gate.sh out/full_baseline.jsonl out/full_routed.jsonl
$ bash ci_gate.sh out/ci_baseline.jsonl out/ci_good_again.jsonl
baseline 121/126 = 96.0%
candidate 125/126 = 99.2%
one-sided Fisher p = 0.9853 (fail at p <= 0.05)
GREEN: no regression found; 126 runs per build catch a 10% drop 84% of the time
ci: gate green, build may merge
exit code 0
$ bash ci_gate.sh out/short_baseline.jsonl out/short_routed.jsonl
baseline 29/30 = 96.7%
candidate 27/30 = 90.0%
one-sided Fisher p = 0.3060 (fail at p <= 0.05)
AMBER: no regression found, but 30 runs per build catch a 10% drop only 18% of the time
at this size the gate can reliably see a drop of about 25.8% and nothing smaller
ci: too few runs to judge, build blocked
exit code 1
$ bash ci_gate.sh out/full_baseline.jsonl out/full_routed.jsonl
baseline 392/400 = 98.0%
candidate 358/400 = 89.5%
one-sided Fisher p = 2.73e-07 (fail at p <= 0.05)
RED: the candidate's pass rate is lower than run-to-run noise explains
ci: regression, build blocked
exit code 1
The three cases give exit 0, 1 and 1. I tested this script only in a local shell; I did not run it on a hosted CI service, so adapt the call to your own system. Three habits make the gate affordable and honest. First, run it on a schedule, such as nightly or before a release, and keep the cheap deterministic checks (parsers, tool code, schema checks against recorded model responses) on every commit, because a gate that runs 126 times for each of two builds costs 252 runs, which is 252 times what a single-run check does. Second, pin a dated model version where your provider offers one, so the pass rate cannot move on a day you shipped nothing. Third, quarantine a flaky scenario in a report instead of letting it block merges forever.
Test the gate itself
The gate judges your agent, so a bug in the gate is a bug in every decision. Save test_gate.py. The tests compare fisher_p with SciPy on 300 random tables, compare the fast table against the slow definition for every pair of counts at two sizes, compare the exact error rates against a brute-force enumeration, check that the false-alarm rate never exceeds alpha, reproduce the one-sample dip and a two-sample dip, and run the command-line tool for every exit code.
# test_gate.py
import json
import random
import subprocess
import sys
from math import comb
from pathlib import Path
import pytest
from scipy.stats import fisher_exact
import gate
HERE = Path(__file__).parent
def brute_rates(n, p0, p1, alpha):
pm0 = [comb(n, k) * p0 ** k * (1 - p0) ** (n - k) for k in range(n + 1)]
pm1 = [comb(n, k) * p1 ** k * (1 - p1) ** (n - k) for k in range(n + 1)]
fa = pw = 0.0
for a in range(n + 1):
for b in range(n + 1):
if gate.fisher_p(a, b, n, n) <= alpha:
fa += pm0[a] * pm0[b]
pw += pm0[a] * pm1[b]
return fa, pw
def test_fisher_matches_scipy_on_random_tables():
rng = random.Random(7)
for _ in range(300):
n1 = rng.randint(1, 60)
n2 = rng.randint(1, 60)
a = rng.randint(0, n1)
b = rng.randint(0, n2)
want = fisher_exact([[a, n1 - a], [b, n2 - b]], alternative="greater")[1]
assert gate.fisher_p(a, b, n1, n2) == pytest.approx(want, rel=1e-9, abs=1e-15)
def test_fisher_edges():
assert gate.fisher_p(0, 0, 10, 10) == 1.0
assert gate.fisher_p(10, 10, 10, 10) == 1.0
assert gate.fisher_p(6, 3, 6, 6) == pytest.approx(20 / 220)
assert gate.fisher_p(8, 0, 8, 8) == pytest.approx(1 / comb(16, 8))
with pytest.raises(ValueError):
gate.fisher_p(11, 0, 10, 10)
def test_fisher_direction():
# a candidate that is better than the baseline must never look like a regression
assert gate.fisher_p(5, 10, 10, 10) > 0.5
assert gate.fisher_p(10, 5, 10, 10) < 0.05
def test_p_value_grows_with_candidate_passes():
ps = [gate.fisher_p(40, b, 50, 50) for b in range(51)]
assert all(x <= y + 1e-15 for x, y in zip(ps, ps[1:]))
@pytest.mark.parametrize("n", [12, 25])
def test_reject_matrix_equals_direct_p_values(n):
R = gate.reject_matrix(n, 0.05)
for a in range(n + 1):
for b in range(n + 1):
assert bool(R[a, b]) == (gate.fisher_p(a, b, n, n) <= 0.05)
def test_rates_match_brute_force():
fa, pw = gate.gate_rates(20, 0.9, 0.7)
want_fa, want_pw = brute_rates(20, 0.9, 0.7, 0.05)
assert fa == pytest.approx(want_fa, abs=1e-12)
assert pw == pytest.approx(want_pw, abs=1e-12)
@pytest.mark.parametrize("n,p", [(10, 0.5), (30, 0.9), (60, 0.95), (126, 0.95), (200, 0.7)])
def test_false_alarm_never_above_alpha(n, p):
fa, _ = gate.gate_rates(n, p, p)
assert fa <= 0.05
def test_power_grows_with_the_size_of_the_drop():
powers = [gate.gate_rates(80, 0.95, p)[1] for p in (0.94, 0.9, 0.85, 0.8, 0.7)]
assert powers == sorted(powers)
def test_normal_runs_textbook_values():
assert gate.normal_runs(0.95, 0.92) == 834
assert gate.normal_runs(0.95, 0.90) == 343
assert gate.normal_runs(0.95, 0.85) == 111
def test_plan_runs_properties():
first, stable = gate.plan_runs(0.95, 0.85)
assert first <= stable
assert gate.gate_rates(first, 0.95, 0.85)[1] >= 0.80
assert gate.gate_rates(first - 1, 0.95, 0.85)[1] < 0.80
for n in range(stable, stable + 25):
assert gate.gate_rates(n, 0.95, 0.85)[1] >= 0.80
if stable > first:
assert gate.gate_rates(stable - 1, 0.95, 0.85)[1] < 0.80
def test_exact_run_count_is_above_the_normal_approximation():
first, _ = gate.plan_runs(0.95, 0.85)
assert first > gate.normal_runs(0.95, 0.85)
def test_detectable_drop_shrinks_with_more_runs():
drops = [gate.detectable_drop(n, 0.95) for n in (30, 60, 126, 371)]
assert drops == sorted(drops, reverse=True)
assert drops[0] > 0.10 > drops[-1]
def test_observed_rate_judge_noise():
assert gate.observed_rate(0.95, 0.0) == 0.95
assert gate.observed_rate(0.95, 0.05) == pytest.approx(0.905)
assert gate.observed_rate(0.5, 0.2) == pytest.approx(0.5)
def test_simulation_agrees_with_exact_power():
_, exact = gate.gate_rates(60, 0.95, 0.75)
sim = gate.simulate_gate(60, 0.95, 0.75, 20000, seed=3)
assert abs(sim - exact) < 4 * (exact * (1 - exact) / 20000) ** 0.5
def write_runs(path, passes, total):
with open(path, "w", newline="\n") as f:
for i in range(total):
f.write(json.dumps({"ok": i < passes}) + chr(10))
def run_cli(tmp_path, base, cand, n, *extra):
b = tmp_path / "base.jsonl"
c = tmp_path / "cand.jsonl"
write_runs(b, base, n)
write_runs(c, cand, n)
cmd = [sys.executable, str(HERE / "agent_gate.py"), str(b), str(c), *extra]
return subprocess.run(cmd, capture_output=True, text=True)
def test_cli_green_red_amber_and_bad_input(tmp_path):
green = run_cli(tmp_path, 380, 379, 400)
assert green.returncode == 0, green.stdout
# 126 runs per build cannot reliably see a 10 point drop from a 93.7% baseline
assert run_cli(tmp_path, 118, 117, 126).returncode == 3
red = run_cli(tmp_path, 118, 99, 126)
assert red.returncode == 1, red.stdout
# p = 0.0303 is under alpha (0.05) but above alpha / 2, so it must still be RED
assert run_cli(tmp_path, 118, 108, 126).returncode == 1
amber = run_cli(tmp_path, 28, 28, 30)
assert amber.returncode == 3, amber.stdout
(tmp_path / "bad.jsonl").write_text("not json" + chr(10))
bad = subprocess.run(
[sys.executable, str(HERE / "agent_gate.py"), str(tmp_path / "bad.jsonl"), str(tmp_path / "bad.jsonl")],
capture_output=True,
text=True,
)
assert bad.returncode == 2
def test_cli_refuses_unequal_run_counts(tmp_path):
b = tmp_path / "base.jsonl"
c = tmp_path / "cand.jsonl"
write_runs(b, 100, 120)
write_runs(c, 100, 126)
done = subprocess.run([sys.executable, str(HERE / "agent_gate.py"), str(b), str(c)], capture_output=True, text=True)
assert done.returncode == 2 and "same number of runs" in done.stdout
def test_one_sample_gate_against_scipy():
from scipy.stats import binom
for n in (30, 100, 169, 250):
c = gate.one_sample_cutoff(n, 0.95)
assert binom.cdf(c, n, 0.95) <= 0.05 < binom.cdf(c + 1, n, 0.95)
false_alarm, power = gate.one_sample_rates(n, 0.95, 0.90)
assert false_alarm == pytest.approx(binom.cdf(c, n, 0.95))
assert power == pytest.approx(binom.cdf(c, n, 0.90))
def test_one_sample_power_dips_when_the_cutoff_stalls():
assert gate.one_sample_rates(171, 0.95, 0.90)[1] > 0.80 > gate.one_sample_rates(172, 0.95, 0.90)[1]
assert gate.one_sample_cutoff(171, 0.95) == gate.one_sample_cutoff(172, 0.95) == 157
def test_two_sample_runs_reproduce_the_published_table():
assert gate.plan_runs(0.95, 0.85) == (126, 126)
false_alarm, power = gate.gate_rates(371, 0.95, 0.90)
assert round(false_alarm, 4) == 0.0355 and round(power, 4) == 0.8000
def test_two_sample_plan_with_a_dip():
assert gate.plan_runs(0.60, 0.45) == (144, 152)
assert gate.gate_rates(145, 0.60, 0.45)[1] > 0.80 > gate.gate_rates(146, 0.60, 0.45)[1]
python -m pytest -q test_gate.py
......................... [100%]
25 passed in 1.75s
Passing tests only prove something if they can fail. mutants.py plants one bug at a time in a copy of the code (a tail that starts one pass too late, a doubled alpha, a gate that never reaches AMBER and so on) and checks that the suite goes red:
# mutants.py
"""mutants.py - plant one bug at a time and check that the test suite goes red."""
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
HERE = Path(__file__).parent
FILES = ["gate.py", "agent_gate.py", "test_gate.py"]
MUTANTS = [
("gate.py", "for x in range(base_pass, min(n_base, passes) + 1):", "for x in range(base_pass + 1, min(n_base, passes) + 1):", "p-value tail starts one pass too late"),
("gate.py", "tail = np.cumsum(pmf[:, ::-1], axis=1)[:, ::-1]", "tail = np.cumsum(pmf, axis=1)", "tail table runs the wrong way"),
("gate.py", "return tail[a + b, a] <= alpha", "return tail[a + b, a] <= 2 * alpha", "alpha doubled (two-sided habit)"),
("gate.py", "false_alarm = pa @ R @ binom_pmf(n, p_base)", "false_alarm = pa @ R @ binom_pmf(n, p_cand)", "false alarms measured on the regressed build"),
("gate.py", "z_a = NormalDist().inv_cdf(1 - alpha)", "z_a = NormalDist().inv_cdf(1 - alpha / 2)", "textbook size with a two-sided z"),
("gate.py", "return first, (last_fail + 1 if last_fail is not None else first)", "return first, first", "stable n ignores the dips"),
("gate.py", "return p * (1 - flip) + (1 - p) * flip", "return p * (1 - flip)", "judge noise only removes passes"),
("gate.py", "inside = np.nonzero(cdf <= alpha)[0]", "inside = np.nonzero(cdf < alpha / 2)[0]", "one-sample cutoff too strict"),
("agent_gate.py", "if p <= args.alpha:", "if p < args.alpha / 2:", "gate fails builds only at half of alpha"),
("agent_gate.py", "if power < 0.80:", "if power < 0.0:", "the AMBER state can never happen"),
("agent_gate.py", "if n_a != n_b:", "if False:", "unequal run counts accepted"),
("agent_gate.py", "passes += ok", "passes += not ok", "counts failures as passes"),
]
def pytest(folder):
return subprocess.run(
[sys.executable, "-m", "pytest", "-q", "-x", "-p", "no:cacheprovider", "test_gate.py"],
cwd=folder, capture_output=True, text=True,
)
def main():
caught = 0
with tempfile.TemporaryDirectory(dir=HERE) as tmp:
base = Path(tmp)
for name in FILES:
shutil.copy(HERE / name, base / name)
control = pytest(base)
print("control (no bug planted):", "green" if control.returncode == 0 else "RED")
for number, (name, old, new, label) in enumerate(MUTANTS, start=1):
work = Path(tmp) / f"m{number}"
work.mkdir()
for f in FILES:
shutil.copy(HERE / f, work / f)
text = (work / name).read_text(encoding="utf-8")
assert text.count(old) == 1, f"mutant {number}: expected one occurrence of {old!r}"
(work / name).write_text(text.replace(old, new), encoding="utf-8", newline="\n")
result = pytest(work)
failed = result.returncode != 0
caught += failed
line = [l for l in result.stdout.splitlines() if l.startswith("FAILED")][:1]
print(f"mutant {number:>2} {'caught' if failed else 'SURVIVED':<8} {label}" + (f" <- {line[0].split(' - ')[0][7:]}" if line else ""))
print(f"{caught} of {len(MUTANTS)} planted bugs caught")
if __name__ == "__main__":
main()
python mutants.py
control (no bug planted): green
mutant 1 caught p-value tail starts one pass too late <- test_gate.py::test_fisher_matches_scipy_on_random_tables
mutant 2 caught tail table runs the wrong way <- test_gate.py::test_reject_matrix_equals_direct_p_values[12]
mutant 3 caught alpha doubled (two-sided habit) <- test_gate.py::test_reject_matrix_equals_direct_p_values[12]
mutant 4 caught false alarms measured on the regressed build <- test_gate.py::test_rates_match_brute_force
mutant 5 caught textbook size with a two-sided z <- test_gate.py::test_normal_runs_textbook_values
mutant 6 caught stable n ignores the dips <- test_gate.py::test_two_sample_plan_with_a_dip
mutant 7 caught judge noise only removes passes <- test_gate.py::test_observed_rate_judge_noise
mutant 8 caught one-sample cutoff too strict <- test_gate.py::test_one_sample_gate_against_scipy
mutant 9 caught gate fails builds only at half of alpha <- test_gate.py::test_cli_green_red_amber_and_bad_input
mutant 10 caught the AMBER state can never happen <- test_gate.py::test_cli_green_red_amber_and_bad_input
mutant 11 caught unequal run counts accepted <- test_gate.py::test_cli_refuses_unequal_run_counts
mutant 12 caught counts failures as passes <- test_gate.py::test_cli_green_red_amber_and_bad_input
12 of 12 planted bugs caught
My first version of the suite caught 10 of the 12 planted bugs. Two survived: “stable n ignores the dips” and “gate fails builds only at half of alpha”. The first survived because none of my tests used a plan where the first size and the stable size differ; the 60% to 45% case from Step 5 fixed that. The second survived because all my command-line cases were far from the line; the 108-of-126 case, with p between alpha divided by two and alpha, fixed it. Now all 12 are caught.
Common mistakes
- Repeating one input. As Step 9 showed, 20 runs of one email gave one output. Vary the inputs; use your real traffic mix or a fixed suite you rotate.
- Reading green as safe. A pass-rate gate can only see drops its run count can detect. Look at the AMBER message and at the table in Step 7 before you trust a green.
- Comparing with an old baseline. A baseline measured last week may not match today’s model endpoint or tool data. Re-measure the baseline in the same window, as the two-sample gate does.
- Rerunning until it passes. If a gate catches a real regression 80% of the time, a rule that reruns a red build up to three times lets that regression through at least once with probability 1 minus 0.8 cubed, which is 48.8%. Fix the run count instead.
- Using the textbook formula. It was 6% to 12% too small in Step 4. Use the exact planner.
- Ignoring judge noise. If an AI judge grades the runs, measure its flip rate and plan with Step 6.
- Expecting the gate to catch rare, severe failures. A 1-in-1,000 failure needs 2,995 runs to see with 95% probability. Use runtime safeguards for those.
Check that everything works end to end
python -m pytest -q test_gate.pyprints25 passed.python step01_single_run.pyprints about 5% and 15% (sampling noise moves them by a few tenths).python step03_rates.pyprints exact false alarms of 0.0243 and 0.0355 and exact power of 0.8014 and 0.8000.python step04_sizing.pyprints 889, 371 and 126 for the first three rows.python agent_gate.py out/try_base.jsonl out/try_cand.jsonlwith 118 and 99 passes ends in RED and exit code 1.- If you ran the model steps:
python real_gate.pyshows pass counts near 98% for the good build and near 90% for the routed one, and a RED verdict on 400 runs per build. Your counts will differ a little, because models and hardware differ.
What I did not check
I did not verify DigitalOcean’s other claims: its exact-match golden-string demonstration, its token-price figures, or its simulation product. The two-sample run counts, the one-sample dip, the 670-run judge example and the 11.8% rare-failure figure are the ones I reproduced. The real-agent experiment uses one task, two small models and 400 runs per build, and its bootstrap table resamples those saved runs, so it describes this agent and not agents in general. The CI wrapper ran in a local shell only.
Where to go next
- Pair your inputs. If both builds see the same emails, a test that compares them email by email can reach the same power with fewer runs. Try a stratified or McNemar-style test on top of
gate.py. - Stop early. A sequential test can stop a nightly job as soon as the evidence is clear, which cuts the average number of runs.
- Replace the judge. If you still grade with an AI model, calibrate it first with my Cohen’s kappa tutorial.
- Build the harness around the agent. My agent harness tutorial adds tool validation, a file sandbox and run limits, so the runs you count are safe to run.
- Add property tests for the deterministic parts. My Hypothesis tutorial covers the code around the model.
Sources
- DigitalOcean Community, How to Test AI Agents Before Production, Vinayak Baranwal, November 23, 2026. Topic source and the run-count figures I reproduced.
- SciPy documentation,
scipy.stats.fisher_exact, used as an independent check of the p-values. - Ollama, API documentation, for the
options(temperature, seed, num_predict) andformatsettings.








No Comment! Be the first one.