Online Experiments and Production Evaluation

Michael BrenndoerferDecember 1, 202634 min read

Compare shadow scores, blended preferences, and randomized outcomes. Apply canary guardrails and monitor input drift before expanding a model rollout.

Language AI HandbookAll chapters
Part 57 of 67Dynamic, Interactive, and Agentic Evaluation
Chapter 439Online Experiments and Production Evaluation
Reading the full chapter · 15 sections · 34 min15 sections · 34 min

All 15 sections · 34 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Online Experiments and Production Evaluation

A support model scores three points higher than the baseline on the offline judge. Before increasing its traffic, I would want to know whether more people resolve their issue, whether the candidate can serve within the latency budget, and what happens to requests the judge rarely sees. Those are three different measurements.

A shadow run compares both model outputs on the same production requests. Interleaving can compare two rankings through clicks on a blended list. A randomized experiment estimates what changes when users are assigned to the new system. Guardrails and drift monitors answer questions that remain after a favorable primary outcome.

The worked example follows one fictional support assistant through those measurements. All data are synthetic and the notebook makes no service calls.

Why offline scores do not transfer

An offline result has a population and a scoring rule. A held-out set of support questions might favor short, well-formed requests, while production includes multilingual conversations and account-state-dependent follow-ups. A judge may reward complete answers even when a user needs one instruction. Either difference can change which model appears stronger.

Offline evaluation can include replayed conversations and downstream labels. The coverage and causal question still matter. If only the baseline response was served, the ensuing escalation is an observed outcome under that serving policy. Replaying the candidate on the same initial request gives you its output. Learning how assignment to that candidate changes escalation requires additional causal evidence and assumptions.

Choose a primary metric with an observation window and a denominator. For example, define seven-day resolution as a binary outcome for each eligible assigned user, after the window has matured. A measure such as thumbs-up rate answers a different question and can change if the system alters who chooses to rate a response.

The causal chain from model change to outcome

A model or prompt change can alter the distribution of responses, what users see, how they act and whether they resolve the task. A rollout can also change latency or availability directly. Use this conceptual chain to map the evidence each method actually captures.

MethodWhat is observedQuestion
Shadow trafficPaired outputs on eligible requests that reach both systemsHow do proxy scores and response characteristics compare?
InterleavingClicks on a blended ranked listWhich ranker receives more credit under this presentation and credit rule?
Randomized A/BOutcomes for eligible units grouped by assignmentHow does assigning the candidate affect the chosen outcome?
Canary monitoringCandidate safety and operational measurementsHas the candidate met the predefined rule for advancing?

An output comparison can justify spending traffic on a randomized test. An improvement on the primary A/B metric and clearance on operational guardrails are separate pieces of the release decision.

Shadow traffic

In a shadow run the baseline still responds to the user. The candidate receives an eligible copy of the input and writes its output to a separate log. The shared request ID lets you join scores for the two responses and compute each response pair's score difference.

For candidate and baseline scores CC and BB on the same request,

Var⁡(C−B)=Var⁡(C)+Var⁡(B)−2Cov⁡(C,B).\operatorname{Var}(C-B)=\operatorname{Var}(C)+\operatorname{Var}(B)-2\operatorname{Cov}(C,B).

For independent pairs, the standard error of their mean difference is the sample standard deviation of C−BC-B divided by the square root of the pair count. Positive within-request covariance lowers that variance relative to an independent comparison with the same number of scores per model. Correlation across requests from the same user can require a user-level analysis.

Log how many eligible requests enter the shadow path, how many return before the deadline, and how many join. If candidate timeouts concentrate on hard requests, the complete-pair score describes a selected subset. Set candidate-specific concurrency and compute limits, block side effects and writes, and protect any copied input under the same permissions as the serving path.

You can annotate a candidate response with the actual baseline interaction's later outcome. A baseline escalation can help you pick cases for review. The join records the outcome that actually occurred under the baseline. Candidate exposure can change a user's next message, so the replay follows the baseline trajectory.

Interleaving

