Rana Maninder Singh
Lesson 4 of 7A/B Testing

Running the Experiment

Lesson opener

In one line: Logging exposures and conversions cleanly.

Why it matters: The analysis population is "exposed," not "opened the app sometime."

Before this lesson: Sample size and power

Before you start

ResourceLink
PreviousSample size and power
NextAnalyzing results
PrerequisitesSample size and power
Time~50 minutes

What you will learn

  • Logging exposures and conversions cleanly
  • Checking sample ratio mismatch (SRM)
  • Freezing the analysis window before you peek
  • Deduplicating users and spotting instrumentation bugs early

Pinned libraries for this course

pip install -r docs/abtest/requirements.txt

Pinned in docs/abtest/requirements.txt:

numpy==2.1.3
scipy==1.14.1
pandas==2.2.3
statsmodels==0.14.4

This lesson uses pandas for logs and scipy.stats.chisquare for SRM — offline only. The same pins keep chisquare and timestamp behaviour aligned across analyst laptops in Pune and Bengaluru. Treat exposure schema changes as experiment-breaking: bump experiment_id when fields or assignment logic change.


Exposure logs

Every user who could see the change must be logged once with variant and timestamp. Conversions join to that exposure set. If you only log buyers, you silently condition on the outcome.

WHY The analysis population is "exposed," not "opened the app sometime."

WHEN At assignment time in the client or edge — same request that chooses A/B.

A Mumbai fintech shipping new UPI CTA copy should log experiment_id, variant, user_id, exposed_at (IST), and app version. Missing version makes rollback analysis painful when half the traffic is on an old APK.

Demo 1 — Exposure table

# Offline demo: exposure log shape
import pandas as pd

exposures = pd.DataFrame({
    "user_id": [1, 2, 3, 4, 5, 6],
    "variant": ["A", "B", "A", "B", "A", "B"],
    "exposed_at": pd.to_datetime([
        "2026-09-01", "2026-09-01", "2026-09-02",
        "2026-09-02", "2026-09-03", "2026-09-03",
    ]),
})
print(exposures["variant"].value_counts().sort_index())
assert exposures["user_id"].is_unique

Demo 2 — Sample ratio mismatch (SRM)

# Offline demo: chi-square SRM check vs expected 50/50
from scipy.stats import chisquare


def srm_pvalue(counts: list[int], expected_ratio=(0.5, 0.5)) -> float:
    total = sum(counts)
    expected = [total * r for r in expected_ratio]
    stat, p = chisquare(counts, f_exp=expected)
    return float(p)


print("balanced ~", round(srm_pvalue([5000, 5100]), 3))
print("broken ~", round(srm_pvalue([5000, 3500]), 3))
assert srm_pvalue([5000, 5100]) > srm_pvalue([5000, 3500])

[!important] If SRM p-value is tiny, stop analysis and fix assignment/logging first.

Demo 3 — Analysis window mask

# Offline demo: freeze start/end before peeking
import pandas as pd

exposures = pd.DataFrame({
    "user_id": [1, 2, 3, 4, 5, 6],
    "variant": ["A", "B", "A", "B", "A", "B"],
    "exposed_at": pd.to_datetime([
        "2026-09-01", "2026-09-01", "2026-09-02",
        "2026-09-02", "2026-09-03", "2026-09-03",
    ]),
})


def in_window(ts: pd.Series, start: str, end: str) -> pd.Series:
    return (ts >= pd.Timestamp(start)) & (ts <= pd.Timestamp(end))


mask = in_window(exposures["exposed_at"], "2026-09-01", "2026-09-02")
print(int(mask.sum()))
assert int(mask.sum()) == 4

Why SRM happens in production

Common causes in Indian mobile-heavy products:

  1. Client-side bucketing bugs on older Android WebViews.
  2. Bot / prepaid-traffic filters applied after assignment on one variant only.
  3. CDN or feature-flag defaults sending unmatched users to control.
  4. Duplicate exposure rows for variant B only (retry logic).

SRM is a validity check, not a "nice to have." A beautiful lift with SRM p ≈ 0 is not a ship decision — it is an incident.

Demo 4 — Deduplicate exposures

# Offline demo: keep first exposure per user
import pandas as pd

exposures = pd.DataFrame({
    "user_id": [1, 2, 3, 4, 5, 6],
    "variant": ["A", "B", "A", "B", "A", "B"],
    "exposed_at": pd.to_datetime([
        "2026-09-01", "2026-09-01", "2026-09-02",
        "2026-09-02", "2026-09-03", "2026-09-03",
    ]),
})


def first_exposure(frame: pd.DataFrame) -> pd.DataFrame:
    return (
        frame.sort_values("exposed_at")
        .drop_duplicates(subset=["user_id"], keep="first")
        .reset_index(drop=True)
    )


dupes = pd.concat([exposures, exposures.iloc[[0]].assign(exposed_at=pd.Timestamp("2026-09-04"))])
clean = first_exposure(dupes)
print(len(dupes), "->", len(clean))
assert clean["user_id"].is_unique

