10A.9 Offline vs Online Evaluation

ProductionLesson 9 of 1213,792 words7 parts
Module 10A · 0 of 12 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12

Lessons 10A.1 to 10A.8 built the offline machine: curated datasets, deterministic graders, calibrated judges, regression suites and CI gates. All of it runs before release, on cases you chose in advance. This lesson covers the other half of the discipline: what you measure after release, on traffic you didn't choose, and how the two halves feed each other. You'll learn the taxonomy of online signals (explicit feedback, implicit behaviour, business and system metrics), how to score production quality without labels, how to run honest online experiments — A/B tests, interleaving, shadow mode, canaries, bandits and switchbacks — how to detect drift in inputs, outputs, models and judges, and how production failures flow back into your offline datasets. The lesson ends with evalkit/online.py, a minimal online-evaluation sampler you can run today with a fake judge and no API keys.

What you'll learn

  • The two worlds — offline vs online evaluation — what each can and cannot tell you, the feedback loop between them, and how to check that your offline score actually predicts online outcomes (metric alignment)
  • The full taxonomy of online signals: explicit feedback, implicit behaviour, business metrics, system metrics and safety signals — and the biases that make raw feedback misleading
  • How to evaluate quality without labels: sampled LLM-judge scoring, human review queues, assertion monitors, scheduled canary probes, user simulators and anomaly detection
  • Online experimentation done honestly: A/B test design (randomisation unit, sample size and power, duration, novelty effects, guardrail metrics, multiple comparisons, the peeking problem, ethics), interleaving, shadow mode, canary rollouts and feature flags, multi-armed bandits and switchback tests — plus the statistics for reading results and the plumbing checks (sample-ratio mismatch, A/A tests) that make them trustworthy
  • Drift detection: input, output, model-version, corpus and judge drift, measured with population stability index, KL and Jensen-Shannon divergence (with code), and what to do when drift fires
  • Closing the loop: failure triage, labelling, regression sets, prioritising fixes, retraining judges, versioned releases — and the privacy and compliance rules for using production data in evaluation
  • A working evalkit/online.py: stratified sampling of production traces, an injectable judge seam, score distributions, drift checks and alert thresholds — plus the observability-platform features (Langfuse, LangSmith, Phoenix) this hands off to Module 11A

What you don't need

  • API keys. Every code sample in this lesson is pure Python (standard library only) and runs with fakes; the judge seam means the same code works unchanged against a real provider when you have keys.
  • Judge design in depth. Lesson 10A.4 owns judge prompts and 10A.5 owns validating them; this lesson uses a validated judge as a component.
  • Offline eval machinery. Datasets (10A.2), scorers (10A.3), CI gates (10A.8) are assumed; links point back where needed.
  • Observability platforms. Tracing, dashboards, SLOs and alerting infrastructure are Module 11A; safety and security engineering is Module 12. This lesson teaches the evaluation layer that sits on top of them.

Setup

All samples are pure standard library — no packages to install. If you are building the evalkit package across this module, this lesson adds online.py (the sampler) and uses small standalone scripts (ab_sample_size.py, drift_stats.py, feedback_bias.py, alignment.py, bandit.py, srm_check.py) that each run on their own:

bash
uv init evalkit --bare --python 3.13 && cd evalkit   # first time only; see lesson 03.1 for the full setup
mkdir -p evalkit                                     # the package directory
# save each script from this lesson, e.g. online.py (Part 7) as evalkit/online.py, then:
uv run python evalkit/online.py

If you already have the module's earlier evalkit files, place online.py beside them inside the evalkit/ package; it imports nothing from them, so it works standalone. The other scripts (alignment.py, feedback_bias.py, ab_sample_size.py, srm_check.py, bandit.py, drift_stats.py) can live anywhere: save one and run it with python3 <file>. Later lessons (10A.10) collect the full package in an appendix.


What you must be able to do after this lesson#

  • Explain what offline and online evaluation can and cannot tell you
  • List the types of online signals and the biases in raw feedback
  • Score production quality without labels using sampled judges and review queues
  • Design an online A/B test with a randomisation unit, sample size and guardrail metrics
  • Detect drift with population stability index and divergence measures
  • Build a minimal online sampler that scores production traces

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"The eval suite is green, so we're fine." 1.1 What each world can tell you
"Does our offline score predict what users experience?" 1.3 Metric alignment
"Users are complaining but the metrics look fine." Part 2: Online signals
"Thumbs-up rate dropped 4 points — is the model worse?" 2.5 The biases in feedback
"We can't label production traffic at scale." Part 3: Evaluating without labels
"Should we A/B test this prompt change?" Part 4: Experimentation
"How many users do we need before we can call it?" 4.1 Sample size and power
"Someone keeps peeking at the dashboard." 4.1 The peeking problem
"The new model silently changed — how do we notice?" Part 5: Drift detection
"Query mix shifted after the marketing campaign." 5.2 PSI, KL and JS divergence
"Production is failing in ways the eval set never saw." Part 6: Closing the loop
"Can we use production traces to build evals?" 6.4 Privacy and compliance
"What does Langfuse's scores API give us?" 6.6 The observability hand-off

Part 1: The two worlds: offline vs online evaluation#

1.1 What each world can and cannot tell you#

Every evaluation in this module so far is offline: a fixed dataset, a fixed scorer, a fixed threshold, run before a change ships. Online evaluation is everything measured on live traffic after (or alongside) release: what users did, what the system cost, what broke, and how quality actually moved.

The split is not "test vs production". It is curated vs naturalistic, and each has a failure mode the other cannot see:

Offline evaluation Online evaluation
Data Cases you wrote, sampled or generated — you know the distribution Real traffic — the distribution users actually produce, including the long tail you never imagined
Ground truth References, expected facts, rubrics, judges you calibrated Mostly none: signals are proxies (clicks, retries, escalations) or sampled judgement
What it proves "On these cases, version B beats version A by X, with a confidence interval" "In production, B moved metric M by Y without breaking guardrail G"
What it cannot prove That real users hit the same cases, in the same proportions, with the same patience Causality without an experiment; why quality changed; rare-but-severe failures you didn't sample
Cost per case High (you pay to build and label the set) but bounded and repeatable Low per case at scale, but labels are scarce and biased toward whoever complains
Repeatability High — same dataset, pinned versions Low — traffic drifts daily; a number today isn't comparable to last week without drift checks
When it runs Every commit, every PR, before release Continuously, always on

1.2 The feedback loop between them#

Offline and online are not two separate disciplines — they are one loop, and the loop is the product:

flowchart LR
    subgraph prod ["Production"]
        U["Users"] --> APP["LLM feature"]
        APP --> TR["Traces + signals<br/>(feedback, behaviour, costs)"]
    end
    subgraph offline ["Offline loop"]
        TR --> TRIAGE["Failure triage queue"]
        TRIAGE --> DS["Eval dataset<br/>(versioned, stratified)"]
        DS --> EV["Offline eval suite<br/>(scorers + judges + CI gate)"]
        EV --> REL["Gated release<br/>(prompt/model/index change)"]
    end
    REL --> APP
    TR --> MON["Online monitors<br/>(sampled judges, assertions,<br/>canaries, drift checks)"]
    MON --> ALERT["Alerts + dashboards"]
    ALERT --> TRIAGE
    EV -.->|"thresholds become<br/>guardrail metrics"| MON

Two couplings make the loop work:

  • Production failures become dataset cases. Every confirmed online failure should leave behind a labelled example (10A.2 owns dataset hygiene; 07.10 shows the RAG version of this rule). Without this, your offline set slowly ages into a museum of last quarter's bugs.
  • Offline thresholds become online guardrails. The pass rate your CI gate demands becomes the floor your online monitors alert below. If offline says "95% of answers must cite a source" and online citation-validity drops under that, something changed that your dataset didn't cover — which is itself a signal (see Part 5).

1.3 Metric alignment: does offline predict online?#

The deepest question in this lesson: when your offline score goes up, does the thing users experience go up too? If not, you're optimising a proxy — possibly a proxy that is anti-correlated with the real goal (a judge that rewards verbosity while users want brevity).

How to check alignment. Across the last N released versions (prompt, model or index changes), record two numbers per version: the offline eval score and the online metric (task success, CSAT, resolution rate). Then compute the rank correlation between them — Spearman's ρ — which asks "do the versions rank the same way on both?" without assuming the relationship is linear:

python
# alignment.py — Spearman rank correlation between offline eval scores
# and online success rates across released versions. Stdlib only.

import math

def ranks(xs):
    """Average ranks for ties (1 = smallest)."""
    order = sorted(range(len(xs)), key=lambda i: xs[i])
    out = [0.0] * len(xs)
    i = 0
    while i < len(order):
        j = i
        while j + 1 < len(order) and xs[order[j + 1]] == xs[order[i]]:
            j += 1
        avg = (i + j) / 2 + 1
        for k in range(i, j + 1):
            out[order[k]] = avg
        i = j + 1
    return out

def pearson(x, y):
    n = len(x)
    mx, my = sum(x) / n, sum(y) / n
    cov = sum((a - mx) * (b - my) for a, b in zip(x, y))
    vx = sum((a - mx) ** 2 for a in x)
    vy = sum((b - my) ** 2 for b in y)
    return cov / math.sqrt(vx * vy) if vx and vy else 0.0

def spearman(x, y):
    return pearson(ranks(x), ranks(y))

if __name__ == "__main__":
    # Ten prompt versions: offline pass-rate vs online task-success rate.
    offline = [0.62, 0.66, 0.70, 0.71, 0.74, 0.75, 0.78, 0.80, 0.82, 0.85]
    online  = [0.55, 0.57, 0.60, 0.63, 0.61, 0.66, 0.68, 0.70, 0.69, 0.73]

    print("version  offline  online")
    for i, (o, n) in enumerate(zip(offline, online), 1):
        print(f"  v{i:<3}   {o:.2f}     {n:.2f}")
    rho = spearman(offline, online)
    print(f"\nSpearman rank correlation: {rho:.2f}")
Output · real — this script is pure stdlib13 lines
version  offline  online
  v1     0.62     0.55
  v2     0.66     0.57
  v3     0.70     0.60
  v4     0.71     0.63
  v5     0.74     0.61
  v6     0.75     0.66
  v7     0.78     0.68
  v8     0.80     0.70
  v9     0.82     0.69
  v10    0.85     0.73

Spearman rank correlation: 0.98

How to read ρ:

ρ range Reading What to do
0.9+ Offline ranks versions almost exactly as online does Your offline suite is a trustworthy proxy; invest in keeping it fast and broad
0.5–0.9 Directionally aligned but noisy Find the slices where they disagree; the disagreement is your next eval cases
~0 No relationship Your offline metric is measuring something users don't care about — or online noise swamps it. Rebuild one of them
Negative Anti-aligned Dangerous: you're optimising against users. Stop CI gating on that metric immediately

Part 2: Online signals: what production tells you#

