Sample Ratio Mismatch (SRM) Check in Python for A/B Tests

Check an A/B test for a sample ratio mismatch with scipy's chi-square test, find which segment causes it, and see how a lost-user bug can fake a lift.

A sample ratio mismatch (SRM) means the number of users in each arm differs from the split you configured by more than chance allows. Check it with a chi-square goodness-of-fit test: scipy.stats.chisquare(observed_counts, f_exp=expected_counts). A tiny p-value (teams commonly alert below 0.001) says something upstream is broken, and the test result should not be trusted until you find it. The code below uses SciPy 1.18.

Quick Example

A test was configured for a 50/50 split. The logged counts are 150,103 in control and 139,838 in treatment. This runs on its own:

import numpy as np
from scipy import stats

observed = np.array([150_103, 139_838])
expected = np.array([0.5, 0.5]) * observed.sum()

chi2, p_value = stats.chisquare(observed, f_exp=expected)
print(f"chi2 = {chi2:.1f}, p = {p_value:.2e}")

The output is chi2 = 363.4, p = 5.07e-81. A gap of about 10,000 users is not sampling noise at this size, so this experiment has an SRM.

Bar chart of expected and observed users per arm: expected 144,970 each, observed 150,103 in control and 139,838 in treatment

Why an SRM Invalidates the Result

Randomization is what makes the arms comparable. If users go missing from one arm, they probably did not go missing at random. In this example, a bug stops some slow Safari users in treatment from being logged. Slow users convert less, so the treatment arm looks better even though the treatment does nothing.

The data below is simulated: 300,000 users, a true effect of zero, and a bug that drops 90% of slow Safari users from treatment.

import pandas as pd

rng = np.random.default_rng(31)
n = 300_000
platform = rng.choice(["Chrome", "Safari", "iOS app", "Android app"], size=n, p=[0.40, 0.25, 0.20, 0.15])
variant = rng.choice(["control", "treatment"], size=n)
slow = rng.random(n) < 0.30
converted = rng.random(n) < np.where(slow, 0.04, 0.10)   # no treatment effect at all
lost = (variant == "treatment") & (platform == "Safari") & slow & (rng.random(n) < 0.90)

full = pd.DataFrame({"variant": variant, "converted": converted})
df = pd.DataFrame({"variant": variant, "platform": platform, "converted": converted})[~lost]

def lift_pp(d):
    c = d.loc[d.variant == "control", "converted"]
    t = d.loc[d.variant == "treatment", "converted"]
    se = np.sqrt(t.var() / len(t) + c.var() / len(c))
    return (t.mean() - c.mean()) * 100, 1.96 * se * 100

print("all users:", lift_pp(full))
print("with bug: ", lift_pp(df))

Without the bug the estimate is -0.15 pp (95% interval ±0.20). With it, the estimate moves to +0.13 pp. Both intervals include zero in this single run, so the harm shows up as a systematic shift of 0.28 pp rather than a clearly significant result. With more traffic, or a bug that drops more users, the same bias would sit outside the interval and the test would report a winner that does not exist.

Confidence intervals for treatment minus control conversion: minus 0.15 percentage points without the bug and plus 0.13 with the bug, true effect zero

How Do I Find Which Segment Is Broken?

Run the same check per segment. With two arms, a binomial test of the treatment share against 0.5 is the segment version of the chi-square test, and scipy.stats.binomtest is the function:

rows = []
for seg, g in df.groupby("platform"):
    k, m = (g["variant"] == "treatment").sum(), len(g)
    rows.append((seg, m, k / m, stats.binomtest(k, m, 0.5).pvalue))

print(pd.DataFrame(rows, columns=["platform", "users", "treatment_share", "p_value"]).round(4))

Safari has a treatment share of 0.421 with p effectively 0. The other three platforms are between 0.4995 and 0.5009 with p-values from 0.70 to 0.86. The mismatch comes from one browser, which points straight at a logging or redirect bug there.

Dot plot of treatment share by platform: Safari at 0.42 far below 0.5, while Chrome, iOS and Android sit on 0.5 within their ranges

When you check many segments, use a strict threshold such as 0.001 so that a normal 5% false alarm rate across segments does not send you hunting for bugs that are not there.

What Counts as an SRM?

Check Function Use when
Two arms, whole experiment stats.chisquare or stats.binomtest The default check
Three or more arms stats.chisquare(observed, f_exp=...) Unequal splits such as 80/10/10
Per segment stats.binomtest in a loop Locating the cause
Over time The same test per day A bug that starts mid-test

For an uneven split, set f_exp to the configured proportions times the total, for example np.array([0.8, 0.1, 0.1]) * observed.sum().

Common Causes

  • Redirects or page-load failures that lose users in one arm (a heavier variant that times out).
  • Bot filtering or deduplication applied after assignment and affecting one arm more.
  • Assignment logged by two systems that disagree.
  • Triggering conditions that differ between arms (counting only users who saw a feature that exists in one arm).
  • A ramp-up of traffic that was not applied evenly across arms.

Practical Tips

  • Run the SRM check before looking at any metric. If it fails, stop and debug.
  • Use the number of users actually assigned, not users who converted or clicked.
  • A very large sample makes the test sensitive to small gaps. A statistically significant but tiny mismatch is still a signal worth a look, since any real bug in assignment is a systematic problem.
  • Do not fix an SRM by reweighting the results. Find the cause and rerun if needed.

Similar Topics