Interleaving combines two rankings into one displayed list. It can be useful for search results or a list of recommended passages. The clicks are observed under the combined presentation, and a credit rule maps them back to the two rankers.

In Team Draft, the team with fewer contributions goes next. Break ties by choosing a team at random. That team contributes its highest-ranked item absent from the merged list. The published loop continues only while both teams still have an unused item. A click is credited to the team that contributed that item. Radlinski, Kurup and Joachims, 2008.

Sharing a display exposes both rankers to the same user and request. Credit can still depend on item positions, duplicate items, attribution and how users click. Treat a result as relative preference under the chosen presentation. The example assigns six slots directly to teams, so it exercises the credit statistic without implementing rank merging or deduplication.

For the toy, aggregate credits within a session and retain the sign of the difference. Under independent sessions and a winner probability of one-half conditional on a decisive session, the number of candidate wins among ndecisiven_\text{decisive} decisive sessions has a Binomial⁡(ndecisive,1/2)\operatorname{Binomial}(n_\text{decisive},1/2) distribution. Equal average click counts alone do not imply symmetric winning signs. Repeated sessions from one user can require user-level aggregation or analysis that accounts for the dependence.

A/B tests

Random assignment balances pre-assignment characteristics in expectation. Once you assign a unit, keep its assignment in the analysis even if it receives the other model. Record the unit key, assignment, actual receipt, outcome window and follow-up status as distinct fields.

Assignment unit

Choose a unit that matches the effect you want to estimate and the way exposure can spill over. Randomizing requests can make sense for a stateless response policy. Persistent memory or an interface that users learn can call for stable user assignment. Shared treatment within a tenant can call for tenant assignment.

For equal cluster size mm, common outcome variance, common pairwise intracluster correlation ρ\rho and independence across clusters, the variance inflation of the mean relative to treating all outcomes as independent is

DEFF=1+(m−1)ρ.\mathrm{DEFF} = 1 + (m-1)\rho.

Each cluster has mm variances and m(m−1)m(m-1) ordered covariance terms. Positive ρ\rho inflates the standard error by DEFF\sqrt{\mathrm{DEFF}} under these conditions. Unequal sizes, a small number of randomized clusters or cross-cluster interactions call for an analysis that matches the design.

Intention-to-treat and the effect among compliers

Let ZZ indicate assignment, with 1 for candidate and 0 for baseline. Let DD indicate actual candidate receipt and YY be the outcome in the specified window. The intention-to-treat effect measures assignment:

ITT=E[Y∣Z=1]−E[Y∣Z=0].\mathrm{ITT} = \mathbb{E}[Y \mid Z=1]-\mathbb{E}[Y \mid Z=0].

The first stage is the assignment effect on candidate receipt, E[D∣Z=1]−E[D∣Z=0]\mathbb{E}[D\mid Z=1]-\mathbb{E}[D\mid Z=0]. Random assignment, a nonzero first stage, an exclusion restriction, monotonic receipt, and well-defined treatment with no interference identify the complier average causal effect:

CACE=E[Y∣Z=1]−E[Y∣Z=0]E[D∣Z=1]−E[D∣Z=0].\mathrm{CACE} = \frac{\mathbb{E}[Y\mid Z=1]-\mathbb{E}[Y\mid Z=0]} {\mathbb{E}[D\mid Z=1]-\mathbb{E}[D\mid Z=0]}.

Exclusion means assignment affects the outcome only through receipt. Monotonicity means there are no users who would receive the candidate only under baseline assignment. Under these conditions the first stage is the fraction of compliers, and the ratio pertains to users whose receipt changes with assignment. Two-sided crossover can include users who receive the candidate in either arm. ITT stays useful when the routing policy itself is the intervention. Angrist, Imbens and Rubin, 1996.

Statistical power and the metric you are testing on

For equally sized independent arms, common per-unit variance σ2\sigma^2 and a fixed-horizon two-sided normal approximation, the approximate number of units per arm for detecting absolute effect Δ=τμ≠0\Delta=\tau\mu\ne0 is