Online signals come in five families. The engineering skill is not collecting them — your observability platform already does that — but knowing what each one means, how biased it is, and which decisions it's fit for.

2.1 Explicit feedback#

Signals the user deliberately gives you:

Signal What it measures Strengths Weaknesses
Thumbs up/down Satisfaction with one answer Cheap to implement; unambiguous polarity Very low response rate; responders are self-selected (usually the most satisfied or most annoyed)
Star ratings / CSAT Satisfaction on a scale Comparable across versions; industry-standard for support Same selection bias; scale interpretation drifts between user segments
Written comments / corrections Why it was good or bad Richest signal — nearly free labelled failures Sparse; needs triage; may contain PII
Edits and regenerations Whether the user had to fix your output Strong implicit-negative signal Confounded: users edit for style, not just correctness
Copy / accept / "use this" actions Whether the output was useful enough to keep High-intent positive signal Confounded by answer length and task type

The pattern to internalise: explicit feedback is high-precision but low-recall, and its polarity is biased by who bothers to respond. Thumbs-down over-represents users who were annoyed enough to click; thumbs-up over-represents users who liked it enough to bother. The rate you compute from responders is not the rate in the population — 2.5 shows the maths.

2.2 Implicit behaviour#

Signals inferred from what users did, not what they said:

Signal What it suggests Caveats
Retry / regenerate The first answer didn't satisfy Could be curiosity, not dissatisfaction; count per session, not per answer
Abandonment / session exit Gave up Confounded by task completion — a user who got their answer and left looks identical to one who gave up
Escalation to human / support ticket The failure was bad enough to cost money Highest-severity signal; always triage into the eval set
Time-to-resolution / handle time Efficiency of the whole interaction A fast wrong answer beats a slow right one on this metric — pair it with a quality metric
Follow-up questions / reformulations The answer didn't fully land For RAG this is the classic "retrieval or answer miss" signal (06.10, 8.1)
Task completion Did the user achieve their goal? The closest thing to a north-star for task-shaped products; hardest to measure — needs outcome instrumentation, not just click events

Whose traffic counts? Every rate in this part is only as honest as its denominator. Production logs mix in bots, crawlers, your own team, uptime probes and the canary/simulator traffic of Part 3 — tag synthetic and internal traffic at ingestion and exclude it from user-facing metrics, or your probes will contaminate the very distributions Part 5 monitors. And feedback arrives late: thumbs, CSAT and conversions land hours to days after the interaction, so dashboards and experiment readouts need an attribution window — count feedback only within a fixed number of days of its trace, and expect early readouts to over-represent fast responders.

2.3 Business and system metrics#

Family Examples Role in evaluation
Business Conversion, deflection rate (questions resolved without a human), CSAT, handle time, retention The outcome layer — what the feature is for. Quality metrics should predict these; if they diverge, your quality metric is misaligned (1.3)
System Latency (p50/p95/TTFT), error rate, token cost per request, refusal/abstention rate, retry rate Guardrail metrics: they rarely improve quality, but they cap it. A prompt change that doubles abstentions or triples cost is a regression even if judged quality rises
Safety Policy violations, jailbreak attempts detected, PII leakage flags, user abuse reports Owned by Module 12 for the defences; here you learn to measure the rates online (6.5)

2.4 The metric hierarchy, online edition#

10A.1 defined the metric hierarchy for offline evals: north-star (what the business cares about), guardrail (must not regress), diagnostic (explains why). Online, the same structure applies but the signals differ:

  • North-star online: task completion, deflection, CSAT, conversion — whatever your product's actual goal is.
  • Guardrail online: latency percentiles, error rate, cost per request, refusal rate, escalation rate.
  • Diagnostic online: judge score distributions by slice, assertion-monitor failure rates, drift statistics, per-slice feedback.

A common failure: optimising the diagnostic (judge score) until it diverges from the north-star (users leave). 1.3 is the check.

2.5 The biases in feedback, and how to correct them#

Four biases distort every online signal:

  1. Selection bias: only some users respond. If unhappy users respond 7× more often than happy ones, the raw thumbs-up rate massively understates satisfaction.
  2. Position/ordering bias: in pairwise or list interfaces, users favour whatever they saw first or last — the same position bias 10A.4 documents for judges applies to humans.
  3. Silent-majority bias: most users never respond at all, and they may differ systematically from responders (busier, less engaged, different segment).
  4. Confounding by exposure: a metric measured only on traffic that saw a feature isn't comparable to one measured on all traffic — new users, power users and different routes have different baselines.

The correction toolkit (in increasing order of rigour):

  • Say what the denominator is. "62% positive among the 4% who responded" is honest; "62% satisfaction" is not.
  • Weight by propensity. If you can estimate how likely each segment is to respond (from a survey or an experiment), weight responses by 1/propensity — over-represented complainers get down-weighted. The demo below shows it working.
  • Compare like with like. Measure the same signal on control and treatment in an experiment (Part 4) — randomisation balances the confounders for you.
  • Use behavioural signals as the check. If thumbs say "fine" but escalations doubled, trust the escalations.
python
# feedback_bias.py — why the raw thumbs-up rate lies. Stdlib only.
#
# Model: 80% of users are satisfied. Satisfied users respond 2% of the
# time, dissatisfied users 15%. Only responders appear in the data.

import random

def simulate(n_users=20_000, seed=3):
    rng = random.Random(seed)
    sat_propensity, unsat_propensity = 0.02, 0.15
    p_satisfied = 0.80

    pos_weight = neg_weight = 0.0
    naive_pos_n = naive_n = 0
    for _ in range(n_users):
        satisfied = rng.random() < p_satisfied
        propensity = sat_propensity if satisfied else unsat_propensity
        if rng.random() >= propensity:
            continue                      # silent majority: never responds
        naive_n += 1
        naive_pos_n += satisfied
        w = 1.0 / propensity             # inverse-propensity weight
        if satisfied:
            pos_weight += w
        else:
            neg_weight += w

    return (naive_pos_n / naive_n,
            pos_weight / (pos_weight + neg_weight),
            naive_n, p_satisfied)

if __name__ == "__main__":
    naive, corrected, n, truth = simulate()
    print(f"ground-truth satisfaction : {truth:.0%}")
    print(f"responses collected       : {n}")
    print(f"naive thumbs-up rate      : {naive:.1%}   <- what the dashboard shows")
    print(f"propensity-corrected      : {corrected:.1%}   <- closer to truth")
Output · real4 lines
ground-truth satisfaction : 80%
responses collected       : 939
naive thumbs-up rate      : 35.6%   <- what the dashboard shows
propensity-corrected      : 80.5%   <- closer to truth

The naive rate is off by about 44 points — not a rounding error, a different story. The corrected rate needs propensity estimates you usually don't have — and the propensity depends on the very sentiment you are trying to measure, so the only honest source is a small random probe survey of users, responders and non-responders alike; that's why the honest answer is "feedback is directional, not absolute", and why experiments (Part 4) beat dashboards for decisions.


Part 3: Evaluating quality online without labels#

Most production traces will never be labelled by a human. The question is how to get a quality signal on them anyway. There are six mechanisms, roughly in order of cost per trace (cheapest first). (For agent traces, the span tree is a trajectory, and the deterministic graders of 10A.7 run on it directly: see 10A.7, 10.4.)

flowchart TD
    T["Production traces"] --> S{"Sample<br/>uniform / stratified /<br/>triggered"}
    S --> J["Sampled LLM-judge<br/>scoring (reference-free)"]
    S --> A["Assertion monitors<br/>format, citations, refusals"]
    S --> H["Human review queues<br/>stratified + uncertainty"]
    S --> C["Scheduled canary probes<br/>+ user simulators"]
    J --> M["Online metrics<br/>score dist, drift, alerts"]
    A --> M
    H --> M
    C --> M
    M --> TRIAGE["Failure triage"]
    TRIAGE --> DS["Eval dataset"]
    DS -.->|"regression cases"| OFF["Offline evals<br/>(10A.1 to 10A.8)"]

3.1 Sampled LLM-judge scoring#

Run your calibrated judge (10A.4, 10A.5) on a sample of production traces — not all of them. The maths is the same as any sampling problem: if you judge 2% of traffic uniformly, your score distribution is an unbiased estimate of the population's, with a confidence interval that widens as the sample shrinks (10A.2 covers sample-size intuition).

Design rules that matter:

  • Sample uniformly for the headline number — stratified sampling (Part 7 implements it) is for coverage, not for the mean.
  • Sample non-uniformly for discovery — over-sample traces that look risky (low confidence, long answers, tool errors, user follow-ups) to find failures faster. But never report the risky-slice score as the population score.
  • Use reference-free judges. Production traces rarely have gold answers; the judge grades the answer against the question, the retrieved context (for RAG) and your rubric — the same reference-free designs 10A.4 covers.
  • Track the score distribution, not just the mean. A stable mean can hide a growing tail of catastrophic failures. Plot the histogram; alert on distribution shift (Part 5).
  • Version the judge. Judge prompt or model changes silently change every historical comparison — record judge_version on every score (10A.5 makes this a rule).
  • Cost-control by design: judge calls are the most expensive part of online eval. Sample rates of 1–10% are typical for high-volume features; batch APIs (03.9) cut the cost ~50% for non-urgent scoring; cheap-judge-first tiering (10A.4) spends strong-judge tokens only where they matter.
python
# ppi_demo.py — prediction-powered estimate of a production pass rate.
# Stdlib only. A judge scores everything cheaply; humans label a small
# random subset; the human labels correct the judge's bias.

import math
import random

Z = 1.96  # 95% two-sided normal quantile


def simulate(n_total=5000, n_human=200, seed=5):
    rng = random.Random(seed)
    rows = []
    for _ in range(n_total):
        human_pass = rng.random() < 0.70                    # hidden truth
        # a lenient judge: says "pass" for 97% of true passes, 25% of true fails
        judge_pass = rng.random() < (0.97 if human_pass else 0.25)
        rows.append((float(judge_pass), float(human_pass)))
    labelled = rng.sample(range(n_total), n_human)         # RANDOM subset
    return rows, set(labelled)


def mean_var(xs):
    m = sum(xs) / len(xs)
    return m, sum((x - m) ** 2 for x in xs) / (len(xs) - 1)


def ci(centre, var_of_mean):
    half = Z * math.sqrt(var_of_mean)
    return centre - half, centre + half


