Give a feature that does nothing to 200 experiments. A before/after read calls nearly all 200 a win. Daily peeking calls about 44. A coin flip with one planned look calls about 10.
Pick a design, then press Run 200. Every red cell is a false winner: a feature you would ship that does nothing. Then we build, piece by piece, the coin flip, the SRM check, the sample size, the stopping rule, CUPED and the traps in marketplaces and logs.
You need a z-test and a p-value (see The Statistics of Evaluation) and a little Python. We build the rest from zero.
Illustrative world: the feature’s true effect is 0. Before/after compares 10,000 users last week with 10,000 users this week, and a holiday lifts this week by 5 points. The coin-flip designs run 14 daily looks. Over many runs, daily peeking flags about 22% and one look flags about 5% (checked with a seeded simulation of 200,000 runs).
Chapter 0
Watch a before/after comparison credit your feature with a holiday
Your team ships a "For You" panel in a music app on December 18. The next Monday, weekly retention reads 45%. Last week it read 40%. The launch email writes itself.
Then someone pulls up last year's chart. Retention jumped 5 points that same week, with no launch. People are home for the holidays. The win was the calendar.
The method that fooled you is a before/after comparison: measure the metric before the change, measure it after, and credit the change with the gap. A confounder is anything that changes at the same time as your feature and also moves the metric. Here, the holiday. Everyone who got the feature also got the holiday, so the two effects cannot be told apart.
Teal is control, purple is treatment, the warm band is the holiday week. Set the feature’s true effect, then switch how you assign users.
Illustrative world: 40% base retention, 2,000 users a day, the launch on day 15, the holiday on days 15 to 21. A fixed seed draws the daily noise.
Is a 5-point gap even real? The test from eval-statistics checks two shares. Call the share that retained in treatment p̂T and in control p̂C. Call the group sizes nT and nC, and the share across both groups p̂.
z equals p-hat-T minus p-hat-C, over the square root of p-hat times one minus p-hat, times one over n-T plus one over n-C.
Subtract p-hat-C from p-hat-T. Divide by the standard error, built from the pooled share p-hat and the sizes n-T and n-C. The result z says how surprising the gap is if nothing differs.
4,000 of 10,000 retained last week and 4,500 of 10,000 this week. p̂ = 8,500/20,000 = 0.425. The standard error is √(0.425 × 0.575 × 0.0002) = 0.00699. z = 0.05/0.00699 = 7.15, so p = 8.6 × 10−13. The weeks differ. The test cannot say why.
The fix is one sentence. Split users at random at the same moment: a coin per user, half get the feature (treatment), half keep the old experience (control). The holiday lifts both arms, so it cancels when you subtract. With a true effect of 0, both arms retain about 45% and the gap is about 0.
The failure. Symptom: a big, highly significant lift right after a launch. Measure: compare the same calendar week last year, or check whether a control group existed at all. Fix: randomize at the same time; if you cannot, see the quasi-experiment table in the Field Guide.
Chapter 1
Split an observed gap into the real effect and the selection bias, then see the coin flip zero the bias
For every user who got your feature there is a ghost: the same person, the same day, without the feature. The effect on that user is the user minus the ghost. You never see the ghost.
Give each user two sealed envelopes, the potential outcomes. Y(1) is the outcome with the feature. Y(0) is the outcome without it. Here each is 1 if the user retains and 0 if not. Opening one envelope burns the other, so no single user’s effect Y(1) − Y(0) is ever observed.
The average treatment effect (ATE) is the average of Y(1) − Y(0) over everyone. Different users can stand in for each other’s ghosts, if the groups are alike.
Grey is Y(0), purple is Y(1). God view shows both. Self-selection lets engaged users take the feature. The coin flip assigns at random; flip it many times and watch the running average.
Illustrative table: Y(0) = 1, 1, 0, 0, 1, 0 and Y(1) = 1, 1, 1, 0, 1, 1 for users 1 to 6. A coin flip with all users in one arm is redrawn.
Where does a gap come from? Call the gap you observe, treated average minus control average, D. Call the average effect on the users who took the feature the effect on the treated, ATT. Call the difference between the two groups’ ghosts, their Y(0) averages, the selection bias B.
D equals A-T-T plus B.
Add and subtract the treated users’ ghosts inside D. One piece is the real effect on them, ATT. The other piece, B, says how different the groups were before any feature.
Self-selection puts users 1, 2 and 5 in treatment. D = 3/3 − 0/3 = 1.0. Their own effects are 0, 0, 0, so ATT = 0. Their ghosts average 1 and the controls’ average 0, so B = 1.0. The whole gap is bias; the true ATE is 2/6 = 0.33.
A coin flip does not look at either envelope. So the treated users’ ghosts match the controls’ Y(0) in distribution. B is 0 on average and ATT equals the ATE, for traits you measured and traits you never logged.
Two limits remain: one small experiment can still be unlucky (Chapter 3), and one user’s arm must not change another user’s outcome (Chapter 6).
pythonimport numpy as np Y0 = np.array([1,1,0,0,1,0]); Y1 = np.array([1,1,1,0,1,1]) ate = (Y1 - Y0).mean() # 0.333 T, C = [0,1,4], [2,3,5] # engaged users opt in D = Y1[T].mean() - Y0[C].mean() # 1.0 att = (Y1[T] - Y0[T]).mean() # 0.0 B = Y0[T].mean() - Y0[C].mean() # 1.0, so D = att + B
The failure. Symptom: "users who turned on the assistant retain 30% better". Measure: ask who chose the feature; opt-in users differ in Y(0). Fix: randomize it among current non-users, the people a launch would reach.
Chapter 2
Choose what to flip the coin for, keep it sticky with a hash, and test that it was fair
"Flip a coin per user" hides three decisions. What is the coin for? How does a user keep one arm? Was the coin fair?
The randomization unit is what you flip the coin for: a user, a session or a request. A visible UI change needs one experience per user. A backend change nobody sees can flip per request.
The unit also changes the metric. User A converts 2 of 4 sessions, user B 1 of 1, user C 0 of 5. Per session, conversion is 3/10 = 30%. Per user, it is (0.5 + 1.0 + 0)/3 = 50%.
Analyze at the unit you randomized. One user’s sessions move together, so a per-session standard error comes out too small.
Hash assignment makes the coin sticky with no database: bucket = hash(user_id + salt) mod 100, buckets 0 to 49 are control. The same user always lands in the same bucket. A new salt per experiment reshuffles users, so experiments do not share their treatment groups.
Dots are users hashed into 100 buckets: teal is control, purple is treatment. Change the salt to reshuffle. Then raise the treatment loss: some treatment users vanish from the logs.
The device hashes 100,000 users with FNV-1a on "id:salt". The loss removes that share of treatment users after assignment, as a crashing client would. The SRM line is p < 0.001.
You planned 50/50 and saw 50,600 against 49,400. Call the observed count in each arm O and the count you planned E.
Chi-squared equals the sum over arms of O minus E, squared, over E.
For each arm, subtract E from O, square it, divide by E. Add the arms. A large chi-squared means the split is unlikely under a fair coin.
E = 50,000 per arm. χ² = 600²/50,000 + 600²/50,000 = 7.2 + 7.2 = 14.4. With 1 degree of freedom, p = 0.00015. A 1.2% imbalance on 100,000 users fails.
A sample ratio mismatch (SRM) is a split that fails this test. It comes from users lost after assignment: a crash in one arm, a bot filter, a broken redirect. The lost users differ from the rest, so they bias every metric. Microsoft’s experimentation team reports that about 6% of its A/B tests have an SRM (ExP blog, citing Fabijan et al., KDD 2019).
The failure. Symptom: the split looks "about even" and the result looks great. Measure: run the chi-squared on the counts, overall and per platform. Fix: discard the result and find the loss; do not reweight.
Chapter 3
Size the experiment before it starts, and write the effect in absolute points
The most common failed experiment is not a false positive. It is two weeks of traffic spent on an effect that needed six months to see. It returns "not significant" whatever the truth is.
Three numbers set the size. Alpha (α, usually 0.05) is the chance of calling a win when the true effect is zero. Power (usually 0.80) is the chance of calling a win when the effect is real. The minimum detectable effect (MDE) is the smallest true lift worth finding. It is a business choice, not a forecast.
Call the control rate p1, the treatment rate you want to detect p2, and the gap between them δ. Call the users needed in each arm n.
n equals z-alpha-over-two plus z-beta, squared, times p-one times one minus p-one plus p-two times one minus p-two, over delta squared.
Add z-alpha-over-two and z-beta and square the sum. Multiply by the two per-user variances. Divide by delta squared. That is n per arm.
p1 = 5%, p2 = 6%, so δ = 0.01. (1.960 + 0.842)² = 7.849. Variances 0.0475 + 0.0564 = 0.1039. n = 7.849 × 0.1039 / 0.0001 = 8,155 per arm, 16,310 in all.
Where does it come from? With no effect, the observed gap is noise with standard error SE, and you call a win past 1.96 SE. For 80% of real experiments to clear that line, the true gap must sit 0.842 SE further out. So δ = 2.802 SE; solve for n.
The left bell is the gap under no effect; the right bell is the gap under the MDE. Yellow is the significance line. Red is α, green is power. Move a slider; then switch the MDE to relative.
Two-sided α = 0.05, power 80%, 50/50 split. Days to fill is total users over daily traffic; run at least one full week anyway.
Now the trap. "A 1% lift" has two readings. One point, 5% to 6%, needs 8,155 per arm: under a day at 20,000 users a day. One relative percent, 5% to 5.05%, needs 2,996,695 per arm: 367 times more, or 300 days. Write the MDE in absolute points, then add the relative figure.
The failure. Symptom: a stream of "not significant" results on small features. Measure: compute the power you had at the effect you hoped for. Fix: accept a larger MDE, pick a more sensitive metric (metric design), or cut variance (Chapter 5).
Chapter 4
Watch a stopping rule turn a 5% false-positive rate into 25%, then fix it with a boundary
Day 3 of a two-week test, the dashboard shows p = 0.03. Ship it? Run an A/A test (both arms get the same experience) and look every day. Most of the time, p dips below 0.05 at some point.
Under no effect, z wanders like a drunk walk as data arrives. A fixed-horizon test asks one question: is |z| past 1.96 at the end? That is a 5% chance. Peeking with early stopping asks: does |z| cross 1.96 on any of 20 looks? The maximum of a walk crosses a line far more often than its end point does.
Each line is one A/A test’s z over the looks. Yellow lines are ±1.96; the yellow funnel is the O’Brien-Fleming boundary. A red line crossed 1.96 at some look. Run 500 and read the three tallies.
Each look adds an equal batch of data, so z is a scaled random walk. The boundary constants come from a seeded simulation of 300,000 walks per look count.
The exact numbers, from 20,000 seeded A/A tests with 20 daily looks and 500 users per arm per day:
Same data, same statistic, five times the error. Why not 20 × 5% = 100%? Each day reuses most of the previous day’s data, so the looks move together.
The failure. Symptom: many wins that fade after launch. Measure: count how often teams looked before the stop, or rerun past tests as A/A. Fix: show the boundary on the dashboard, not the raw p-value.
Chapter 5
Use each user’s pre-experiment behaviour to cut the variance without touching the effect
Most of the spread in sessions per user is not noise from the treatment. Heavy users stay heavy and light users stay light. That part was knowable before the experiment started.
Anything measured before randomization is independent of the coin. So an adjustment built only from pre-period data cannot shift the treatment effect. It can only soak up variance. CUPED (Controlled experiments Using Pre-Experiment Data; Deng, Xu, Kohavi and Walker, WSDM 2013) does exactly this.
Call a user’s metric during the experiment Y and the same metric in the weeks before X. Call the average X over all users X̄. Call the slope of Y on X θ.
Y-cuped equals Y minus theta times X minus X-bar, where theta is the covariance of X and Y over the variance of X.
Predict each Y from its X with slope theta. Subtract the part above or below average, theta times X minus X-bar. The average of Y stays the same; the spread shrinks.
With made-up numbers: X = 2, 4, 6, 8, 10 and Y = 3, 5, 5, 9, 10. X̄ = 6, cov = 7.2, var(X) = 8, so θ = 0.9. Ycuped = 6.6, 6.8, 5.0, 7.2, 6.4. The mean stays 6.4. The variance falls from 7.04 to 0.56.
How much does it buy? Call the correlation of X and Y ρ (rho). The variance after the adjustment is the old variance times one minus rho squared:
Sample size scales with variance. So ρ = 0.5 saves 25% of users, ρ = 0.7 saves 49%, and ρ = 0.9 saves 81%.
Left: each dot is a user, X across, Y up. Right: 200 experiments’ effect estimates, raw in grey and CUPED in blue. The green line is the true effect. Raise ρ.
Illustrative: 400 users per experiment, true effect 0.30, unit variance. A fixed seed drives the simulation; the variance ratio is the measured one.
Two practical rules. A new user has no pre-period, so set X = X̄: no adjustment, no harm. And never adjust by anything measured after randomization.
The failure. Symptom: after CUPED the effect changes sign. Measure: check when the covariate window ends. Fix: use only data from before first exposure; an in-experiment covariate carries part of the effect and subtracts it.
Chapter 6
See a shared driver pool turn a 2-point effect into 12, and randomize time instead of riders
A ride app gives half its riders a better matching algorithm. That does not create two parallel cities. It creates one city where treatment riders take cars that control riders would have got.
The A/B test assumes SUTVA, the Stable Unit Treatment Value Assumption: each user’s outcome depends only on that user’s own arm. Marketplaces, social networks and shared budgets break it. The test still runs; it answers the wrong question.
Bars show the match rate of each arm. The green dash is the true launch effect, +2 points. Raise driver scarcity in user-split mode, then switch to switchback and press Play.
Illustrative model: a 70% base match rate and 72% at full launch. The theft grows in a straight line with scarcity, to 78% against 66% at scarcity 0.7. Switchback windows add noise from a fixed seed.
The decomposition at scarcity 0.7:
The treatment gain is real improvement plus stolen supply, and the control loss is the theft again. The naive gap counts the theft twice and overstates the launch six times. With positive spillovers, such as a referral reward, the bias flips sign and the naive gap understates.
| Design | What it randomizes | What it costs |
|---|---|---|
| Switchback | time windows: the whole city is treatment 7:00 to 7:30, control the next half hour | far fewer units (336 half-hour windows a week); carryover between windows |
| Cluster | whole friend groups or regions, so most links stay inside one arm | few, lumpy units, so higher variance |
| Interleaving | items from two rankers merged into one list per query | measures click preference, not revenue or retention |
Bojinov, Simchi-Levi and Zhao analyse switchback designs in Management Science (2023). Team-draft interleaving comes from Radlinski, Kurup and Joachims (CIKM 2008).
Time also fakes effects. A novelty effect lifts clicks for a week and then fades. Change aversion does the reverse. Plot the daily effect: a curve that still slopes means the long-run effect is not measured yet.
The failure. Symptom: a big marketplace win that shrinks to a fraction at full launch. Measure: check if control users lost anything versus the pre-period. Fix: switchback or cluster randomization, analysed with one data point per window or cluster.
Chapter 7
Reweight the old policy’s logs to estimate a new policy, and read how few events carry the answer
Your new recommender beats the old one by 8% on held-out clicks. Online, it is flat. You scored it on logs that the old model wrote.
The logs show only what the old policy chose to show. A niche film the new model loves may have no logged impressions, and clicks carry the old ranker’s position bias.
Off-policy evaluation (OPE) estimates a new policy’s online value from old logs. It needs a logging policy that was random, with each shown item’s probability recorded: its propensity. A logger that always shows its top pick makes OPE impossible.
Call the number of logged events n. For event i, call the action shown ai and its reward ri. Call the old policy’s chance of that action πlog(ai) and the new policy’s πnew(ai).
V-hat-IPS equals one over n times the sum over i of pi-new of a-i over pi-log of a-i, times r-i.
Give each logged event a weight, pi-new over pi-log. Multiply the reward r-i by it. Average over all n events. Rare actions the new policy likes count many times over.
The logger shows A with 0.8 and B with 0.2. Five events: (A,1), (A,0), (B,1), (A,1), (B,0). The new policy always shows B. Weights 0, 0, 5, 0, 5. V̂ = (5 × 1 + 5 × 0)/5 = 1.0. The log’s own average is 0.6.
That 1.0 rests on two events. The effective sample size counts how many events carry it: the squared sum of the weights over the sum of the squared weights.
Each bar is a logged event, sized by its weight. The blue line is the running IPS estimate; green is the new policy’s true value. Shrink the logger’s exploration and watch the weights and the ESS.
Illustrative world: A earns a reward 55% of the time and B 70%. The target policy always shows B, so its true value is 0.70.
Use offline scores as a filter, not a forecast. Plot past models’ offline gain against their online gain; if the ranks agree, offline kills bad candidates cheaply. Then run OPE, interleaving and a full A/B test.
The failure. Symptom: offline winners come back flat online. Measure: the ESS of the weights; a tiny share of n means the logs never saw the new policy’s choices. Fix: log a little random exploration with propensities, and use doubly robust estimators. Importance sampling derives the weight.
Chapter 8
Set the truth yourself, then watch each design report on the world you made
In real life you never know the truth, so a bad practice that ships many "winners" feels productive. Here the truth is a slider. Every error becomes a count.
Top: the latest experiment’s z over 14 days and its stopping boundary. Bottom: the scoreboard across runs. Set the truth, choose a stopping rule, then press Run 200.
Baseline conversion 5%, 50/50 split, 14 days. Daily conversions use a normal approximation; CUPED shrinks the noise variance by 1 − 0.7² = 0.51. The SRM switch drops 6% of treatment users who would not have converted, and the SRM check (p < 0.001) voids the run. Illustrative, checked against a seeded simulation of 20,000 runs per setting.
Try these in order. Each one is a chapter in a single number.
The numbers above are from 20,000 seeded runs per setting; 200 runs land within a few points of them.
Chapter 9
Count the share of shipped winners that do nothing, and see why real winners are overstated
Your org runs 100 experiments a year. About 10 test ideas that work. Every test is honest: α = 0.05, 80% power, one look. What share of the shipped winners do nothing?
Call the share of ideas that work the base rate b. Call the false-positive rate α and the power 1 − β. The false discovery rate (FDR) is the share of declared winners whose true effect is zero.
FDR equals one minus b, times alpha, over one minus b times alpha plus b times one minus beta.
Count the null ideas that win, one minus b times alpha. Count the real ideas that win, b times the power. Divide the first count by the total.
b = 0.10: real winners 10 × 0.8 = 8, false winners 90 × 0.05 = 4.5. FDR = 4.5/12.5 = 0.36. With peeking, α becomes about 0.25: FDR = 22.5/30.5 = 0.74. At b = 0.30 it drops to 0.13.
So the base rate of good ideas matters most. Better ideas and more power beat a stricter α. Over 20 null tests, the chance of at least one false winner is 1 − 0.9520 = 0.64.
Even real winners are overstated. Each estimate is the truth plus noise. You ship only estimates past the line, so you keep the lucky draws. This is the winner’s curse.
Each dot is one experiment’s estimate. Yellow is the significance line. Grey dots miss it; red dots win and stack on the right. Compare the blue mean of winners with the green truth. Lower the true effect.
Estimates are normal around the true effect with the chosen standard error, seeded. The exact mean of winners is the truncated-normal mean, shown beside the simulated one.
With a true lift of 1.0% and a standard error of 0.5%, the line sits at 1.96 × 0.5 = 0.98%. Power is 52%. The average winner reports 1.39%, 39% too high. At 80% power (standard error 0.357%) the average winner reports 1.12%.
Here φ (phi) is the bell curve’s height and Φ (capital phi) is the share below a point. Their ratio is the average overshoot past the line, in standard errors.
The failure. Symptom: leadership sums a year of winners’ lifts, and a year-long holdout shows about half. Measure: keep a long-term holdout, a small group that never gets the launches. Fix: shrink winner estimates toward past effects and rerun big surprises before planning on them.
Chapter 10
Keep the terms, the numbers, the checks and the code in one place
Randomize at the same time, on the unit the user feels. Check the split and size the test before it starts. Fix the stopping rule, cut variance with pre-period data, and look for anything the arms share. Then read the interval.
| Term | What it is | Number from this page |
|---|---|---|
| Two-share z | gap over its standard error | 7.15 for 40% vs 45% on 10,000 each |
| D = ATT + B | observed gap = effect on treated + selection bias | 1.0 = 0 + 1.0 under self-selection |
| SRM χ² | Σ(O − E)²/E on arm counts | 14.4, p = 0.00015 for 50,600 vs 49,400 |
| n per arm | (zα/2 + zβ)² · variances / δ² | 8,155 for 5% to 6%; 2,996,695 for 5% to 5.05% |
| Peeking | stop at the first |z| > 1.96 | 25.4% false positives over 20 looks |
| O’Brien-Fleming | bound c·√(K/k) at look k | c = 2.04 for 5 looks, 2.13 for 20 |
| CUPED | Y − θ(X − X̄); variance × (1 − ρ²) | ρ = 0.7: 1.96 times fewer users |
| Interference | arms share a resource | naive +12 vs true +2 points |
| IPS and ESS | mean of (πnew/πlog)·r; (Σw)²/Σw² | 1.0 with an ESS of 2 |
| FDR | false winners over all winners | 0.36 honest; 0.74 with peeking |
| Winner’s curse | mean of significant estimates | 1.39 for a true 1.0 at 52% power |
pythonimport numpy as np from scipy import stats def sample_size(p1, p2, alpha=0.05, power=0.80): z = stats.norm.ppf(1 - alpha/2) + stats.norm.ppf(power) return int(np.ceil(z**2 * (p1*(1-p1) + p2*(1-p2)) / (p2 - p1)**2)) def srm_p(n_control, n_treatment): # planned 50/50 return stats.chisquare([n_control, n_treatment]).pvalue def cuped(y, x): # x measured BEFORE randomization theta = np.cov(x, y, bias=True)[0, 1] / x.var() return y - theta * (x - x.mean()) def two_share_z(conv_t, n_t, conv_c, n_c): p = (conv_t + conv_c) / (n_t + n_c) se = np.sqrt(p * (1 - p) * (1/n_t + 1/n_c)) return (conv_t/n_t - conv_c/n_c) / se print(sample_size(0.05, 0.06)) # 8155 print(srm_p(50600, 49400)) # 0.000148 -> SRM, stop print(two_share_z(4500, 10000, 4000, 10000)) # 7.15
| Method | Idea | Assumption you must defend |
|---|---|---|
| Difference-in-differences | compare the treated group’s change with an untreated group’s change | parallel trends without the treatment |
| Interrupted time series | project the pre-trend forward as the counterfactual | no other shock at the same time |
| Regression discontinuity | units just either side of a cutoff are as if random | nobody games the cutoff |
| Encouragement design | randomize a nudge toward the treatment | the nudge moves the outcome only through the treatment |
| Synthetic control | a weighted blend of untreated units mimics the treated one | a good pre-period fit holds after launch |
The Statistics of Evaluation builds every test used here. Metric Design picks the metric an experiment should move, and The Metrics Ladder turns a lift into a business story. Plots That Tell the Truth shows how to present a readout. Summarizing Distributions covers heavy-tailed metrics, and Estimator Evaluation covers bias and variance. Regression Testing for ML takes a ship decision into release gates. Evaluating Generative Models builds metrics for generated output, and AI Evaluation covers the LLM eval process.
Importance sampling · Offline RL · Off-policy actor-critic · The Statistics of Evaluation
Further reading: Kohavi, Tang and Xu, Trustworthy Online Controlled Experiments (Cambridge, 2020).
Deng, Xu, Kohavi and Walker, "Improving the Sensitivity of Online Controlled Experiments by Utilizing Pre-Experiment Data" (WSDM 2013).
Fabijan et al., "Diagnosing Sample Ratio Mismatch in Online Controlled Experiments" (KDD 2019).
R. A. Fisher, 1938: "To consult the statistician after an experiment is finished is often merely to ask him to conduct a post mortem examination."
Now press Present or Teach. Explain from memory why a coin flip removes selection bias, how to size a test, why peeking lies, and what CUPED subtracts. Then go back to the hero, run all three designs, and say which chapter explains each red cell.