Online Experiments and Production Evaluation › Worked example: from a synthetic production log to a decision
Language AI HandbookAll chapters Start with a fictional support assistant and a candidate that also reranks suggested passages. The notebook uses one seeded generator for the trial runs. The offline, shadow, interleaving, A/B and canary logs illustrate distinct kinds of evidence. Each is constructed locally for this example.
Setup
We'll use only common scientific Python. All randomness is seeded so the chapter is deterministic.
PythonIn [2]Expand
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from book_plot_style import (
PALETTE,
polish_axes,
seed_book_plots,
use_book_style,
)
from scipy import stats
seed_book_plots()
RNG = np.random.default_rng(20240501)The simulated user population has 20,000 rows. Patience and new-user status enter the resolution model.
PythonIn [3]Expand
N_USERS = 20_000
user_ids = np.arange(N_USERS)
clickiness = RNG.beta(2.0, 5.0, size=N_USERS) # propensity to engage
patience = RNG.beta(5.0, 2.0, size=N_USERS) # propensity to tolerate
is_new_user = RNG.random(N_USERS) < 0.35
users = pd.DataFrame(
{
"user_id": user_ids,
"clickiness": clickiness,
"patience": patience,
"new_user": is_new_user,
}
)
users.head()For the A/B fixture, each sampled user appears once. The separate interleaving fixture generates independent sessions.
The offline eval
First we produce the offline artifact: judge scores for the two candidates on a fixed eval set. We create a set of 400 eval questions representing the "annotator" distribution and score each model. We'll deliberately bias the eval distribution toward easy questions, one of the classic offline-vs-online mismatches.
PythonIn [4]Expand
N_EVAL = 400
eval_difficulty = RNG.beta(
2.0, 5.0, size=N_EVAL
) # mostly easy, like annotators like
# The expected candidate-minus-baseline score decreases with difficulty.
base_offline = 62 + 20 * (1 - eval_difficulty) + RNG.normal(0, 4, N_EVAL)
cand_offline = (
66
+ 22 * (1 - eval_difficulty)
- 8 * eval_difficulty
+ RNG.normal(0, 4, N_EVAL)
)
offline = pd.DataFrame(
{
"eval_id": np.arange(N_EVAL),
"difficulty": eval_difficulty,
"base_judge": base_offline,
"cand_judge": cand_offline,
}
)
offline["delta"] = offline["cand_judge"] - offline["base_judge"]Now compute the offline read: the mean judge delta and its confidence interval. We'll report this as the number a team would put on a slide: "candidate wins offline."
PythonIn [5]Expand
from scipy.stats import t as t_dist
n = len(offline)
d_bar = offline["delta"].mean()
d_s = offline["delta"].std(ddof=1)
se = d_s / np.sqrt(n)
crit = t_dist.ppf(0.975, df=n - 1)
ci = (d_bar - crit * se, d_bar + crit * se)
offline_summary = pd.DataFrame(
{
"quantity": ["mean judge delta", "SE", "95% lower", "95% upper", "n"],
"value": [d_bar, se, ci[0], ci[1], n],
}
)ConsoleOut [6]Expand
quantity value
mean judge delta 3.207
SE 0.306
95% lower 2.606
95% upper 3.807
n 400.000The paired judge difference is +3.207 points. The 95% paired t interval is [2.606, 3.807] over 400 questions. This calculation treats questions as independent sampling units for the fixture.
The score generator makes the expected candidate-minus-baseline difference decline with difficulty. Compare the tails before interpreting the overall mean.
PythonIn [7]Expand
hard = offline[offline["difficulty"] >= offline["difficulty"].quantile(0.75)]
easy = offline[offline["difficulty"] <= offline["difficulty"].quantile(0.25)]
by_stratum = pd.DataFrame(
{
"stratum": ["easy", "hard"],
"mean_delta": [easy["delta"].mean(), hard["delta"].mean()],
"n": [len(easy), len(hard)],
}
)ConsoleOut [8]Expand
stratum mean_delta n easy 5.269 100 hard 0.406 100
The easy quartile averages +5.269 points and the hard quartile +0.406, with 100 questions in each.
The scatter shows the spread around all three mean lines.
PythonIn [9]Expand
plot_offline = offline.copy()
plot_offline["hard_cut"] = plot_offline["difficulty"].quantile(0.75)
plot_offline["easy_cut"] = plot_offline["difficulty"].quantile(0.25)
easy_mean_delta = plot_offline.loc[
plot_offline["difficulty"] <= plot_offline["easy_cut"], "delta"
].mean()
hard_mean_delta = plot_offline.loc[
plot_offline["difficulty"] >= plot_offline["hard_cut"], "delta"
].mean()
overall_mean_delta = plot_offline["delta"].mean()VisualizationOut [10]Expand