if __name__ == "__main__":
    rows, labelled = simulate()
    judge_all = [j for j, _ in rows]
    human_lab = [h for i, (_, h) in enumerate(rows) if i in labelled]
    judge_lab = [j for i, (j, _) in enumerate(rows) if i in labelled]

    # 1. Judge only: cheap, tight, WRONG (it is biased)
    m, v = mean_var(judge_all)
    print("judge only      : %.3f  CI (%.3f, %.3f)" % ((m,) + ci(m, v / len(judge_all))))

    # 2. Humans only: unbiased, but only 200 labels
    m, v = mean_var(human_lab)
    print("humans only     : %.3f  CI (%.3f, %.3f)" % ((m,) + ci(m, v / len(human_lab))))

    # 3. Prediction-powered: judge mean on everything + a bias correction
    #    measured on the human-labelled subset (human - judge).
    resid = [h - j for h, j in zip(human_lab, judge_lab)]
    m_j, v_j = mean_var(judge_all)
    m_r, v_r = mean_var(resid)
    theta = m_j + m_r
    var = v_j / len(judge_all) + v_r / len(resid)
    print("prediction-powered: %.3f  CI (%.3f, %.3f)" % ((theta,) + ci(theta, var)))
    print("true rate        : %.3f" % (sum(h for _, h in rows) / len(rows)))
Output · real — deterministic with seed 54 lines
judge only      : 0.750  CI (0.738, 0.762)
humans only     : 0.710  CI (0.647, 0.773)
prediction-powered: 0.680  CI (0.633, 0.726)
true rate        : 0.694

The judge-only interval is tight and excludes the truth; the human-only interval is honest but wide; the prediction-powered interval is both honest and narrower than humans alone, because the judge supplies information the 200 labels cannot. Conditions that matter: the human subset must be a random sample of the same traffic the judge scored (not the traces your risk signals flagged), the judge version must be the one used on the labelled subset, and the normal-approximation interval needs a few hundred labels. Packages such as ppi_py implement tuned, lower-variance variants; this is the principle.

3.2 Human review queues#

Judges scale but have error; humans are the ground truth but don't scale. The compromise is a review queue: a prioritised list of traces a human labels, feeding three purposes — calibrating the judge (10A.5), auditing judge drift, and mining eval-set cases.

Queue design that works:

  • Stratified sampling for coverage: guarantee the queue contains each route, language, slice and failure mode in proportion — a purely random queue over-represents whatever's common.
  • Uncertainty/disagreement sampling for yield: prioritise traces where the judge is uncertain, where two judges disagree, or where cheap signals (retries, follow-ups, short answers) fire. This finds failures far faster than random review — the exact multiplier depends on how concentrated failures are and how informative your risk signals are, so measure it on your own traffic rather than quoting a rule of thumb.
  • Rubric-anchored review: give reviewers the same rubric and anchored examples the judge uses (10A.4), so human labels and judge labels mean the same thing — otherwise your κ measurement (10A.5) compares apples to oranges.
  • Review UX matters: show the question, the answer, the retrieved context (for RAG), the judge's verdict and reasoning, and one-click label + comment. Hide the judge's verdict until after the human labels if you want unbiased κ; show it if you want efficient correction — pick per purpose.

The platforms make this concrete. As of November 2026:

  • Langfuse has annotation queues plus a scores API (GET /api/public/v3/scores) with five score types keyed by dataType (NUMERIC, CATEGORICAL, BOOLEAN, TEXT, CORRECTION — the last for corrected outputs), and explicit-vs-implicit user-feedback docs that map directly onto Part 2. Its LLM-as-judge can run on live production traces with sampling.
  • LangSmith has online evaluators that run on production runs or threads with filters and sampling rates, annotation queues in two styles (single-run and pairwise annotation queues that show two outputs side by side), and feedback tags for thumbs/comments.
  • Arize Phoenix models every annotation with an annotator_kind — HUMAN, LLM, CODE, DECISION or AGENT in its client and REST API (as of November 2026, from the Arize-ai/phoenix source; HUMAN, LLM and CODE are the three this lesson uses) — so a span can carry a human label, a judge score and a code assertion simultaneously, and its evals library runs client-side or server-side.

3.3 Assertion monitors#

Not every quality check needs a model. Assertion monitors are deterministic checks run continuously on production traffic — the online version of 10A.3's hard assertions:

  • Format validity: does the output parse as the declared JSON shape? Did it respect max_tokens? Is it in the right language?
  • Citation validity (RAG): do cited chunk IDs exist? Do quotes appear verbatim in the cited chunk? (07.5 owns citation mechanics; the monitor runs the same checks online.)
  • Refusal/abstention rate: is the system refusing or abstaining more than its baseline? A doubling is a regression even if judged quality is flat.
  • Policy strings: forbidden phrases, required disclosures, PII-pattern scans on outputs (05.5 owns the normalisation the checks build on).
  • Latency/cost budgets: p95 latency, tokens per request, cost per request — the system guardrails from 2.3.

Assertions are cheap enough to run on every trace, not a sample — which makes them your highest-coverage online signal. Their failure modes belong in the alert path, not just the dashboard.

3.4 Canary prompts and scheduled probes#

Assertion monitors watch what users happened to send. Canary probes actively send known queries on a schedule — the production version of a smoke test:

  • A fixed set of ~20–50 queries with known-good expected properties (must cite, must refuse, must extract field X, must answer in ≤N tokens), run every N minutes against production.
  • Catches failures before users report them: provider model updates, index corruption, prompt regressions, dependency upgrades.
  • Distinct from 06.10's canary queries (retrieval-specific known-answer probes) and 04.9's canary cases (prompt-regression cases): same idea, different layer. This lesson uses "canary probe" for the scheduled production-facing job.

3.5 User-simulator probes#

For conversational and agentic products, a simulated user (an LLM playing a persona with a goal) can probe multi-turn behaviour that single-turn assertions can't reach: does the agent recover from an ambiguous first answer? Does it stay in persona over 10 turns? Does it refuse appropriately when the simulated user pushes?

The machinery overlaps with 10A.2's synthetic users and 10A.7's agent evals — the online-specific part is running probes on a schedule against production and comparing scores over time. Treat simulator results as a diagnostic signal ("conversation quality drifted this week"), not a release gate — simulators have their own biases and can't replace real-traffic signals. Before you trust a probe's trend, validate the simulator against real conversations (10A.12, Part 7).

3.6 Anomaly detection on score, latency and cost#

Beyond fixed thresholds, anomaly detection learns the normal range of a metric and alerts on deviations: a judge-score distribution that shifts, a latency percentile that creeps, a cost-per-request that doubles, an abstention rate that spikes.

The honest version for most teams is simpler than ML anomaly detection:

  • Baseline + tolerance bands: compute the metric's distribution over a trailing window (e.g. 7 days); alert when today falls outside mean ± k·σ or a percentile band.
  • PSI on distributions: the same drift statistic as 5.2 applied to score histograms — "is today's score distribution the same shape as last week's?"
  • CUSUM-style cumulative alerts: small persistent shifts that never trip a daily threshold still matter; cumulative-sum alerts catch them. (Module 11A owns the alerting infrastructure; here you need the signal definitions.)

Whatever you choose, alert on rates and distributions, not raw counts — traffic volume varies by hour and day, and raw-count alerts are noise.

3.7 Where alerts live#

Setting thresholds, routing alerts, on-call rotations and SLOs are Module 11A's subject (its metrics/SLO/alerting lesson). What you take from this part: every online signal above should terminate in one of three places — an alert (act now), a dashboard (watch), or the eval dataset (learn). A signal that goes nowhere is instrumentation theatre.


Part 4: Experimentation online#

Online signals tell you what happened; experiments tell you what caused it. This part is the full methodology for changing something live and learning whether it helped — the deepest part of the lesson, because it's where most teams quietly fool themselves.

flowchart TD
    Q{"What are you<br/>changing?"} --> O["Offline eval first<br/>always"]
    O --> D{"Risk / blast radius?"}
    D -->|"low, reversible"| SH["Shadow mode<br/>log would-be answers"]
    D -->|"medium"| CA["Canary rollout<br/>1-5% of traffic"]
    D -->|"needs causal read"| AB["A/B test<br/>randomised units"]
    CA --> AB
    AB --> G{"Guardrails OK<br/>+ metric wins?"}
    G -->|"yes"| FULL["Ramp to 100%"]
    G -->|"no / unclear"| OFF
    SH -.->|"agree with offline?"| AB
    AB -.->|"shared state /<br/>carry-over"| SW["Switchback design"]

4.1 A/B tests: design it honestly#

An A/B test (online controlled experiment) randomly assigns each unit of traffic to a control or treatment and compares outcomes. The canonical reference is Kohavi, Tang and Xu's Trustworthy Online Controlled Experiments (Cambridge, 2020) — the book Google, LinkedIn and Microsoft engineers wrote from running thousands of experiments a year. Everything below is its discipline applied to LLM features.

Choose the randomisation unit first — it determines what you're actually measuring:

Unit Good for Watch out for
User Most product metrics; the usual choice Needs enough distinct users; returning users see one variant consistently
Session When a user's sessions are independent (search, support tickets) Same user can see both variants across sessions — fine if the metric is per-session
Request / turn Per-answer metrics in multi-turn products Contaminates conversation-level metrics: turn 3's answer depends on turn 1's variant
Time (switchback) Shared-state systems where units contaminate each other Carry-over effects; see 4.6

04.10, 8.2 already built the sticky-assignment machinery (assign_variant — hash a stable unit ID so each unit always lands in the same arm). Re-use it; this lesson owns the design around it. Log the assignment, the variant and the prompt/model version with every call — without that, analysis is impossible.

Sample size and power. The single most-misunderstood number in experimentation. You need enough units per arm that a real effect would be visible above noise. For a rate metric (conversion, success, thumbs-up), the normal approximation gives:

text
n per arm ≈ (z_α + z_β)² × (p₁(1-p₁) + p₂(1-p₂)) / (p₁ - p₂)²

where p₁ is the baseline rate, p₂ = p₁ + minimum-detectable-effect, z_α ≈ 1.96 for α=0.05 two-sided, z_β ≈ 0.84 for 80% power. In plain English: the smaller the effect you want to detect, and the closer to 50% your baseline rate is, the more users you need.

python
# ab_sample_size.py — users needed per arm for a two-proportion test.
# Stdlib only (math.erf for the normal CDF).

import math

def norm_cdf(x):
    return 0.5 * (1 + math.erf(x / math.sqrt(2)))

def z_quantile(p):
    lo, hi = -10.0, 10.0
    for _ in range(80):
        mid = (lo + hi) / 2
        if norm_cdf(mid) < p:
            lo = mid
        else:
            hi = mid
    return (lo + hi) / 2

def sample_size_per_arm(p_control, mde, alpha=0.05, power=0.8):
    """Users per arm to detect an ABSOLUTE difference of `mde` in a rate."""
    p_treat = p_control + mde
    za = z_quantile(1 - alpha / 2)
    zb = z_quantile(power)
    var = p_control * (1 - p_control) + p_treat * (1 - p_treat)
    return math.ceil((za + zb) ** 2 * var / mde ** 2)

if __name__ == "__main__":
    print("users needed PER ARM (alpha=0.05 two-sided, power=0.8)\n")
    print(f"{'baseline':>9} {'+2pp':>9} {'+5pp':>9} {'+10pp':>9} {'+1pp':>9}")
    for base in [0.10, 0.30, 0.50, 0.70]:
        row = [sample_size_per_arm(base, d) for d in (0.02, 0.05, 0.10, 0.01)]
        print(f"{base:>8.0%} " + " ".join(f"{n:>9,}" for n in row))