Demo 5 — Join conversions to exposures

# Offline demo: inner-join conversions onto exposures only
import pandas as pd

exposures = pd.DataFrame({
    "user_id": [1, 2, 3, 4, 5, 6],
    "variant": ["A", "B", "A", "B", "A", "B"],
})
conversions = pd.DataFrame({
    "user_id": [2, 4, 99],
    "converted_at": pd.to_datetime(["2026-09-01", "2026-09-02", "2026-09-02"]),
})


def analysis_frame(exposures_df: pd.DataFrame, conversions_df: pd.DataFrame) -> pd.DataFrame:
    base = exposures_df[["user_id", "variant"]].copy()
    base["converted"] = base["user_id"].isin(set(conversions_df["user_id"])).astype(int)
    return base


af = analysis_frame(exposures, conversions)
print(af)
assert int(af.loc[af["user_id"] == 99, "converted"].sum()) == 0  # never exposed
assert int(af["converted"].sum()) == 2

Freezing the window

Pre-register start and end (or end rule: "when each arm hits n"). Peeking mid-window and moving the end date because the chart looked sad or happy invalidates the nominal alpha. Optional sequential designs exist; ad-hoc stop rules do not.

WHY The p-value assumes a fixed design.

WHEN Write the window in the same brief as the MDE.

Demo 6 — Daily exposure monitor (not a peek at CVR)

Monitoring counts and SRM daily is operationally healthy. Monitoring p-values on the primary daily is peeking unless you planned a sequential test.

# Offline demo: daily exposure counts for ops health only
import pandas as pd

exposures = pd.DataFrame({
    "user_id": [1, 2, 3, 4, 5, 6],
    "variant": ["A", "B", "A", "B", "A", "B"],
    "exposed_at": pd.to_datetime([
        "2026-09-01", "2026-09-01", "2026-09-02",
        "2026-09-02", "2026-09-03", "2026-09-03",
    ]),
})


def daily_counts(frame: pd.DataFrame) -> pd.DataFrame:
    out = frame.copy()
    out["day"] = out["exposed_at"].dt.floor("D")
    return out.groupby(["day", "variant"]).size().unstack(fill_value=0)


print(daily_counts(exposures))
assert daily_counts(exposures).sum().sum() == len(exposures)

Instrumentation habits that survive on-call

Running an experiment is mostly logging discipline. Assignment must happen when the user becomes eligible, and the exposure event must fire once with a stable experiment_id. Retries on flaky mobile networks in tier-2 cities can duplicate events; that is why first-exposure dedupe exists. If variant B retries more often because the new CTA triggers an extra analytics call, you invent SRM from nothing.

Ops may watch daily exposure counts and SRM. That is healthy. Watching the primary p-value daily is not, unless you pre-registered a sequential design. Separate the dashboards: one for "are we collecting clean exposures?" and one for "end-of-window decision," locked until the end date. Freeze the analysis window in writing. Moving the end date because Monday looked sad invalidates the nominal alpha even if nobody says the word peeking.

Join conversions only to exposed users. A conversion from user 99 who never hit the assignment path does not belong in the treatment rate. Intent-to-treat designs are valid when planned; silent inclusion of never-exposed users is not. Store app version and platform so a WebView bug on older Android builds can be diagnosed when SRM trips. When SRM p-values are tiny, stop the confirmatory story and open an incident — do not "adjust" by dropping one arm until the chart looks balanced.

A practical dry-run: flip the experiment on an internal allowlist in Bengaluru and Pune offices for one day, export exposures, run SRM and dedupe checks, and confirm conversion joins. Only then open to 50/50 production traffic. Changing the traffic percentage mid-test without a new experiment id correlates early and late cohorts and confuses weeks_needed math from the prior lesson. Document the owner of the exposure schema so on-call knows whom to page when counts stall overnight.

WHY Bad logs make beautiful but false lift charts.

WHEN Before launch day, with a dry-run on staging traffic if you can.

Failure modes

  1. Analyzing users who never saw the page (intent-to-treat vs exposure confusion without a plan).
  2. Counting multiple exposures per user as independent.
  3. Changing the flag percentage mid-test without resetting the experiment id.
  4. Declaring a winner before SRM passes.

Instrument first, analyze later. The next lesson computes p-values and lift intervals on clean frames. If SRM fails on day one, pause assignment, fix bucketing, and start a new experiment id rather than "cleaning" rows until the ratio looks pretty. Never declare a winner from a dashboard that has not passed the SRM gate in this lesson.

Verified against numpy 2.1.3, scipy 1.14.1, pandas 2.2.3 (+1 more) documentation, September 2026.

Test yourself

  1. What is an exposure?
  2. What does SRM stand for?
  3. What does a very small SRM p-value suggest?
  4. Why freeze the analysis window?
  5. True or false: you should analyze users who never saw the page as if exposed.
  6. What does chisquare compare in the SRM helper?
  7. Name one logging field you must store.
  8. Why count each user once?
  9. What lesson covers sample size?
  10. True or false: SRM checks come after declaring a winner.