The offline quartiles describe the offline difficulty distribution. The shadow fixture supplies a different input sample.
Shadow traffic: measure the candidate on production inputs
Now we simulate a shadow deployment. We sample 8,000 production requests, with an input difficulty distribution that is harder than the eval set (production includes many nasty edge cases), plus nonstationary "drift" toward harder requests over time (so we can reuse this log later for drift monitoring).
PythonIn [11]Expand
N_PROD = 8_000
request_id = np.arange(N_PROD)
# Production traffic is harder on average than the eval set, and drifts harder over the window.
time_frac = request_id / N_PROD
prod_difficulty = RNG.beta(4.0, 3.0, size=N_PROD) + 0.25 * time_frac
prod_difficulty = np.clip(prod_difficulty, 0.0, 1.0)
# Generate synthetic judgment scores. The shadow baseline is a second judge draw.
shadow_base = 60 + 22 * (1 - prod_difficulty) + RNG.normal(0, 5, N_PROD)
shadow_cand = (
66
+ 20 * (1 - prod_difficulty)
- 4 * prod_difficulty
+ RNG.normal(0, 5, N_PROD)
)
# Production's actual responses are judged too (so we can compare on the same inputs).
prod_quality = 60 + 22 * (1 - prod_difficulty) + RNG.normal(0, 5, N_PROD)
shadow = pd.DataFrame(
{
"request_id": request_id,
"time_frac": time_frac,
"difficulty": prod_difficulty,
"shadow_base_judge": shadow_base,
"shadow_cand_judge": shadow_cand,
"prod_judge": prod_quality,
}
)
shadow["paired_delta"] = shadow["shadow_cand_judge"] - shadow["prod_judge"]The candidate and served-baseline scores describe the same items. Form an approximate normal interval from the differences. The helper accepts aligned finite real scores and fails if it cannot construct a finite interval. For comparison compute an equal-size hypothetical independent standard error using the same marginal variances and omitting covariance. This benchmark does not analyze a second experiment.
PythonIn [12]Expand
from warnings import catch_warnings, simplefilter
from scipy.special import erfinv
def as_real_floats(values):
with catch_warnings():
simplefilter("error", np.exceptions.ComplexWarning)
try:
return np.asarray(values, dtype=float)
except (
OverflowError,
TypeError,
ValueError,
np.exceptions.ComplexWarning,
) as exc:
raise ValueError(
"Inputs must be represented as real floats."
) from exc
def paired_wald_ci(x, y, conf=0.95):
x, y = as_real_floats(x), as_real_floats(y)
confidence = as_real_floats(conf)
if confidence.ndim != 0:
raise ValueError("Supply a scalar confidence level.")
conf = float(confidence)
if x.ndim != 1 or x.shape != y.shape or x.size < 2:
raise ValueError("Supply at least two aligned score pairs.")
if not np.isfinite(x).all() or not np.isfinite(y).all():
raise ValueError("Paired scores must be finite.")
if not 0 < conf < 1:
raise ValueError("Confidence must be between zero and one.")
n = len(x)
z = np.sqrt(2) * erfinv(conf)
with np.errstate(over="ignore", invalid="ignore"):
d = x - y
if not np.isfinite(d).all():
raise ValueError(
"Paired score differences exceed the numeric range."
)
m = d.mean()
s = d.std(ddof=1) / np.sqrt(n)
lo, hi = m - z * s, m + z * s
if not np.isfinite([m, s, lo, hi]).all():
raise ValueError("Paired interval statistics exceed the numeric range.")
return {"mean": m, "n": n, "se": s, "lo": lo, "hi": hi}
shadow_paired = paired_wald_ci(
shadow["shadow_cand_judge"], shadow["prod_judge"]
)
x = shadow["shadow_cand_judge"]
y = shadow["prod_judge"]
n_shadow = len(x)
se_independent = np.sqrt(x.var(ddof=1) / n_shadow + y.var(ddof=1) / n_shadow)
z_shadow = stats.norm.ppf(0.975)
delta_shadow = x.mean() - y.mean()
shadow_unpaired = {
"mean": delta_shadow,
"n": n_shadow,
"se": se_independent,
"lo": delta_shadow - z_shadow * se_independent,
"hi": delta_shadow + z_shadow * se_independent,
}ConsoleOut [13]Expand
Shadow paired: mean=+2.512, n=8000, SE=0.079, 95% CI=[+2.358, +2.667] Independent reference: mean=+2.512, n=8000, SE=0.102, 95% CI=[+2.312, +2.713]
On 8,000 matched requests, the shadow delta is +2.512. Positive score covariance gives a paired SE of 0.079, compared with 0.102 for the independent-arm reference at the same sample sizes. That reference uses the two observed marginal variances to show what omitting covariance would imply. Both return the same point estimate because they use the same observed scores.
The shadow scores support a proxy comparison. The next fixture uses blended ranking slots. The A/B experiment later measures resolution by assignment.
Interleaving: which ranker do users prefer?
We simulate only the Team Draft credit pattern. Each pair of slots has one contribution per team in randomized order. Click probability decreases with position. Team A represents the candidate and has a small multiplicative advantage in the click generator.
PythonIn [14]Expand
N_SESSIONS = 3000
LIST_LEN = 6
TRUE_ADV = 0.06 # candidate per-item click advantage under the alternative
def simulate_session(rng, true_adv):
# Randomize who goes first in each round of two available slots.
credits = {"A": 0, "B": 0}
for slot in range(LIST_LEN):
if slot % 2 == 0:
first_team = "A" if rng.random() < 0.5 else "B"
team = first_team
else:
team = "B" if first_team == "A" else "A"
# clicking propensity decreases with slot position, and A/B differ by true_adv
slot_discount = 0.9**slot
team_bonus = {"A": 1.0 + true_adv / 2, "B": 1.0 - true_adv / 2}[team]
p_click = 0.30 * slot_discount * team_bonus
if rng.random() < p_click:
credits[team] += 1
return credits
team_credits = [simulate_session(RNG, TRUE_ADV) for _ in range(N_SESSIONS)]
interleave_log = pd.DataFrame(team_credits).rename(
columns={"A": "a_clicks", "B": "b_clicks"}
)
interleave_log["session"] = np.arange(N_SESSIONS)
interleave_log["total"] = (
interleave_log["a_clicks"] + interleave_log["b_clicks"]
)Compare the two nonnegative integer credit counts for each session. The two-sided sign test uses independent sessions and a symmetric no-preference null among decisive sessions. It omits ties and does not count individual clicks as independent evidence.
PythonIn [15]Expand
from operator import index
def normalize_credit_count(value):
if isinstance(value, (bool, np.bool_)):
raise ValueError("Credit counts must be nonnegative integers.")
try:
count = index(value)
except TypeError as exc:
raise ValueError("Credit counts must be nonnegative integers.") from exc
if count < 0:
raise ValueError("Credit counts must be nonnegative integers.")
return count
def team_draft_test(a_clicks, b_clicks):
a_clicks = np.asarray(a_clicks, dtype=object)
b_clicks = np.asarray(b_clicks, dtype=object)
if a_clicks.shape != b_clicks.shape or a_clicks.ndim != 1:
raise ValueError("Supply one pair of credit counts per session.")
a_counts = [normalize_credit_count(value) for value in a_clicks]
b_counts = [normalize_credit_count(value) for value in b_clicks]
pairs = list(zip(a_counts, b_counts, strict=True))
a_wins = sum(a > b for a, b in pairs)
b_wins = sum(b > a for a, b in pairs)
decisive = a_wins + b_wins
p_value = (
stats.binomtest(a_wins, decisive, p=0.5).pvalue if decisive else None
)
return {
"a_wins": a_wins,
"b_wins": b_wins,
"n_decisive": decisive,
"p_value": p_value,
}
interleaving = team_draft_test(
interleave_log["a_clicks"], interleave_log["b_clicks"]
)ConsoleOut [16]Expand
Independent session signs: {'a_wins': 936, 'b_wins': 899, 'n_decisive': 1835, 'p_value': np.float64(0.40069215977663536)}The printed result summarizes one synthetic item-credit fixture. A session can offer several clicks, but its sign contributes at most one comparison. The fixture assigns credit teams directly and does not construct or deduplicate actual ranked lists. A real Team Draft implementation needs those additional steps. The sign result describes relative preference under the blended presentation.
A/B test: assign at the user level, compute ITT
The A/B fixture assigns 12,000 distinct users and records receipt separately. Its primary outcome is in-session resolution. The same latent draw for each user defines both possible receipt states, with a higher threshold under candidate assignment.
PythonIn [17]Expand
AB_USERS = 12_000
ab = users.sample(AB_USERS, random_state=1).copy()
# Assignment: 50/50 at the user level.
ab["arm"] = np.where(RNG.random(AB_USERS) < 0.5, "cand", "base")
# One draw per user defines both potential receipt states. This rules out defiers.
uptake = RNG.random(AB_USERS)
receipt_threshold = np.where(ab["arm"] == "cand", 0.92, 0.03)
ab["received"] = np.where(uptake < receipt_threshold, "cand", "base")
# Baseline outcome probability depends on patience & new-user status (nuisance vars).
def outcome_prob(patience, new_user, received):
base = 0.42 + 0.18 * patience - 0.06 * new_user
if received == "cand":
base += 0.045 # small true effect of the candidate
return np.clip(base, 0.0, 1.0)
ab["p_resolve"] = [
outcome_prob(pa, nu, rc)
for pa, nu, rc in zip(ab["patience"], ab["new_user"], ab["received"])
]
ab["resolved"] = (RNG.random(AB_USERS) < ab["p_resolve"]).astype(int)
# Additional synthetic measurements; the primary outcome is binary resolution.
ab["turns"] = np.where(
ab["received"] == "cand",
RNG.normal(3.6, 1.4, AB_USERS),
RNG.normal(3.9, 1.5, AB_USERS),
)
# Assign a simulated day index so we can check for novelty/primacy.
ab["day"] = RNG.choice(np.arange(1, 8), size=AB_USERS)Now compute the primary metric by ITT: compare resolved between assigned arms, ignoring received. Here we report a difference in binary proportions with a Wald interval. The next cell also checks the randomized allocation with an exact binomial test.
PythonIn [18]Expand
base_r = ab.loc[ab["arm"] == "base", "resolved"]
cand_r = ab.loc[ab["arm"] == "cand", "resolved"]
def prop_ci(x, conf=0.95):
p = x.mean()
n = len(x)
s = np.sqrt(p * (1 - p) / n)
z = stats.norm.ppf(1 - (1 - conf) / 2)
return {"p": p, "n": n, "lo": p - z * s, "hi": p + z * s}
base_ci = prop_ci(base_r)
cand_ci = prop_ci(cand_r)
diff = cand_ci["p"] - base_ci["p"]
se_diff = np.sqrt(
cand_ci["p"] * (1 - cand_ci["p"]) / cand_ci["n"]
+ base_ci["p"] * (1 - base_ci["p"]) / base_ci["n"]
)
z = stats.norm.ppf(0.975)
ab_result = pd.DataFrame(
{
"arm": ["base", "cand"],
"n": [base_ci["n"], cand_ci["n"]],
"p_resolved": [base_ci["p"], cand_ci["p"]],
"ci_lo": [base_ci["lo"], cand_ci["lo"]],
"ci_hi": [base_ci["hi"], cand_ci["hi"]],
}
)
ab_effect = {
"diff": diff,
"se": se_diff,
"lo": diff - z * se_diff,
"hi": diff + z * se_diff,
}ConsoleOut [19]Expand
arm n p_resolved ci_lo ci_hi base 5943 0.5302 0.5175 0.5429 cand 6057 0.5646 0.5521 0.5771 ITT effect on resolution: +0.0344 [+0.0166, +0.0522]
The observed ITT estimate is about 3.4 percentage points on these seeded users. The simulation specifies a 4.5-point change in receipt-level outcome probability before clipping and an expected 0.89 first stage. Their product is 4.005 percentage points when the clip is inactive. An observed randomized contrast may differ from that expectation. The 95% fixed-look interval clears zero here. Advancing the rollout depends on the canary gates as well.
The complier effect estimate divides the observed ITT contrast by the observed difference in candidate take-up across assignment arms. It is a point estimate in this notebook.
PythonIn [20]Expand
compliance_diff = (
ab.loc[ab["arm"] == "cand", "received"].eq("cand").mean()
- ab.loc[ab["arm"] == "base", "received"].eq("cand").mean()
)
if compliance_diff <= 0:
raise ValueError("This example expects a positive first stage.")
tot = diff / compliance_diff
srm = stats.binomtest(int(ab["arm"].eq("cand").sum()), len(ab), p=0.5)
assert ab["user_id"].is_uniqueConsoleOut [21]Expand
compliance difference: 0.8858 Complier effect point estimate: +0.0389 Assignment balance p-value (all assigned users): 0.3023
The Wald ratio divides by the difference in exposure rates, about 0.89 by design. It estimates the average effect among compliers under randomized assignment, exclusion, no defiers, nonzero first stage and a well-defined treatment with no interference. The assignment-balance check tests the configured 50/50 split using all assigned unique users before any receipt or outcome filter.
Compute candidate-minus-baseline resolution by day as a descriptive diagnostic.
PythonIn [22]Expand
daily = ab.groupby(["day", "arm"])["resolved"].mean().unstack()
daily["effect"] = daily["cand"] - daily["base"]
daily = daily.reset_index().rename(columns={"day": "day_index"})ConsoleOut [23]Expand
day_index base cand effect
1 0.5223 0.5567 0.0344
2 0.5505 0.5751 0.0247
3 0.5347 0.5429 0.0082
4 0.4988 0.5556 0.0568
5 0.5465 0.5631 0.0166
6 0.5088 0.5927 0.0839
7 0.5467 0.5660 0.0193Day is a diagnostic in this fixture. The data generation contains no changing treatment effect, so a slope can arise from sampling variation. In a real test compare exposure age, cohort and calendar time before attaching a novelty explanation.
VisualizationOut [24]Expand