n≈2σ2(z1−α/2+z1−β)2(τμ)2.n \approx \frac{2\sigma^2(z_{1-\alpha/2}+z_{1-\beta})^2}{(\tau\mu)^2}.

Here μ\mu is the baseline mean, τ\tau is the target relative lift, α\alpha is the test size and 1−β1-\beta is the target power. Halving ∣Δ∣|\Delta| quadruples the approximation with variance held fixed. With a Bernoulli baseline, substituting p(1−p)p(1-p) as the common variance gives nn proportional to (1−p)/(τ2p)(1-p)/(\tau^2p). For feasible fixed positive relative lift, required sample size in this approximation increases as pp falls. For rare outcomes or appreciably different arm variances, use a power calculation matched to the intended test.

Choose the primary outcome before inspecting results. Define the size of benefit worth acting on, and check whether assigned units have had time to reach the end of their outcome windows. Use secondary and segment estimates for diagnosis, with planned inference when claiming a difference. Sample ratio mismatch is a discrepancy between observed and expected allocation. An assignment count check is an early diagnostic. Compare later count changes against eligibility, logging and outcome maturity before interpreting a difference. Fabijan et al., 2019.

Novelty, primacy, and repeated exposure

An immediate reaction can differ from the effect after users have adapted. Plot estimates by exposure age and report the contributing cohort and its uncertainty. A calendar-day contrast can move because the cohort mix changed or because of sampling variation. When the long-run comparison matters, a maintained randomized holdout can preserve a baseline, with an explicit operating cost and review horizon.

Interference and carryover

One unit's outcome can depend on other units' exposure. A more expensive candidate can slow the baseline through a shared queue. A cache keyed without the variant can return an output from the wrong arm. A user assigned by request can carry state from an earlier exposure. These mechanisms can move an estimated contrast in different directions.

Separate caches or capacity where the serving question permits, or use assignment groups that capture the relevant interaction. A switchback, in which the assignment changes by time block, needs a carryover model and a matching analysis. Bojinov, Simchi-Levi and Zhao.

Peeking and sequential error inflation

If KK independent tests each reject with probability α\alpha under the null, the probability of any rejection is exactly 1−(1−α)K1-(1-\alpha)^K. At α=0.05\alpha=0.05 and K=10K=10, it is about 0.40130.4013. The union bound min⁡(1,Kα)\min(1,K\alpha) remains valid with dependence if each look's marginal rejection probability is at most α\alpha. Daily cumulative data are usually dependent because they reuse observations.

For efficacy, prespecify a single final look or use a design with calibrated interim boundaries. A test calibrated for arbitrary stopping or a time-uniform confidence sequence requires its own assumptions. A separate policy can pause traffic for safety without presenting a paused fixed-horizon efficacy analysis as an ordinary final test. Johari et al., 2022. Howard et al., 2021.

Guardrail metrics and monitored rollouts

Write down the thresholds, denominator, checkpoint schedule and possible actions before opening traffic. In the toy, the candidate must clear absolute caps for safety-harm rate, error rate, the observed 95th-percentile latency and a normalized cost statistic. Other rollouts compare candidate and baseline changes against a specified tolerance.

For a binary harm rate at one fixed checkpoint, an approximate one-sided Wilson upper bound uses the standard normal quantile at the chosen coverage level. It can be positive even with zero observed harms. If the upper bound exceeds the cap, the policy can hold the next ramp for insufficient evidence of clearance. Evidence that the true rate exceeds the cap is a separate claim. Wilson, 1927.

Staging limits exposure at each ramp. A prespecified severe event can also trigger a pause. If you use the bounds to make repeated statistical decisions, use a design calibrated for those looks and the chosen family of guardrails. The example uses one fixed checkpoint and treats the observed latency and cost caps as operational rules.

Drift: when the experiment's assumptions stop holding

Compare a recent window to a reference on recorded features such as request length, topic or locale. Input drift changes P(X)P(X). A policy update can change what counts as a correct answer, and a logging change can move a rate by changing its denominator. The same trend across two windows can have several explanations. Log serving version, metric definition and eligibility alongside the measurements.