Output · real7 lines
users needed PER ARM (alpha=0.05 two-sided, power=0.8)

 baseline      +2pp      +5pp     +10pp      +1pp
     10%     3,839       683       197    14,749
     30%     8,391     1,374       354    33,272
     50%     9,804     1,562       385    39,237
     70%     8,077     1,248       291    32,644

Read it as: detecting a 2-point lift on a 30% baseline needs ~8,400 users per arm — ~17,000 total. A 10-point lift needs only ~350 per arm. Most LLM experiments are powered for big effects only; a "5% quality improvement" on a mid-range metric is usually undetectable without enormous traffic. Plan experiments around the smallest effect that would change your decision, not the smallest you'd like to see.

That formula is for rate metrics — proportions like conversion, resolution or thumbs-up. Continuous metrics (handle time, judge scores, latency, tokens per request) need a different calculation: the same shape, but built on the metric's variance rather than p(1−p), in the spirit of a two-sample t-test. The paired-bootstrap machinery in 10A.8 (evalkit.compare) does the offline version of this on per-case differences; experimentation platforms compute the online equivalent automatically — the practical point is identical: know your variance before you launch.

Duration. Run for at least one full weekly cycle (weekday/weekend mix matters for consumer products) and until you hit the pre-registered sample size — whichever is later. Don't stop early because the chart looks good (the peeking problem below).

Novelty and primacy effects. Users react to change, not just to the variant: a new UI or prompt gets a curiosity bump that fades over days. Counter by (a) running long enough for the novelty to wash out, (b) analysing only the post-novelty window if you must decide sooner, and (c) pre-registering the analysis window in the experiment doc.

Guardrail metrics. Every experiment needs metrics that can veto the winner: latency p95, error rate, cost per request, refusal/abstention rate, escalation rate, safety-violation rate. A treatment that wins on quality but doubles cost or trips a safety signal does not ship — the guardrail is the veto, not another thing to average in.

Multiple metrics. Declare one primary metric (the thing the change is for) and a small set of secondaries before you start. Every additional metric you check multiplies your false-positive rate (10A.8 covers multiple-comparison control for eval slices; the same discipline applies online). Slicing results by country, device or user tier is where Simpson's paradox lives — see 4.7.

The peeking problem. If you check the p-value every hour and stop when it crosses 0.05, your false-positive rate isn't 5% — it's far higher, because you're taking the minimum p-value over many looks. Johari, Koomen, Pekelis and Walsh showed in "Peeking at A/B Tests" (KDD 2017) that standard p-values break down under continuous monitoring, and proposed always-valid p-values and confidence intervals, provably valid however you decide when to stop (the paper reports an implementation in a large commercial A/B-testing platform). How much worse than 5% it gets depends on how often you look and for how long — simulate it on an A/A test (below) rather than trusting a rule of thumb. Practical rules:

  • Pre-register the sample size and end date; analyse once at the end.
  • If you must monitor, use a platform with always-valid inference, or apply a sequential-testing correction — don't eyeball the naive p-value.
  • "It looks significant" is not a reason to stop; it's a reason to wait for the pre-registered end.

Ethics and user trust. Experiments on real users carry obligations: don't test harmful or deceptive variants; don't withhold a clearly-better experience from the control group longer than needed; be able to explain the experiment; respect consent and regional rules (02.9, Part 9 covers the data side). For LLM features specifically: a variant that is less safe is never an acceptable experiment arm — safety guardrails are vetoes, not metrics.

4.2 Interleaving#

For ranking and retrieval comparisons, there's a cheaper design than A/B: interleaving. Instead of showing user A only results from system 1 and user B only from system 2, you merge the two result lists into one interleaved list, track which items the user clicks, and credit the click to the system that produced it. Because both systems serve the same user on the same query, user-level confounders cancel out — interleaving is dramatically more sensitive than A/B for ranking quality.

Chapelle, Joachims, Radlinski and Yue's "Large-scale validation and analysis of interleaved search evaluation" (ACM TOIS, 2012) is the canonical validation: interleaving agrees well with offline judgements and is far more statistically efficient than A/B for ranking. The catch: it only works when (a) you can merge two outputs into one presentation, and (b) clicks are a meaningful signal. For generative LLM answers you can't interleave two prose answers into one — interleaving is a retrieval/ranking tool (06.10 owns retrieval evals; this is the experiment-design angle). Don't confuse it with the other interleaving in the glossary — the round-robin merge of ranked lists in hybrid search (06.8) — same word, different job.

4.3 Shadow mode#

Shadow mode (a.k.a. dark launch, traffic mirroring): the candidate system runs on live requests in parallel with production, but its output is logged and discarded — the user sees only the production answer. You get real-traffic evaluation with zero user risk.

  • Best for: changes too big or risky for A/B — a new retrieval index, a model swap, a rewritten prompt — and for building the eval set from real traffic before launch.
  • Cost: you pay for both systems on the shadowed fraction — double inference cost for that share. Shadow a sample (1–10%), not all traffic.
  • What it measures: offline-style metrics on the production distribution — run your scorers and judges on the shadow outputs and compare distributions to production. It answers "does the candidate behave differently on real inputs?" It does not answer "do users prefer it?" — there's no user signal on a discarded answer.
  • Pitfall: shadow traffic isn't production traffic if your shadow path differs (different latency, different downstream state). Keep the shadow faithful or label the difference.

07.9, Part 8 previews shadow traffic for RAG specifically; 05.9 uses shadow evaluation for index cutovers. This lesson owns the general pattern.

4.4 Canary rollouts and feature flags#

Between "shadow" and "full A/B" sits the canary rollout: release the change to a small slice of traffic (1–5%), watch the guardrails and quality signals, then ramp. It's not an experiment — there's no randomised control — it's a safety mechanism: catch the catastrophic failure on 2% of users before it hits 100%.

The machinery is feature flags: runtime switches that route traffic to variants without redeploying. The landscape as of November 2026:

Tool Model Notes
Flagsmith Open source (BSD-3-Clause on GitHub), self-host or cloud Feature flags + remote config; free cloud plan of 50,000 requests/month (as of November 2026)
GrowthBook Open-source core (MIT Expat outside the enterprise directories; code under those directories is under the GrowthBook Enterprise License, per the repo's root LICENSE as of November 2026), self-host or cloud Flags plus built-in A/B experimentation and warehouse-native analysis; Thompson-sampling bandits on its Pro and Enterprise plans
Unleash Open source (AGPL-3.0 server on GitHub, a copyleft licence: read it before embedding or modifying), self-host or cloud Focused feature management
LaunchDarkly Proprietary SaaS The enterprise incumbent; a free Developer plan, then usage-based pricing (monthly active users and service connections, not seats)

Canary discipline for LLM features: ramp in steps (1% → 5% → 25% → 50% → 100%), hold each step long enough to see the guardrail metrics stabilise, keep a kill-switch that reverts instantly (08A.14 owns the agent-level version), and never ramp on a Friday afternoon.

4.5 Multi-armed bandits (awareness)#

A multi-armed bandit automates the explore/exploit trade-off: instead of a fixed 50/50 A/B split for a fixed duration, a bandit algorithm shifts traffic towards the currently-best variant as it learns, always reserving some exploration. Thompson sampling — sample each arm's success probability from its posterior and pick the highest — is the classic method (Thompson, 1933); Lattimore and Szepesvári's Bandit Algorithms (2020, free online) is the standard reference.

python
# bandit.py — Thompson sampling on a 3-armed bandit. Stdlib only.
#
# Three 'prompt variants' with hidden success rates; the algorithm picks
# an arm each round, observes a Bernoulli reward, and balances exploring
# (try uncertain arms) vs exploiting (use the best).

import random

def thompson_step(alpha, beta):
    """Pick the arm with the highest sampled success probability.
    Beta distributions are conjugate to Bernoulli."""
    return max(range(len(alpha)),
               key=lambda i: random.betavariate(alpha[i], beta[i]))

def run(rounds=3000, seed=1):
    random.seed(seed)
    true_rates = [0.45, 0.50, 0.60]      # hidden: variant C is best
    alpha = [1.0] * 3                   # Beta(1,1) = uniform prior
    beta = [1.0] * 3
    pulls = [0] * 3
    reward = 0.0
    for _ in range(rounds):
        arm = thompson_step(alpha, beta)
        pulls[arm] += 1
        if random.random() < true_rates[arm]:
            alpha[arm] += 1
            reward += 1
        else:
            beta[arm] += 1
    regret = rounds * max(true_rates) - reward
    return pulls, reward / rounds, regret

if __name__ == "__main__":
    pulls, avg, regret = run()
    print("pulls per variant:", pulls)
    print(f"average reward: {avg:.3f}   (best arm pays 0.60)")
    print(f"regret vs always-best: {regret:.0f} reward points over 3000 rounds")
Output · real3 lines
pulls per variant: [134, 159, 2707]
average reward: 0.581   (best arm pays 0.60)
regret vs always-best: 56 reward points over 3000 rounds

Thompson sampling spends most pulls on the best arm but keeps sampling the others — it adapts without a fixed "test then ship". When to use it: stable, high-volume, low-stakes arms where continuously shifting traffic is acceptable (e.g. which of three prompt styles to show). When not to: you need a clean causal read for a report, the effect is small relative to noise, arms have different costs or risks, or you're in a regulated context that requires a fixed experiment — a bandit's whole point is that traffic allocation is the decision, which makes it a poor fit when you must pre-commit to a winner. GrowthBook's Pro tier and similar platforms offer bandit modes; treat them as awareness, not default.

4.6 Switchback tests#

When the unit of randomisation contaminates itself — a marketplace where treated drivers affect control drivers' outcomes, a conversational product where turn N's variant shapes turn N+1's context, a pricing feature with shared inventory — the honest design is a switchback: alternate variants over time for the same units, so each unit experiences both conditions and user-mix confounders cancel.

04.10, 8.3 introduced the pattern ("same users, alternating weeks"); the rigorous version is Bojinov, Simchi-Levi and Zhao's "Design and Analysis of Switchback Experiments" (Management Science, 2023), which derives optimal designs and inference under carry-over effects — the lingering influence of a treatment after it ends. Practical rules: alternate on a schedule longer than the carry-over window, randomise which variant runs in each period rather than strictly alternating, and analyse with methods built for the design (the paper gives exact randomisation-based p-values and conservative confidence intervals) — a naive t-test that treats every period or request as independent understates variance, because neighbouring periods share users and carry-over. Switchbacks trade user-level randomisation for time-level randomisation; use them when contamination makes user-level splits invalid, not as a default.

4.7 Reading results: CIs, Simpson's paradox and LLM issues#

Analyse with confidence intervals, not p-value thresholds. Report the effect size and its interval: "treatment improved task-success by +3.2pp, 95% CI [+0.4, +6.0]". The interval tells you both significance and practical significance — a statistically significant +0.1pp may not be worth the cost.

Simpson's paradox. Aggregate results can reverse when sliced: treatment wins overall but loses in every segment, or vice versa, because the arms have different segment mixes. Always check the primary metric per pre-declared slice (plan, region, device, new-vs-returning), and be suspicious of any aggregate win that doesn't replicate in the major slices. This is the same trap 10A.8 warns about for eval slices — online, the slices are user segments.

LLM-specific experiment issues that classic A/B guidance doesn't cover:

  • Non-determinism within users. The same prompt can produce different answers on different calls (02.5, Part 7). Your "treatment effect" is measured through model noise — you need larger samples than a deterministic system would, or you average over repeated exposures.
  • Long-term and learning effects. A better answer today may teach the user a wrong mental model that hurts next week; a worse-but-clearer answer may build trust that pays off later. Short experiments measure the immediate effect only — for big changes, follow up with a longer-horizon metric.
  • Cost asymmetry. Two variants can have identical quality but 3× different token cost — cost is a guardrail metric, and the "winner" on quality may lose on unit economics. Include cost per resolved task, not just per request.
  • Judge contamination. If you measure the experiment with an LLM judge, the judge sees both variants' outputs — and may prefer the variant stylistically closer to its own training (10A.4 covers judge biases). Randomise/blind the judge where possible, and sanity-check against human review on a subsample.
  • Network effects. In multi-user or shared-corpus systems, one user's treatment can change another's control experience (a retrieval index update affects everyone). That's the switchback case above.

Two more techniques worth knowing at awareness level. Variance reduction (CUPED) shrinks confidence intervals without more traffic by adjusting each unit's in-experiment metric with their pre-experiment baseline — Deng, Xu, Kohavi and Walker's "Improving the Sensitivity of Online Controlled Experiments by Utilizing Pre-Experiment Data" (WSDM 2013) reports roughly 50% variance reduction on Bing's experiments, and most experimentation platforms offer it as a toggle. Non-inferiority and equivalence testing answer the question experiments are often really asking — "is B at least as good as A?" — by testing against a pre-declared margin δ rather than zero. The sample-size logic has the same shape, but the hypothesis is different: you're trying to rule out a meaningful loss, not detect a gain. Reach for it when the new variant is cheaper, faster or simpler rather than better — which describes most LLM prompt and model changes.

4.8 Verify the plumbing: sample-ratio mismatch and A/A tests#

Before you read any result — including the ones in 4.7 — verify that the experiment's plumbing actually did what you designed. Two canonical checks, both from the same experimentation literature as the rest of this part:

Sample-ratio mismatch (SRM). Your design says 50/50; the assignment log should say 50/50. A sample-ratio mismatch is what you call it when the observed counts per arm don't match the intended split — tested with a chi-square goodness-of-fit check on the arm counts. In plain English: compute what each arm should have received, compare with what it did receive, and ask whether the gap is bigger than chance would produce. A p-value below ~0.001 is the common alarm threshold (a rule of thumb, not a law — with enough traffic, trivially small imbalances become "significant", so judge the size of the mismatch alongside the p-value). SRM means something is broken before the metrics even start: a hashing bug in assign_variant, bot or internal traffic hitting only one arm, a mid-experiment config change, or a logging fault. Every downstream number is suspect until you find it — this is the first check a trustworthy experiment runs, and experimentation platforms typically run it automatically.

python
# srm_check.py — sample-ratio-mismatch check for a two-arm experiment.
# Stdlib only. Chi-square goodness-of-fit on the arm counts; for one
# degree of freedom, chi2 = z^2, so the two-sided p-value is
# erfc(sqrt(chi2/2)).

import math

def chi2_srm(control, treatment, expected_share=0.5):
    """Chi-square statistic and approximate p-value for observed arm
    counts vs the intended split."""
    total = control + treatment
    ec = total * expected_share
    et = total * (1 - expected_share)
    chi2 = (control - ec) ** 2 / ec + (treatment - et) ** 2 / et
    p = math.erfc(math.sqrt(chi2 / 2))
    return chi2, p

if __name__ == "__main__":
    print("SRM check: observed arm counts vs a 50/50 split")
    print("(p < 0.001 is the common rule-of-thumb alarm)\n")
    for control, treatment in [(5050, 4950), (5200, 4800), (5003, 4997)]:
        chi2, p = chi2_srm(control, treatment)
        flag = "   <-- investigate!" if p < 0.001 else ""
        print(f"control={control}  treatment={treatment}  "
              f"chi2={chi2:.3f}  p={p:.4f}{flag}")
Output · real6 lines
SRM check: observed arm counts vs a 50/50 split
(p < 0.001 is the common rule-of-thumb alarm)

control=5050  treatment=4950  chi2=1.000  p=0.3173
control=5200  treatment=4800  chi2=16.000  p=0.0001   <-- investigate!
control=5003  treatment=4997  chi2=0.004  p=0.9522

Read it as: a 50/50 split on 10,000 users is unremarkable; a 52/48 split is a broken pipe, not a finding — stop the experiment and find the cause before analysing a single metric. For splits other than 50/50, pass expected_share; for more than two arms the same idea extends to a chi-square over all arms (the p-value then needs the chi-square distribution proper, which the platforms compute for you).

A/A tests. The second plumbing check runs the same variant in both arms — there is no real difference to find, so any "significant" result is a false positive by construction. An A/A run validates the whole pipeline end-to-end (assignment, logging, metric computation, analysis) and quantifies your inherent variance: how big a difference noise alone produces at your traffic level. It also calibrates the peeking problem from 4.1 — watch how often an A/A "reaches significance" if you peek daily, and you'll see the inflation Johari et al. describe. Run an A/A when you change the assignment mechanism, the metric pipeline, or the traffic source; many teams run a small permanent A/A slice (e.g. 1% of traffic) as a continuous canary for the experiment infrastructure itself.


Part 5: Drift detection#

Deep-dive

Drift is any change in the world your system operates in that makes yesterday's measurements stop predicting today's behaviour. For LLM systems drift is everywhere and often silent — a provider swaps a model version overnight, a marketing campaign shifts the query mix, your own prompt deploy changes the output style. Detecting drift is how you know when to re-baseline, re-evaluate and re-validate.

5.1 The drift taxonomy#

flowchart LR
    subgraph inputs ["Inputs drift"]
        I1["Topics / intents"]
        I2["Languages"]
        I3["Length / format"]
        I4["Adversarial share"]
    end
    subgraph system ["System drifts"]
        M1["Provider silent model update"]
        M2["Prompt / index / config change"]
        M3["Judge prompt or model change"]
        M4["Retrieval corpus change"]
    end
    inputs --> DET["Distribution checks<br/>PSI / KL / JS on<br/>binned features"]
    system --> DET
    DET --> ACT{"Drift?"}
    ACT -->|"yes"| R["Re-baseline, re-label,<br/>re-run offline eval,<br/>page owner"]
    ACT -->|"no"| KEEP["Keep monitoring"]
Drift type What changes How you see it First response
Input drift The queries/users themselves: topics, languages, length, format, adversarial share Feature-distribution checks on logged inputs (query length, language ID, topic classifier, injection-attempt rate) Re-stratify the eval set; check per-slice metrics; the eval set may no longer represent reality
Output drift Answer style, length, refusal rate, format compliance — even with the same inputs Assertion-monitor rates, judge score distributions, output-length histograms Check for silent provider updates or your own deploy; diff a sample of outputs
Model-version drift The provider swaps the model behind an alias, or a silent update changes behaviour Pin model snapshots where possible (02.9, 8.3); track provider changelogs; run canary probes after any announced update Re-run the offline suite on the new version before trusting comparisons; expect score shifts that aren't regressions
Corpus / index drift Documents added/changed/deleted; re-chunking; index rebuilds Retrieval metrics on a fixed query set (06.10); freshness metrics; zero-result rate Re-validate eval labels that depend on corpus contents (06.10, 2.7); check ACL/permission cases still hold
Judge drift Judge prompt edited, judge model updated, judge provider changed Judge version in every score record; periodic κ re-measurement against the human label set (10A.5) All historical judge-score comparisons become suspect — re-baseline and re-calibrate before comparing across the boundary

5.2 Measuring drift: PSI, KL and JS divergence#

The workhorse statistic for "did this distribution change?" is the Population Stability Index (PSI): bin the metric into buckets, compute the share of observations in each bucket for the baseline period and the current period, then sum (actual − expected) × ln(actual / expected) across buckets. PSI is symmetric, bounded below by 0, and interpretable on a fixed scale.

Two siblings worth knowing:

  • KL divergence KL(p‖q) measures how much q surprises you if p is the truth — but it's asymmetric (KL(p‖q) ≠ KL(q‖p)) and infinite when q gives zero probability where p doesn't. Always state the direction.
  • Jensen-Shannon divergence symmetrises KL by averaging both directions against their mean — bounded in [0, ln 2], never infinite, gentler with small samples. Prefer it when you want a single symmetric number.
python
# drift_stats.py — PSI, KL and Jensen-Shannon divergence on distributions.
# Stdlib only. Compare "what we served this week" vs "the 4-week baseline".

import math

def normalize(counts):
    total = sum(counts.values())
    return {k: v / total for k, v in counts.items()}

def psi(expected, actual, eps=1e-4):
    """Population Stability Index. Rule of thumb: <0.1 stable,
    0.1-0.25 investigate, >0.25 act. Not a law — see below."""
    keys = set(expected) | set(actual)
    total = 0.0
    for k in keys:
        ea = max(expected.get(k, 0.0), eps)
        aa = max(actual.get(k, 0.0), eps)
        total += (aa - ea) * math.log(aa / ea)
    return total

def kl_divergence(p, q, eps=1e-12):
    """KL(p || q): how much q surprises you if p is the truth."""
    keys = set(p) | set(q)
    total = 0.0
    for k in keys:
        pk = max(p.get(k, 0.0), eps)
        qk = max(q.get(k, 0.0), eps)
        total += pk * math.log(pk / qk)
    return total

def js_divergence(p, q):
    """Jensen-Shannon: symmetric, bounded [0, ln 2]."""
    keys = set(p) | set(q)
    m = {k: (p.get(k, 0.0) + q.get(k, 0.0)) / 2 for k in keys}
    return 0.5 * kl_divergence(p, m) + 0.5 * kl_divergence(q, m)

if __name__ == "__main__":
    baseline   = {"billing": 40, "howto": 30, "bug": 20, "account": 10}
    this_week  = {"billing": 38, "howto": 29, "bug": 22, "account": 11}
    spike_week = {"billing": 62, "howto": 18, "bug": 12, "account": 8}

    for name, counts in [("this week", this_week), ("spike week", spike_week)]:
        p = normalize(baseline)
        q = normalize(counts)
        print(f"\n{name} vs baseline")
        print(f"  PSI : {psi(p, q):.3f}   (rule of thumb: <0.1 stable, "
              f"0.1-0.25 investigate, >0.25 act)")
        print(f"  KL  : {kl_divergence(p, q):.3f}   (baseline || this week)")
        print(f"  JS  : {js_divergence(p, q):.3f}   (symmetric, max {math.log(2):.3f})")
Output · real9 lines
this week vs baseline
  PSI : 0.004   (rule of thumb: <0.1 stable, 0.1-0.25 investigate, >0.25 act)
  KL  : 0.002   (baseline || this week)
  JS  : 0.001   (symmetric, max 0.693)

spike week vs baseline
  PSI : 0.203   (rule of thumb: <0.1 stable, 0.1-0.25 investigate, >0.25 act)
  KL  : 0.102   (baseline || this week)
  JS  : 0.025   (symmetric, max 0.693)

How to read it: "this week" is essentially the baseline (PSI 0.004 — noise); "spike week" shifted enough to land in the investigate band (PSI 0.203). Note the three statistics disagree in magnitude — PSI is the most sensitive to bucket-level shifts, JS the most conservative. Use PSI for alerting on binned distributions, JS when you want a symmetric bounded number, and always pair the statistic with a human look at which buckets moved — a PSI of 0.2 caused by a benign topic mix change is very different from one caused by a model update.

What to drift-check, concretely:

  • Inputs: query length distribution, language mix, topic/intent classifier shares, injection-attempt rate, new-vs-returning user mix.
  • Outputs: answer-length distribution, refusal/abstention rate, format-validity rate, citation rate, judge score histogram.
  • System: latency percentiles, tokens per request, cost per request, error rate.
  • Judge: score distribution per judge version — a judge change shows up as a step change in the score histogram on the change date.

5.3 Embedding-based drift detection (awareness)#

For semantic drift — "are today's queries about different things than last month's?" — you can embed a sample of inputs and measure how the embedding distribution moved (e.g. mean embedding distance, or clustering drift). This catches topic drift that category histograms miss. It's awareness-level here: the machinery (embed → compare distributions) is the same pattern as above, and the pitfalls are real — embedding models themselves drift when providers update them, so pin the embedder version or your drift detector drifts too. 06.1 owns embedding APIs; 02.3 covers embedding drift as a concept.

5.4 What to do when drift fires#

Drift is a signal, not a verdict. The response ladder:

  1. Identify which drift type fired (input? output? model? corpus? judge?) — the taxonomy in 5.1 tells you where to look first.
  2. Check for a known cause: did we deploy a prompt/model/index change? Did the provider announce an update? Did a campaign launch? Most drift has an explanation; find it before treating it as an anomaly.
  3. Decide whether it matters: benign input drift (more billing questions after a price change) may need no action beyond re-stratifying metrics; output or model drift that degrades quality needs the offline eval re-run.
  4. Re-baseline deliberately: update the comparison window and record that you did — otherwise next week's drift check compares against a stale baseline and the signal is lost.
  5. Feed it back: a drift that reveals a coverage gap becomes new eval-set cases (Part 6); a drift that reveals a judge problem triggers re-calibration (10A.5).

Part 6: Closing the loop#

Online evaluation is worthless if its findings don't change the system. This part is the operational half: how production signal becomes labelled data, how that data becomes fixes, and the rules for doing it legally and safely.

6.1 From signal to labelled case#

The pipeline every online signal should feed:

  1. Detect: an alert, a drift alarm, a review-queue item, a user report, an experiment result.
  2. Triage: a human (or a cheap classifier) decides is this a real failure, and of what type? — the failure taxonomy from 10A.1 and 07.10 gives you the categories.
  3. Label: attach the ground truth — what the correct answer should have been, which rubric criteria failed, which slice it belongs to. This is the expensive step; do it once per confirmed failure, not per trace.
  4. Add to the eval set: a versioned, deduplicated case in the dataset (10A.2 owns the hygiene: provenance, splits, licences).
  5. Reproduce offline: run the offline suite — does the case fail there too? If it passes offline but failed online, you found an offline/online gap (1.3) — record it.
  6. Fix and verify: the fix must turn the new case green without regressing the rest of the suite (10A.8 owns the gate).

6.2 Prioritising fixes by frequency × severity#

You can't fix everything. Rank candidate fixes by frequency × severity:

  • Frequency: how often does this failure occur in production traffic? (The sampled judge scores and assertion monitors give you the rate.)
  • Severity: what's the cost when it happens? Wrong medical-style advice ≫ slightly verbose answer ≫ awkward phrasing.

A failure that is rare but catastrophic (PII leak, dangerous advice, data corruption) outranks a common-but-mild one — severity has a veto, like the guardrails in 4.1. The product of the two gives a defensible priority order for the engineering queue, and it's the same math 10A.1 uses for error-cost weighting — applied to live traffic instead of the dataset.

6.3 Retraining judges, updating prompts, versioned releases#

The loop closes on changes, and each change type has its own discipline:

  • Retraining/re-calibrating judges: when judge drift fires (5.1) or κ degrades (10A.5), the fix is a new judge version — re-calibrate against the human label set, bump judge_version, and re-baseline all score comparisons across the boundary.
  • Updating prompts: prompt changes go through the same loop as any release — offline eval → canary → A/B if it matters → ramp (04.10 owns prompt versioning; 10A.8 owns the CI gate).
  • Versioned releases: every change — prompt, model, index, judge, threshold — is a versioned artefact with a changelog, so "what changed on March 3rd?" has an answer. 02.9, Part 8 covers provider model versioning; Module 11C owns the deployment machinery that ships it.

6.4 Privacy and compliance of production data#

Using production traces for evaluation means handling real user data — the most sensitive data in the system. The rules:

  • Consent and purpose: your privacy policy / terms must cover using interactions to improve the service. Using data for eval is a secondary use — check it is covered, and get legal review for regulated contexts.
  • Minimisation: store and judge the minimum needed — the query and answer, not the user's identity, not unrelated session data. Hash user IDs for correlation (03.10 owns the redaction conventions).
  • Redaction before judgement: PII-scrub traces before they reach a judge model or a human reviewer — the judge is a third-party API call, and a human reviewer is a person. 02.9, Part 9 covers provider data policies (retention, training use, ZDR); Module 12 owns PII handling properly.
  • Retention: eval datasets built from production data need a retention policy — how long cases live, when they're deleted, and what happens on user deletion requests (a deleted user's cases must be removable).
  • Access control: who can see raw traces vs labelled cases vs aggregate metrics? Reviewers see redacted traces; datasets may be shareable internally; raw production logs are the most restricted tier.
  • Regional rules: GDPR and sector rules (health, finance) constrain cross-border processing and secondary use — the same rules that governed the original request govern its reuse for eval. Check 02.9, 9.6 and involve your legal/compliance team; this is not legal advice.

6.5 Evaluating safety online: a preview#

Safety signals are online signals too: policy-violation rate, jailbreak-attempt detections, PII-leakage flags, user abuse reports, refusal-inappropriateness. Measure them as rates over traffic (assertion monitors and classifiers), alert on spikes, and feed confirmed cases into the safety eval set. The defences — injection protection, guardrails, moderation — are Module 12's subject; this lesson only teaches that safety is measured online with the same signal→triage→dataset loop as quality. A safety metric is always a guardrail (veto), never a thing to trade off against quality.

6.6 The observability hand-off#

Everything above assumes you can store traces, attach scores and query them later. That storage and UI is the observability platform's job — Module 11A owns it in depth. What this lesson needs from it, verified as of November 2026:

  • Langfuse: scores API (GET /api/public/v3/scores, five score types keyed by dataType), annotation queues, explicit-vs-implicit user-feedback model, LLM-as-judge on live traces with sampling.
  • LangSmith: online evaluators (filters + sampling rates on runs/threads), annotation queues (single-run and pairwise), feedback tags, trace retention tiers.
  • Arize Phoenix: annotations with annotator_kind (HUMAN/LLM/CODE, plus DECISION and AGENT in the current source), evals library for client- and server-side evaluation, span-level annotations.
  • Braintrust: datasets, experiments and production logging with scoring — verify current features on its docs.

The pattern to take away: your evalkit sampler produces scores; the platform stores them, shows them, and queues human review. Keep your datasets and results in open formats (JSONL) so you're never locked in — 10A.10 covers build-vs-buy.


Part 7: The minimal online-eval sampler#

This is the running project's online half: a pure-stdlib sampler that draws a representative slice of production traces, scores them through an injectable judge, and reports the score distribution plus drift vs a baseline. Every model call goes through the TraceJudge protocol — an injectable judge callable in the spirit of 10A.4's call_model seam and 10A.6's Judge protocol, here taking a Trace and returning a TraceVerdict — so the whole thing runs with FakeJudge and no keys. (The names are deliberately Trace-prefixed: evalkit.scorers.Verdict from 10A.3 and evalkit.rag_eval.Judge from 10A.6 already exist with different shapes, and the consolidated package in 10A.10 imports them all.)

python
# online.py — a minimal online-evaluation sampler for evalkit.
# Pure standard library. Every model call goes through the injectable
# `judge` callable, so the whole pipeline runs with FakeJudge and no keys.

from __future__ import annotations

import json
import math
import random
import statistics
from collections import Counter, defaultdict
from dataclasses import dataclass, field
from typing import Callable, Iterable, Protocol


@dataclass(frozen=True)
class Trace:
    """One production interaction, reduced to what evaluation needs."""
    trace_id: str
    user_id: str
    query: str
    answer: str
    route: str = "default"
    prompt_version: str = "v1"
    retrieved: tuple[str, ...] = ()
    feedback: str | None = None
    metadata: dict = field(default_factory=dict)


@dataclass(frozen=True)
class TraceVerdict:
    """What a trace judge returns for one trace. (Named TraceVerdict so it
    doesn't collide with evalkit.scorers.Verdict from lesson 10A.3.)"""
    score: float
    label: str = ""
    reason: str = ""
    judge_version: str = "unknown"


class TraceJudge(Protocol):
    """The seam every model call goes through."""
    def __call__(self, trace: Trace) -> TraceVerdict: ...


def sample_uniform(traces, n, seed=0):
    rng = random.Random(seed)
    return rng.sample(traces, min(n, len(traces)))


def sample_stratified(traces, strata_of, fractions, seed=0):
    """Sample a fixed fraction of EACH stratum (route, language...)."""
    rng = random.Random(seed)
    by_stratum = defaultdict(list)
    for t in traces:
        by_stratum[strata_of(t)].append(t)
    picked = []
    for name, group in sorted(by_stratum.items()):
        frac = fractions.get(name, fractions.get("*", 0.0))
        k = max(1, round(len(group) * frac)) if frac > 0 else 0
        picked.extend(rng.sample(group, min(k, len(group))))
    return picked


def run_sample(traces, judge):
    """Score every trace; one judge failure shouldn't kill the batch."""
    out = []
    for t in traces:
        try:
            out.append((t, judge(t)))
        except Exception as exc:
            out.append((t, TraceVerdict(score=float("nan"),
                                         reason=f"judge error: {exc}")))
    return out


def summarize(results):
    scores = [v.score for _, v in results if v.score == v.score]
    errors = len(results) - len(scores)
    return {
        "n_traces": len(results),
        "n_judged": len(scores),
        "n_judge_errors": errors,
        "mean_score": round(statistics.mean(scores), 3) if scores else None,
        "median_score": round(statistics.median(scores), 3) if scores else None,
        "pass_rate": round(sum(1 for s in scores if s >= 0.5) / len(scores), 3)
                     if scores else None,
        "label_counts": dict(Counter(v.label for _, v in results)),
        "judge_versions": dict(Counter(v.judge_version for _, v in results)),
    }


def distribution_drift(current, baseline, buckets=5):
    """PSI between two score lists (see drift_stats.py for the full version).
    Scores are expected in [0, 1]; out-of-range values clamp into the edge
    buckets rather than erroring or wrapping around."""
    def hist(xs):
        counts = [0] * buckets
        for x in xs:
            counts[max(0, min(int(x * buckets), buckets - 1))] += 1
        total = max(len(xs), 1)
        return [max(c / total, 1e-4) for c in counts]
    a, b = hist(current), hist(baseline)
    return sum((x - y) * math.log(x / y) for x, y in zip(a, b))


class FakeJudge:
    """Deterministic stand-in: scores by canned rules on the trace text.
    Real code passes a judge built on a provider call; same interface."""
    def __init__(self, fail_on=None):
        self.fail_on = fail_on or set()

    def __call__(self, trace):
        if trace.trace_id in self.fail_on:
            raise RuntimeError("simulated judge outage")
        text = (trace.query + " " + trace.answer).lower()
        if "i don't know" in text or "cannot help" in text:
            return TraceVerdict(0.2, "abstain", "looks like an abstention", "fake-v1")
        if len(trace.answer) < 40:
            return TraceVerdict(0.4, "thin", "answer suspiciously short", "fake-v1")
        if "error" in text or "traceback" in text:
            return TraceVerdict(0.1, "broken", "error text in answer", "fake-v1")
        return TraceVerdict(0.85, "ok", "looks fine", "fake-v1")


def make_fixture_traces(n=200):
    """Deterministic fake production traffic across three routes."""
    rng = random.Random(7)
    routes = ["rag", "chat", "extract"] * (n // 3 + 1)
    traces = []
    for i in range(n):
        route = routes[i % len(routes)]
        kind = rng.random()
        if kind < 0.08:
            q, a = "what is the refund policy?", "I don't know, let me check."
        elif kind < 0.15:
            q, a = "summarise this", "ok"
        elif kind < 0.20:
            q, a = "run report", "Traceback (most recent call last): ..."
        else:
            q, a = "how do I export invoices?", (
                "Go to Settings > Billing > Export, choose the date range "
                "and format (CSV or PDF), then click Export. The file is "
                " emailed when ready, usually within a minute.")
        traces.append(Trace(
            trace_id=f"tr-{i:04d}", user_id=f"u-{rng.randrange(40):03d}",
            query=q, answer=a, route=route,
            prompt_version="v2" if i % 3 == 0 else "v1"))
    return traces


def main():
    traces = make_fixture_traces()
    print(f"production traces today: {len(traces)}")

    sample = sample_stratified(traces, strata_of=lambda t: t.route,
                               fractions={"*": 0.10}, seed=11)
    print(f"sampled for judging:    {len(sample)} "
          f"({dict(Counter(t.route for t in sample))})")

    results = run_sample(sample, FakeJudge(fail_on={"tr-0015"}))

    print("\n== summary ==")
    for k, v in summarize(results).items():
        print(f"  {k}: {v}")

    baseline = [0.85] * 80 + [0.4] * 20   # yesterday's judged scores
    current = [v.score for _, v in results if v.score == v.score]
    psi = distribution_drift(current, baseline)
    print(f"\nscore-distribution PSI vs baseline: {psi:.3f}")
    verdict = "stable" if psi < 0.1 else "investigate" if psi < 0.25 else "act now"
    print(f"rule of thumb: {verdict}")


if __name__ == "__main__":
    main()
Output · real — pure stdlib, no keys15 lines
production traces today: 200
sampled for judging:    21 ({'chat': 7, 'extract': 7, 'rag': 7})

== summary ==
  n_traces: 21
  n_judged: 20
  n_judge_errors: 1
  mean_score: 0.805
  median_score: 0.85
  pass_rate: 0.9
  label_counts: {'ok': 18, 'thin': 2, '': 1}
  judge_versions: {'fake-v1': 20, 'unknown': 1}

score-distribution PSI vs baseline: 0.081
rule of thumb: stable

What the output teaches: 21 traces sampled stratified across three routes (7 each — uniform sampling might have missed a small route); one judge failure recorded as n_judge_errors: 1 rather than crashing the batch; the score distribution feeds distribution_drift, which compares today's histogram against yesterday's stored baseline — PSI 0.081 lands in the "stable" band.

Swapping in a real judge is a one-function change: implement __call__(self, trace) -> TraceVerdict on top of any provider SDK (03.1 for the clients, 10A.4 for the judge prompt and output schema), keep judge_version honest, and the sampler, stratification, reporting and drift check all work unchanged. For the free path, the same code runs against the local stand-in from 03.1, Part 12.


Which signal when: the decision table#

Situation Reach for Why
"Does version B beat A on our cases?" Offline eval (10A.8) Controlled, repeatable, cheap per run
"Is production quality drifting?" Assertion monitors + score-distribution PSI (3.3, 5.2) Continuous, every trace or a sample, no labels needed
"Are users happier this week?" Explicit + implicit signals, propensity-aware (Part 2) Real users, but biased — treat as directional
"Did this prompt change cause the improvement?" A/B test (4.1) Only randomisation gives causality
"Are the arm counts even what we designed?" SRM check + periodic A/A (4.8) Broken plumbing invalidates every downstream number
"Which of two retrievers is better on live queries?" Interleaving (4.2) Same user, same query, click credit — far more sensitive than A/B for ranking
"Is the new index safe to ship?" Shadow mode → canary → A/B (4.3, 4.4) Real traffic, staged risk
"Should we keep exploring or ship the winner?" Bandit if high-volume/low-stakes; fixed A/B otherwise (4.5) Bandits adapt; A/B gives a clean causal read
"Units contaminate each other (shared state, carry-over)?" Switchback (4.6) Time-level randomisation controls for contamination
"Inputs look different this month" Input-drift checks (5.2) PSI/KL/JS on binned features before trusting comparisons
"Judge scores incomparable across a judge change" Re-calibrate + re-baseline (10A.5, 5.1) Judge version is part of the metric's definition
"A failure users hit that evals never saw" Triage → label → eval-set case → offline regression (6.1) The loop that keeps offline honest
"Can we use production traces for evals?" Yes, with consent/minimisation/redaction/retention/access rules (6.4) Production data is the most sensitive data you hold

The ways online evaluation goes wrong — anti-patterns that produce confident, wrong conclusions:

Failure What you see Root cause Fix
Optimising thumbs-up rate Team celebrates a rising positive rate while escalations double Thumbs are self-selected and biased; the silent majority disagrees Track behavioural signals (escalation, abandonment, task completion) alongside feedback; weight by propensity (2.5)
A/B on too few users "Treatment wins!" on 200 users per arm for a 2pp effect Sample size never computed; noise read as signal Compute n per arm before launch (4.1); pre-register the end
Ignoring a sample-ratio mismatch "Significant" result announced, then audit finds a 52/48 split Assignment counts never checked against the intended split Run the chi-square SRM check before reading any metric; find the broken pipe first (4.8)
Peeking at the dashboard Experiment "goes significant" on day 2, then evaporates Continuous monitoring inflates false positives well above the nominal 5% Pre-registered end date; always-valid inference or sequential correction (Johari et al., KDD 2017)
Judging only easy traffic Online judge score is great; users still complain Sampling uniform but review prioritising nothing; rare hard cases invisible Stratified + uncertainty sampling for review queues; over-sample risky slices for discovery but report population scores separately (3.1, 3.2)
Ignoring drift Month-over-month score comparisons meaningless Input/model/judge drift unmeasured; baselines stale Drift-check distributions weekly; re-baseline deliberately and record it (Part 5)
Using production data without consent Eval dataset built from traces users didn't agree to reuse Secondary-use rules ignored; PII sent to judges unredacted Consent/minimisation/redaction/retention/access-control checklist (6.4)
Shadow mode as the only check Candidate "looks fine" in shadow; users hate it Shadow measures behaviour, not preference — no user signal on a discarded answer Shadow for risk screening; A/B for the causal read (4.3)
Bandit for everything Traffic keeps shifting; nobody can say what won Bandit optimises reward, not knowledge; no clean experiment record Fixed-horizon A/B when you need a reportable causal conclusion (4.5)
Judge drift mistaken for quality drift Scores drop after a judge model update; team panics Judge version not recorded; comparison across an uncontrolled boundary judge_version on every score; re-calibrate before comparing (5.1)
Canary as the whole eval Green canary, red users Canary measures 30 known cases, not the long tail Canary is a tripwire; the sampled judge + review queue cover the population (3.4)

What this means for you#

Offline evals prove "B beats A on these cases"; online evals measure "what actually happened" — and the loop between them is the product, not a nice-to-have. Every online signal should terminate somewhere concrete: an alert, a dashboard or a new dataset case. Online experiments need pre-registered design and plumbing checks (SRM, AA) before their numbers mean anything, and the production data feeding all of it is the most sensitive data you hold — consent, redaction and retention come before convenience.


Common misconceptions#

Misconception Reality
"A green offline suite means production is fine." Offline covers the cases you imagined. Online signals cover the ones users actually hit — keep both loops running (1.1).
"Thumbs-up rate is our satisfaction metric." It's a biased sample of self-selected responders — directional at best (2.5). Pair it with behavioural signals and experiments.
"We can judge every production trace." At scale you can't afford to, and you don't need to — uniform sampling gives an unbiased estimate; stratified/uncertainty sampling finds failures faster (3.1).
"An A/B test needs equal groups and a fixed duration." It needs the right unit, enough sample size for the effect you care about, and a pre-registered end — duration follows the traffic, not the calendar (4.1).
"Checking the results daily is just good monitoring." Peeking inflates false positives well beyond the nominal 5%; pre-register and analyse once, or use always-valid inference (Johari et al., KDD 2017).
"Interleaving is the same as the hybrid-search interleave." Different things: experimentation interleaving merges two systems' outputs to credit clicks; hybrid-search interleaving round-robins ranked lists (4.2, 06.8).
"Shadow mode tells us if users prefer the new system." It tells us how the candidate behaves on real traffic — there's no user signal on a discarded answer. Use A/B for preference (4.3).
"A multi-armed bandit is just a smarter A/B test." It optimises reward, not knowledge — traffic allocation is the decision, so it's wrong when you need a clean causal read or a reportable winner (4.5).
"PSI above 0.25 always means act now." The thresholds are a credit-risk rule of thumb; calibrate on your own history and pair the statistic with a look at which buckets moved (5.2).
"Drift always means something broke." Most drift has a benign cause (campaign, seasonality, provider update). Identify the type, find the cause, then decide (5.4).
"Production traces are free eval data." They're the most sensitive data you hold — consent, minimisation, redaction, retention and access rules apply before they become cases (6.4).
"The judge score is ground truth." The judge is a measurement instrument with error and drift — calibrate it against humans and version it (10A.5, 5.1).

Key takeaways#

  • Two worlds, one loop. Offline evals prove "on these cases, B beats A"; online evals measure "on real traffic, what happened". The loop — production failures → dataset → offline gate → release → production — is the product.
  • Metric alignment is checkable: correlate offline scores with online metrics across released versions (Spearman ρ); per-metric, not global.
  • Online signals are biased proxies: explicit feedback is high-precision/low-recall and self-selected; implicit signals are ambiguous; business metrics are the north-star; system metrics are guardrails; safety metrics are vetoes.
  • Quality without labels comes from six mechanisms: sampled judge scoring, human review queues, assertion monitors, canary probes, user simulators and anomaly detection — each terminating in an alert, a dashboard or the dataset.
  • Experiments need honest design: the right randomisation unit, pre-computed sample size for the smallest decision-changing effect, guardrail vetoes, one primary metric, a pre-registered end (no peeking), LLM-specific care for non-determinism, cost asymmetry and judge contamination — and plumbing checks (SRM, A/A) before any result is trusted.
  • The design spectrum: offline eval → shadow → canary → A/B → (bandit for high-volume/low-stakes) → switchback for contaminated units. Interleaving for ranking comparisons.
  • Drift is measurable: PSI/KL/JS on binned distributions catch input, output, model, corpus and judge drift; re-baseline deliberately and feed coverage gaps back into the eval set.
  • Close the loop: triage → label → eval-set case → offline reproduction → fix → verify. Prioritise by frequency × severity. Version everything.
  • Production data is sensitive: consent, minimisation, redaction before judges/reviewers, retention, access control, regional rules.
  • evalkit/online.py is the minimal sampler: stratified sampling, injectable judge, score distributions, PSI drift — pure stdlib, runs with FakeJudge, no keys.

Terms introduced in this lesson#

Term One-line definition
Offline evaluation Evaluation on a curated dataset before release
Online evaluation Evaluation on live production traffic after release
Metric alignment Whether an offline score predicts the online outcome it proxies for
Explicit feedback Deliberate user signals: thumbs, ratings, comments, edits
Implicit feedback Behavioural signals: retries, abandonment, escalation, task completion
Deflection rate Share of queries resolved without a human agent
Guardrail metric A metric that vetoes a release or winning variant (latency, cost, safety) rather than something to maximise
Selection bias Distortion from only observing self-selected responders
Propensity weighting Weighting responses by 1/response-propensity to correct selection bias
Sampled judge scoring Running a calibrated LLM judge on a sample of production traces
Human review queue A prioritised list of traces for human labelling and judge calibration
Assertion monitor A deterministic online check (format, citations, refusal rate) run on traffic
Canary probe A scheduled known-query smoke test against production
User-simulator probe An LLM playing a persona to test multi-turn behaviour on a schedule
Anomaly detection Alerting on deviations from a learned normal range of a metric
A/B test A randomised online controlled experiment comparing variants
Randomisation unit The entity assigned to a variant (user, session, request, time)
Sample size / power Users needed per arm to detect a given effect at a given confidence
Minimum detectable effect (MDE) The smallest effect worth designing the experiment to detect
Peeking problem Inflated false positives from monitoring an experiment continuously
Always-valid inference Sequential-analysis methods (mSPRT) robust to continuous monitoring
Sample-ratio mismatch (SRM) Observed arm counts not matching the intended split — a broken-pipe check before reading results
A/A test An experiment with the same variant in both arms, used to validate the pipeline and measure inherent variance
Interleaving (experimentation) Merging two systems' outputs to credit clicks — for ranking eval, not hybrid search
Shadow mode Running the candidate on live traffic but serving production's answer
Canary rollout Releasing a change to a small traffic slice while watching guardrails
Feature flag A runtime switch routing traffic to variants without redeploying
Multi-armed bandit An algorithm balancing exploration vs exploitation across variants
Thompson sampling A bandit method sampling each arm's success probability from its posterior
Switchback test Alternating variants over time for the same units to control carry-over
Carry-over effect A treatment's lingering influence after it ends
Simpson's paradox An aggregate trend reversing when the data is sliced
Drift Any change making past measurements stop predicting present behaviour
Input drift Change in the queries/users themselves
Output drift Change in answer style/format/refusal even on same inputs
Model-version drift Silent provider model updates changing behaviour
Corpus/index drift Changes in the retrieval corpus or index
Judge drift Judge prompt/model changes altering score meanings
Population Stability Index (PSI) A statistic comparing two distributions' bucket shares
KL divergence Asymmetric measure of how one distribution surprises another
Jensen-Shannon divergence Symmetric, bounded divergence between two distributions
Failure triage queue The queue of suspected production failures awaiting labelling
Frequency × severity The prioritisation rule for fixes: how often × how bad
North-star / guardrail / diagnostic (online) The metric hierarchy applied to live signals

All terms are also collected in the glossary.


Exercises#

Run the code from this lesson and experiment:

  1. Sampler (Part 7): change fractions={"*": 0.10} to {"rag": 0.5, "*": 0.02}. How does the per-route sample change, and why does stratified sampling guarantee the rag route is well-covered even at low overall rates?
  2. Judge errors (Part 7): add a second trace_id to fail_on and re-run. What happens to pass_rate and mean_score — and why is recording the error better than crashing?
  3. Drift (5.2): in drift_stats.py, make spike_week even more extreme ("billing": 80). At what PSI does the rule-of-thumb say "act now", and does JS divergence move as fast?
  4. Sample size (4.1): use ab_sample_size.py to find the users-per-arm needed to detect a +1pp lift on a 50% baseline vs a +5pp lift on a 10% baseline. Which is cheaper, and why does the baseline rate matter?
  5. Feedback bias (2.5): change sat_propensity to 0.10 in feedback_bias.py (responders more representative). How much does the naive-vs-corrected gap shrink?
  6. Bandit (4.5): change true_rates to [0.55, 0.50, 0.52] — arms much closer together. Does Thompson sampling still concentrate pulls on the best arm? What does that tell you about bandits on small effects?
  7. Alignment (1.3): in alignment.py, change online to [0.30, 0.28, 0.33, 0.31, 0.35, 0.32, 0.36, 0.34, 0.37, 0.35] — online decreasing as offline rises. What does Spearman ρ say, and what would you do?
  8. Experiment design: your support chatbot has ~500 daily active users and a 40% resolution rate. You want to detect a +5pp resolution lift. Using ab_sample_size.py, how many days until you have enough users per arm? Is an A/B test even feasible, or do you need a different design?
  9. Plumbing (4.8): run chi2_srm(5120, 4880) from srm_check.py — does it alarm? Now try (10200, 9800) on 20,000 users and (51000, 49000) on 100,000. What does the pattern tell you about why the size of a mismatch matters as much as its p-value? Then design an A/A test for a system you know: what would you measure, and what result would tell you the experiment pipeline is healthy?

Check yourself#

  1. What can offline evaluation not tell you that online evaluation can?
  2. What are the five families of online signals, and which is a veto rather than a metric to maximise?
  3. Why is the raw thumbs-up rate a biased estimate of satisfaction?
  4. Name the six mechanisms for evaluating quality online without labels.
  5. What is the randomisation unit in an A/B test, and why does it matter?
  6. Roughly how many users per arm do you need to detect a +2pp lift on a 30% baseline at 80% power?
  7. What is the peeking problem, and what's the practical fix?
  8. When is interleaving better than A/B, and when can't you use it?
  9. What does shadow mode measure — and what can't it measure?
  10. What's the difference between PSI, KL and Jensen-Shannon divergence?
  11. Name the five drift types and one metric that detects each.
  12. What does PSI = 0.203 mean under the common rule of thumb, and why is it "not a law"?
  13. Walk through the loop from a production failure to a regression test.
  14. What are the six privacy rules for using production traces in evaluation?
  15. Why is judge_version recorded on every score?

Further resources#

  • Kohavi, Tang & Xu, Trustworthy Online Controlled Experiments: A Practical Guide to A/B Testing (Cambridge University Press, 2020, DOI 10.1017/9781108653985) — the canonical A/B testing text; experiment design, guardrails, pitfalls.
  • Johari, Koomen, Pekelis & Walsh, "Peeking at A/B Tests: Why it matters, and what to do about it" (KDD 2017, DOI 10.1145/3097983.3097992) — the peeking problem and always-valid inference.
  • Chapelle, Joachims, Radlinski & Yue, "Large-scale validation and analysis of interleaved search evaluation" (ACM TOIS 30(1), 2012, DOI 10.1145/2094072.2094078) — interleaving for ranking evaluation.
  • Bojinov, Simchi-Levi & Zhao, "Design and Analysis of Switchback Experiments" (Management Science 69(7), 2023, DOI 10.1287/mnsc.2022.4583) — rigorous switchback design and inference.
  • Lattimore & Szepesvári, Bandit Algorithms (2020, banditalgs.com) — the standard bandit reference; Thompson sampling and friends.
  • Deng, Xu, Kohavi & Walker, "Improving the Sensitivity of Online Controlled Experiments by Utilizing Pre-Experiment Data" (WSDM 2013) — the CUPED variance-reduction method of 4.7.
  • Angelopoulos, Bates, Fannjiang, Jordan & Zrnic, "Prediction-powered inference" (Science 382, 2023, arXiv:2301.09633, DOI 10.1126/science.adi6000) — valid intervals from a cheap predictor (a judge) plus a few labels.
  • Siddiqi, Credit Risk Scorecards (Wiley, 2006) — the origin of the PSI 0.1/0.25 rule of thumb used in drift detection.
  • Langfuse docs: Scores API, User feedback, Scores overview — production score storage and annotation queues.
  • LangSmith docs: Online evaluations (LLM-as-judge), Annotation queues — online evaluators and human review.
  • Arize Phoenix docs: Annotations and evaluation, Capture feedback — annotator_kind model and evals.
  • OpenAI, "Moving from OpenAI Evals to Promptfoo" (cookbook) — the Evals platform deprecation and migration path (relevant to eval tooling choices; 10A.10 covers the landscape).

← 10A.8 — Regression Testing, CI and Experiment Tracking | Module 10A overview | 10A.10 — Evaluation Platforms, Benchmarks and Building an Eval Culture →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close