Guardrails: monitor the canary for a regression
The canary has 1,500 candidate requests and displays fixed-checkpoint candidate results. Hold if either 99% one-sided Wilson upper bound exceeds its rate cap or if the observed p95 latency or median normalized cost exceeds its own cap.
PythonIn [25]Expand
N_CANARY, N_BASE = 1500, 4000
# Safety harms (policy violations, disallowed content) per request.
harm_cand = RNG.binomial(1, 0.0031, N_CANARY)
harm_base = RNG.binomial(1, 0.0029, N_BASE)
# Errors (5xx/timeouts) per request.
err_cand = RNG.binomial(1, 0.008, N_CANARY)
err_base = RNG.binomial(1, 0.009, N_BASE)
# Individual latencies in milliseconds; the gate uses the sample 95th percentile.
lat_cand = RNG.lognormal(mean=np.log(820), sigma=0.45, size=N_CANARY)
lat_base = RNG.lognormal(mean=np.log(790), sigma=0.45, size=N_BASE)
# Each draw is a request-level cost scaled to a per-1,000-request equivalent.
cost_cand = RNG.normal(1.62, 0.12, N_CANARY)
cost_base = RNG.normal(1.55, 0.12, N_BASE)
def rate_bound(events, n, conf=0.99):
integer_count = (int, np.integer)
if (
any(isinstance(v, (bool, np.bool_)) for v in (events, n))
or not isinstance(events, integer_count)
or not isinstance(n, integer_count)
or n <= 0
or not 0 <= events <= n
or not 0.5 < conf < 1
):
raise ValueError(
"Supply valid binomial counts and a one-sided confidence level."
)
events, n = int(events), int(n)
p = events / n
inv_n = 1 / n
zval = stats.norm.ppf(conf)
z2_over_n = zval**2 * inv_n
denom = 1 + z2_over_n
center = (p + z2_over_n / 2) / denom
half = zval * np.sqrt((p * (1 - p) + z2_over_n / 4) * inv_n) / denom
# Keep the positive endpoint representable even when the result underflows.
upper = np.clip(center + half, np.nextafter(0.0, 1.0), 1.0)
return p, upper
harm_rate, harm_ub = rate_bound(harm_cand.sum(), len(harm_cand))
err_rate, err_ub = rate_bound(err_cand.sum(), len(err_cand))
lat_p95 = np.percentile(lat_cand, 95)
cost_p50 = np.median(cost_cand)ConsoleOut [26]Expand
guardrail cand_value upper_99 threshold exceeds_gate
harm_rate 0.0020 0.0070 0.0060 True
error_rate 0.0067 0.0136 0.0120 True
p95_latency_ms 1797.3445 NaN 1500.0000 True
median_scaled_cost 1.6269 NaN 2.0000 FalseThe rates are per canary request. The cost gate uses the median of per-request costs scaled to a 1,000-request equivalent. The table applies the rule to the computed upper bounds and to the observed latency and cost. An upper bound above its cap fails to establish clearance, even when the point estimate falls below the cap. Holding under that rule does not establish that the underlying rate exceeds the cap. The 99% Wilson upper bounds describe one fixed look with binomial counts. A missing required measurement or unusable cap also holds the ramp. Repeated looks need their own calibrated procedure.
Drift monitoring: has the input distribution moved?
Split the shadow input stream into an early reference window below 0.33 of elapsed time and a late window at or above 0.67. Measure the input difficulty shift and show the mean production judge score in each window. The diagnostic requests at least two quantile bins before merging repeated edges. It adds a fixed positive smoothing constant of to each share in the logarithmic ratio, so a bin with no observations in one window still contributes a finite term.
PythonIn [27]Expand
def psi(reference, current, bins=10):
# Bin on reference quantiles; compare proportions
eps = 1e-6
if isinstance(bins, (bool, np.bool_)):
raise ValueError(
"Request at least two quantile bins using an integer count."
)
try:
bins = index(bins)
except TypeError as exc:
raise ValueError(
"Request at least two quantile bins using an integer count."
) from exc
if bins < 2:
raise ValueError(
"Request at least two quantile bins using an integer count."
)
reference = as_real_floats(reference)
current = as_real_floats(current)
if not reference.size or not current.size:
raise ValueError("Drift windows must be nonempty.")
if not np.isfinite(reference).all() or not np.isfinite(current).all():
raise ValueError("Drift windows must contain finite observations.")
with np.errstate(over="ignore", invalid="ignore"):
quantiles = np.quantile(reference, np.linspace(0, 1, bins + 1)[1:-1])
if not np.isfinite(quantiles).all():
raise ValueError("Reference quantiles exceed the numeric range.")
interior = np.unique(quantiles)
edges = np.r_[-np.inf, interior, np.inf]
ref_counts, _ = np.histogram(reference, bins=edges)
cur_counts, _ = np.histogram(current, bins=edges)
ref_pct = ref_counts / ref_counts.sum()
cur_pct = cur_counts / cur_counts.sum()
return np.sum(
(cur_pct - ref_pct) * np.log((cur_pct + eps) / (ref_pct + eps))
)
ref_window = shadow.loc[shadow["time_frac"] < 0.33, "difficulty"]
cur_window = shadow.loc[shadow["time_frac"] >= 0.67, "difficulty"]
psi_val = psi(ref_window.values, cur_window.values)
ks = stats.ks_2samp(ref_window, cur_window)
ref_mean_judge = shadow.loc[shadow["time_frac"] < 0.33, "prod_judge"].mean()
cur_mean_judge = shadow.loc[shadow["time_frac"] >= 0.67, "prod_judge"].mean()ConsoleOut [28]Expand
PSI-style difficulty score: 0.6993 Empirical KS gap: 0.318 prod judge early=68.44, late=65.21
The binned difficulty score is 0.6993, and the empirical KS gap is 0.318. Production judge means are 68.44 early and 65.21 late. The fixture holds the scoring model fixed and shifts input difficulty. Clipping at 1 contributes to the final-bin spike. In live monitoring those two trends alone would leave the cause open.
Use common histogram bin edges to compare the early and late windows.
VisualizationOut [29]Expand

Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!