For an ordered feature, a histogram on fixed reference-derived bin edges shows the distribution shift. The fixture also calculates a PSI-style score from the bin proportions and the two-sample KS statistic, the maximum absolute gap between the empirical cumulative distributions. Treat them as diagnostics. Calibration depends on window size, bin choices and details such as tied observations. Compare score and traffic changes by a common, adequately represented slice before attributing an overall movement to the model.

Worked example: from a synthetic production log to a decision

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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
        quantity   value
mean judge delta   3.207
              SE   0.306
       95% lower   2.606
       95% upper   3.807
               n 400.000

The 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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
Scatter plot of per-item judge delta against eval-set difficulty with three horizontal reference lines for the easy-quartile, overall, and hard-quartile means.
Per-item judge delta (candidate minus baseline) plotted against eval-set difficulty, with the easy-quartile, overall, and hard-quartile means marked. The aggregate mean is positive, but the candidate advantage is much smaller on the hardest quartile.

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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
 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]
CollapseExpand
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_unique
ConsoleOut [21]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
 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.0193

Day 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]
CollapseExpand
Line plot of the daily candidate-minus-baseline resolution effect across days in the test.
Daily candidate-minus-baseline resolution rates across seven simulated days. The fixture assigns days without a changing treatment effect. Day-to-day differences illustrate sampling variation.

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]
CollapseExpand
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]
CollapseExpand
         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         False

The 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 10−610^{-6} to each share in the logarithmic ratio, so a bin with no observations in one window still contributes a finite term.

PythonIn [27]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
Histogram comparing reference and current input difficulty distributions, with the current window shifted toward harder inputs.
Density histograms of early and late input difficulty on common bins. The late window has a dashed outline and contains harder requests in the synthetic stream.

Code: the practical loop

The final cells combine the efficacy interval, the ranking statistic and the canary gates.

Use the same assigned population in the final efficacy estimate and the reported assignment check.

First, a small helper that computes the standard two-proportion ITT contrast with a confidence interval and a label for the decision state.

PythonIn [30]
CollapseExpand
def itt_two_proportion(assigned, outcome):
    """ITT contrast of two binary outcome rates, grouped by assignment."""
    assigned = np.asarray(assigned)
    outcome = np.asarray(outcome)
    if assigned.ndim != 1 or assigned.shape != outcome.shape:
        raise ValueError("Supply one outcome for each assignment.")
    if set(assigned) != {"base", "cand"} or not np.isin(outcome, [0, 1]).all():
        raise ValueError("Supply both assignment arms and binary outcomes.")
    is_t = assigned == "cand"
    y_t = outcome[is_t]
    y_c = outcome[~is_t]
    p_t, n_t = y_t.mean(), len(y_t)
    p_c, n_c = y_c.mean(), len(y_c)
    diff = p_t - p_c
    se = np.sqrt(p_t * (1 - p_t) / n_t + p_c * (1 - p_c) / n_c)
    z = stats.norm.ppf(0.975)
    return {"diff": diff, "se": se, "lo": diff - z * se, "hi": diff + z * se}


def decision(ci):
    if ci["lo"] > 0:
        return "positive efficacy interval"
    if ci["hi"] < 0:
        return "negative efficacy interval"
    return "inconclusive (CI includes zero)"

The efficacy label describes where the fixed-look interval falls relative to zero.

For the interleaving summary, reuse the session-level sign test defined above.

Reuse the fixed-checkpoint rate bound in the final gate calculation.

PythonIn [31]
CollapseExpand
from fractions import Fraction


def gate_value(value):
    if isinstance(value, (bool, np.bool_)):
        return None
    if isinstance(value, (int, np.integer)):
        return int(value) if value >= 0 else None
    if (
        isinstance(value, (float, np.floating))
        and np.isfinite(value)
        and value >= 0
    ):
        return Fraction(*value.as_integer_ratio())
    return None


def guardrail_report(canary, thresholds):
    report = {}
    for name in ("harm", "error"):
        threshold = thresholds.get(f"{name}_ub")
        try:
            rate, upper = rate_bound(
                canary.get(f"{name}_events"), canary.get(f"{name}_n")
            )
        except ValueError:
            report[name] = {
                "breach": True,
                "reason": "invalid or missing counts",
            }
            continue
        rate_cap = gate_value(threshold)
        if rate_cap is None or rate_cap > 1:
            report[name] = {
                "breach": True,
                "reason": "invalid or missing rate cap",
            }
            continue
        report[name] = {
            "rate": rate,
            "ub99": upper,
            "threshold": threshold,
            "breach": gate_value(upper) > rate_cap,
        }

    for name, key in (
        ("latency", "p95_latency"),
        ("cost", "median_scaled_cost"),
    ):
        value, threshold = canary.get(key), thresholds.get(key)
        measured, cap = gate_value(value), gate_value(threshold)
        if measured is None or cap is None:
            report[name] = {
                "breach": True,
                "reason": "invalid or missing measurement or cap",
            }
            continue
        report[name] = {
            "value": value,
            "threshold": threshold,
            "breach": measured > cap,
        }
    return report

Now apply these functions to the synthetic data we already built, to show the assembled decision.

PythonIn [32]
CollapseExpand
itt = itt_two_proportion(ab["arm"].values, ab["resolved"].values)
inter = team_draft_test(
    interleave_log["a_clicks"].values, interleave_log["b_clicks"].values
)
guard = guardrail_report(
    {
        "harm_events": harm_cand.sum(),
        "harm_n": len(harm_cand),
        "error_events": err_cand.sum(),
        "error_n": len(err_cand),
        "p95_latency": lat_p95,
        "median_scaled_cost": cost_p50,
    },
    {
        "harm_ub": 0.0060,
        "error_ub": 0.0120,
        "p95_latency": 1500.0,
        "median_scaled_cost": 2.00,
    },
)
any_breach = any(row["breach"] for row in guard.values())
ConsoleOut [33]
CollapseExpand
Primary metric (ITT):
  effect=+0.0344  95% CI=[+0.0166, +0.0522]
  decision: positive efficacy interval

Interleaving (relative preference):
  A wins=936, B wins=899, p=0.40069215977663536

Guardrails:
  harm     {'rate': 0.002, 'ub99': np.float64(0.007012195349280362), 'threshold': 0.006, 'breach': True}
  error    {'rate': 0.006666666666666667, 'ub99': np.float64(0.013631708414812527), 'threshold': 0.012, 'breach': True}
  latency  {'value': np.float64(1797.3445235426595), 'threshold': 1500.0, 'breach': True}
  cost     {'value': np.float64(1.6269257240997714), 'threshold': 2.0, 'breach': False}

Any guardrail breach: True

Overall: HALT rollout

The three failed gates are safety clearance, error-rate clearance and observed p95 latency. The median scaled cost passes. The positive primary interval is insufficient for a ramp under these rules, so the result is HALT rollout.

Reading the decision

The offline and shadow scores both favor the candidate on their respective proxy samples. The blended-ranking fixture has 936 candidate wins and 899 baseline wins across 1,835 decisive sessions, with a two-sided p-value of about 0.401. The user-level experiment estimates an intent-to-treat resolution gain of about 3.44 percentage points, with a 95% interval from 1.66 to 5.22 points. The rollout holds because a favorable primary result still leaves three operational gates uncleared.

For the next checkpoint, record the eligible population, assignment unit, outcome maturity, measured denominators, thresholds and precise reason for holding. In the fictional example those fields explain the apparent tension between a resolution gain and a rollout halt.

Key Parameters

Keep the experimental configuration alongside the output. The person reviewing a reported rate should be able to reconstruct who entered its denominator, which model version served them and how long the outcome had to arrive.

ParameterWhat to retain
Assignment policyThe eligible population, randomization unit, configured allocation and version of the assignment rule.
Observation windowThe start event and maturity cutoff for each user, including the rule for delayed outcomes.
Primary effect thresholdThe smallest improvement worth acting on, in outcome units, alongside the preplanned significance level and decision horizon.
Canary ruleThe numerical cap, its unit, level and checkpoint for each rate bound, and which action follows a failed gate.
Drift windowsCalendar boundaries, the monitored feature definition, and the bin edges derived from the reference sample.

If a threshold changes during a rollout, retain which version produced each decision. A later analyst should be able to reapply a stated rule to the data that were available at that checkpoint.

Limitations & impact

The synthetic examples generate complete measurements immediately. In a support system a user can return several days later, submit a new ticket, or leave before the resolution window ends. An analysis opened before the follow-up horizon has matured can mix users with different amounts of time to resolve their issue. Record the age of the enrolled cohort at a checkpoint and make the decision after the prespecified eligibility and outcome conditions are met.

Resource coupling can change what a small canary represents. An isolated deployment may perform well with a small fraction of traffic and encounter queue limits after expansion. A higher traffic fraction can also change the workload seen by baseline users when the two arms share a dependency. Monitor the resource path and document the traffic fraction alongside the endpoint observations.

A refusal, handoff, or later correction can affect which follow-up interactions exist. The trial supports a comparison of assigned serving policies over the defined window. A replay can still be useful for inspecting the initial request and creating reproducible regressions, while a long-run outcome requires observation under the relevant policy.

Summary

For a release review, put the shadow comparison, randomized efficacy result and canary gate records in the same evidence packet. Include the paired roster behind the shadow estimate and the assigned roster behind the resolution contrast. In this example the next ramp stays on hold. A later checkpoint can reuse the prespecified gate definitions against fresh eligible observations after the needed fixes, with a recorded measurement window and traffic level.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about online experiments and production evaluation.

Online Experiments and Production Evaluation

Question 1 of 80 of 8 completed
In a shadow run, what does the candidate model receive and what happens to its output?
Join the discussionAsk a question or share what you learned.

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!

A different angle
All writing
Language AI Handbook · Vol. 18

Judge Calibration and Meta-Evaluation

Build counterbalanced calibration fixtures, measure agreement and bias, and validate LLM judges against a characterized expert reference.

31 min read
Language AI Handbook · Vol. 18

Live and Continuously Updated Benchmarks

Design live benchmarks with versioned releases, shared-item comparisons, explicit exposure controls, and reproducible scoring.

40 min read
Language AI Handbook · Vol. 18

Evaluation Harnesses and Reproducibility

Build a versioned evaluation harness that pins prompts, graders, and configs. Measure replay agreement, task-level uncertainty, and paired model differences.

47 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026onlineexperiments, author = {Michael Brenndoerfer}, title = {Online Experiments and Production Evaluation}, year = {2026}, url = {https://mbrenndoerfer.com/writing/online-experiments-production-evaluation-ab-testing-shadow-traffic}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-12-03} }
APAAcademic
Michael Brenndoerfer (2026). Online Experiments and Production Evaluation. Retrieved from https://mbrenndoerfer.com/writing/online-experiments-production-evaluation-ab-testing-shadow-traffic
MLAAcademic
Michael Brenndoerfer. "Online Experiments and Production Evaluation." 2026. Web. December 3, 2026. <https://mbrenndoerfer.com/writing/online-experiments-production-evaluation-ab-testing-shadow-traffic>.
CHICAGOAcademic
Michael Brenndoerfer. "Online Experiments and Production Evaluation." Accessed December 3, 2026. https://mbrenndoerfer.com/writing/online-experiments-production-evaluation-ab-testing-shadow-traffic.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Online Experiments and Production Evaluation'. Available at: https://mbrenndoerfer.com/writing/online-experiments-production-evaluation-ab-testing-shadow-traffic (Accessed: December 3, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Online Experiments and Production Evaluation. https://mbrenndoerfer.com/writing/online-experiments-production-evaluation-ab-testing-shadow-traffic
Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy