Skip to content
Tech Interview Prep
Technical interview guide

Hypothesis Testing

The framework for deciding whether an observed effect is likely real or could plausibly be noise: null hypotheses, p-values, and the two ways a test can be wrong.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v7
Editorial status
Reviewed

Scope: Standards and library references current as of 2026-09: NIST/SEMATECH e-Handbook, the 2016 ASA statement on p-values, SciPy, and statsmodels.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain what a p-value actually is and how it changes a production decision.

Answer

A p-value is the probability of seeing data at least as extreme as yours, computed under the assumption that the null hypothesis is true. It is P(data | null), never P(null | data). It is not the probability the null is true, and it is not the size of the effect.

That distinction decides production calls, so make it concrete.

A worked decision

You ship a change to the checkout recommender. Control converts at 10.0%, treatment at 10.4%, 100,000 sessions per arm.

Python
import math
p0, p1, n = 0.10, 0.104, 100_000
se = math.sqrt(2 * p0 * (1 - p0) / n)   # 0.0013416
z  = (p1 - p0) / se                      # 2.9814
# two-sided p = 2 * (1 - Phi(2.9814)) = 0.0029

p = 0.0029, so at the conventional α = 0.05 you reject the null. But the number that decides the ship is the interval: 0.4pp ± 1.96 × 0.134pp gives a 95% CI of [0.14pp, 0.66pp]. At 1M sessions/month and $50 revenue per conversion, that is $200k/month at the point estimate and $68.5k/month at the lower bound. If the change costs $20k/month in infra, the lower bound still clears it: ship. If it costs $90k/month, the same p-value says don't. The p-value never made that call; the interval and the cost did.

Where p-values mislead in practice

Four ways, each with a number:

  • Base rates. Most changes do nothing. If 10% of your experiments have a real effect, then at α = 0.05 with 80% power, 100 experiments yield about 8 true positives and 4.5 false positives: a third of your "wins" are noise. The p-value cannot see this; the prior can.
  • Multiple comparisons. The dashboard has 20 metrics. At α = 0.05 you expect one false positive per experiment by construction. Bonferroni gives 0.05/20 = 0.0025, and our p = 0.0029 fails it. Pre-register one primary metric.
  • Optional stopping. Five equally spaced unadjusted looks at α = 0.05 push the family-wise error rate to roughly 0.14. If you must peek, use a sequential test with always-valid intervals.
  • Low power. At n = 100k per arm, the minimum detectable effect at 80% power is 2.8 × 0.134pp ≈ 0.38pp. If the lift you care about is 0.1pp, you need about 1.4M per arm. A non-significant p-value from an underpowered test is not evidence of no effect.

Trade-offs

Reporting effect size and a confidence interval alongside p is the minimum. When the decision is asymmetric, shipping a bad change hurts more than missing a good one, a Bayesian posterior with expected loss gives you a threshold you can defend. When you need to stop early, sequential methods widen the interval but buy back the α you would otherwise burn.

Failure modes and detection

The inversion: reading p = 0.0029 as a 0.29% chance the change does nothing: is caught by asking for the prior. Peeking is caught in the analysis log: if the sample size was not fixed in advance, the α is not 0.05. Metric sprawl is caught by counting the dashboard. Underpowered tests are caught by computing the MDE before launch, not after.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

How would you reason about the null and alternative hypotheses in a system you own?

Answer

Core answer (first 90 seconds). I start from the decision, not the statistic. For a system I own, the null is the state I keep if the data says nothing, normally "the change does nothing", and the alternative is the smallest effect that would change what I ship. Then I check the test can see that effect before I run it. On a checkout flow at 12% baseline conversion, a 0.5pp absolute lift is the threshold I'd act on; at 80% power and 5% two-sided alpha that needs roughly 68,000 users per arm. If I can't get that traffic, I widen the threshold or don't run the test. I don't run it and then call the null result "no effect".

Setting H0 and H1 for a system you own.

  • H0 is the default action, not a strawman. If the default is "keep the current ranker", H0 is "the new ranker is no better". Writing H0 as the thing you hope to reject is how motivated reasoning gets in.
  • H1 is the minimum effect worth acting on, not "any difference". At 200k users per arm the minimum detectable effect is about 0.29pp; at 2M per arm it drops to about 0.09pp, so a 0.1pp lift comes back significant, and it is still a fifth of the 0.5pp threshold I'd act on. Significance is not the same as mattering.
  • Two-sided unless you can defend one-sided. One-sided halves the sample, but you must be willing to ignore a large regression in the other direction: for a system you own, you usually aren't.
Decision you're makingH0H1What you report
Ship only if betterlift = 0lift ≠ 0CI; ship if the lower bound clears the threshold
Ship unless it's worselift ≤ −marginlift > −marginone-sided CI against the margin
Catch any regressionno changeany changesequential / always-valid test

Sizing it. The rule of thumb n = 16·p(1−p)/d² per arm is the two-proportion power formula with the pooled-variance approximation: (z_{α/2}+z_β)² = 7.84 for 80% power at 5% two-sided, doubled to 15.68 because both arms contribute p(1−p), rounded to 16.

Python
import math
p, d = 0.12, 0.005           # baseline conversion, decision threshold (absolute)
n = 16 * p * (1 - p) / d**2  # 80% power, 5% two-sided
print(math.ceil(n))

Trace: p*(1-p) = 0.12 × 0.88 = 0.1056; 16 * 0.1056 = 1.6896; d**2 = 0.000025; 1.6896 / 0.000025 = 67584.0; ceil leaves it at 67584. Output: 67584.

Failure modes.

  • Peeking. A fixed-horizon 5% test checked daily no longer has a 5% false-positive rate; the nominal alpha holds only at the pre-registered sample size. Detect it in the analysis log; fix it with a sequential or always-valid test.
  • Wrong unit of analysis. Randomise by user, analyse by session, and the variance is understated, so p-values come out too small. Detect it by comparing the naive standard error to a cluster-robust one.
  • Metric sprawl. Twenty guardrail metrics at 5% each give 1 − 0.95²⁰ ≈ 64% chance of at least one false positive. Pre-register one primary metric and correct the rest.

When a hypothesis test is the wrong tool. If you can't randomise, a test on observational data answers a different question: use a causal method with an explicit identification assumption. If the decision is asymmetric (a regression costs 10× a win), an expected-loss calculation over the CI beats a significance verdict.

What I report. The interval and the decision, not the p-value. "Lift 0.3pp, 95% CI [−0.1, 0.7]; lower bound below the 0.5pp threshold, so we don't ship" is a sentence a stakeholder can act on.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Walk through type I and type II errors, including where engineers most often get it wrong.

Answer

Type I error is rejecting a true null: a false alarm, rate α, the significance level you fix before looking at data. Type II error is failing to reject a true alternative: a miss, rate β. Power is 1 − β: the chance you detect an effect that is actually there.

Why they trade off. Picture two distributions of the test statistic. Under H0 it is centred at zero; under a real effect of size d it is centred at d. You pick one critical value and call everything past it a rejection. Slide the threshold left: you catch more real effects (power up) and more null noise (α up). Slide it right and both fall. At a fixed sample size the two rates move in opposite directions, so you cannot buy your way out of one without paying in the other. The only levers that cut both are a larger sample or a larger effect.

Where engineers get it wrong.

Reading α as P(H0). p = 0.03 is not a 3% chance the null is true. It is the chance of data this extreme given the null. The posterior you actually want needs a prior, and for a small effect with a weak prior it can stay high even at p = 0.03.

Setting α and never computing power. Then β is unknown and usually huge. Twenty users per arm chasing d = 0.2 at α = 0.05 gives power ≈ 9%: you would miss a real effect 91% of the time and call the null "confirmed".

Multiple comparisons. Twenty independent metrics at α = 0.05 gives a family-wise false-positive rate of 1 − 0.95²⁰ ≈ 64%. One of them will look like a winner.

Peeking. Checking daily and stopping the first time p < 0.05 pushes the real α well above 0.05.

Significance vs. size. At large n a 0.1% lift is significant and not worth shipping.

Sizing. Fix α, power, and the smallest effect worth detecting, then derive n. For a two-sample test, n per arm ≈ 2(z_{1−α/2} + z_{1−β})² / d².

αpowern per arm (d = 0.2)
0.050.80393
0.050.90526
0.010.80584

The senior move is to state all three up front and let the sample size fall out, rather than picking n from convenience and reporting whatever α the data happens to clear.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

What does statistical power guarantee, and what does it deliberately leave open?

Answer

Power is 1−β: the probability that a test of a fixed design rejects the null when the true effect is at least the size you powered for. The guarantee is conditional and one-directional, if the real effect is Δ or larger, you will get a significant result with probability 1−β. What it deliberately leaves open is everything else: the true effect size, its sign, and the meaning of a non-significant result. A null result from an underpowered test is uninformative: it is equally consistent with "no effect" and with "an effect smaller than this design can resolve." Power never licenses the claim "there is no effect."

Mechanically, under H0 the test statistic is centred at 0; under H1 it is centred at Δ/SE. β is the area of the H1 distribution that falls below the critical value. Raising n shrinks SE, which narrows both distributions and pushes their centres apart in standard-error units, so β falls. That is why power is a property of the design, not of the data: it is fixed the moment you fix n, α, and the Δ you assume. Change the assumed Δ and the required n changes with it: the effect size is the free variable you are choosing, not measuring.

Python
from statsmodels.stats.power import TTestIndPower
# two-sample t-test, two-sided alpha=0.05, power=0.8, equal arms
TTestIndPower().solve_power(effect_size=0.2, alpha=0.05, power=0.8)
# 393.4  -> 394 per arm

Same call at other effect sizes shows how much of the answer is the assumption, not the method:

Assumed Δ (Cohen's d)n per arm at 80% power, α=0.05
0.2 (small)393.4
0.5 (medium)63.8
0.8 (large)25.5

Pre-registered power analysis is the default when the decision is expensive or hard to reverse. A cheap, low-powered experiment is the right call when the action is cheap to reverse, when you are screening many candidates and will follow up the survivors, or when a false negative costs far less than the extra samples. Sequential designs (group-sequential, always-valid) buy back power by letting you stop early, at the cost of a pre-specified stopping rule. Post-hoc power is not an alternative: computed from the observed effect it is a deterministic function of the p-value you already have, so it corroborates nothing.

Three failure modes worth naming. Post-hoc power reported as evidence: it moves 1:1 with p, so it cannot add information. Powering for an effect you do not care about, e.g. a pilot's inflated effect size, which makes the study look adequately powered while it cannot detect the effect you would act on. And reporting "no significant difference" as "no difference": the honest number to report is the study's minimum detectable effect at the power you actually had.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Describe the minimum detectable effect and the evidence you would collect before relying on it.

Answer

The 60-second answer

MDE is the smallest true effect the test has a given probability of detecting: the effect size at which the test rejects the null with probability equal to power. For a two-arm test of a proportion, with α = 0.05 (two-sided) and 80% power:

MDE ≈ (1.96 + 0.84) · √(2·p(1−p)/n)

At a 5% baseline and n = 10,000 per arm: √(2·0.05·0.95/10,000) = 0.00308, so MDE ≈ 2.8 × 0.00308 ≈ 0.0086. About 0.9 percentage points, a 17% relative lift. If the smallest lift worth shipping is 2%, this test cannot resolve it; you'd need roughly (0.02/0.0086)² ≈ 5.4× the sample, about 54,000 per arm.

It is fixed at design time by n, the baseline variance, and the error rates. It is not a property of the data you later collect.

Evidence to collect before relying on it

  • Baseline rate from your own logs, not a guess. MDE scales with √(p(1−p)); a 5% baseline and a 50% baseline give very different MDEs at the same n.
  • Eligible sample size after filtering: assignment minus non-exposure, bot traffic, and users who never reach the metric. Dilution inflates the effective MDE.
  • Variance estimate for the actual metric. Proportions are stable; revenue or session-count metrics are heavy-tailed, and a plug-in variance from a short window understates the MDE.
  • Design effects: clustering (per-user vs per-session randomization), unequal split, CUPED or other variance reduction, and multiple comparisons across metrics. Each changes the effective n.
  • An A/A test or historical backtest to confirm the realized false-positive rate matches α and the variance model holds.
  • Guardrail metrics and their own MDEs: you need to know the smallest regression you can catch, not just the lift.

Trade-offs

MDE falls as 1/√n, so halving it costs 4× the sample. Options: run longer, raise the traffic share, apply variance reduction (CUPED typically cuts variance 30–50% on pre-period-correlated metrics), or pick a more sensitive proxy metric. The deciding criterion is the smallest effect that would change the decision: if MDE exceeds it, don't run. A non-significant result is guaranteed regardless of the truth, and you've spent the traffic for nothing.

Failure modes

  • Reporting a p-value from an underpowered test as evidence of no effect.
  • Computing MDE from raw assignment while the analysis uses exposed users.
  • Trusting a variance estimate from a window shorter than the metric's natural cycle (weekly seasonality).

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

A teammate proposes a design that hinges on effect size versus significance. How do you evaluate it?

Answer

What I'd ask first. What decision does this design drive, and what's the smallest effect that would change it? If the answer is "ship if it wins," significance is the wrong gate. With enough traffic, any nonzero change clears p < 0.05, so a significant result tells you the effect is detectable, not that it's worth acting on. I'd want the design to pre-commit to a minimum detectable effect (MDE), the smallest lift worth shipping, and to judge the confidence interval against that threshold rather than against zero.

Why the two diverge. The p-value scales with sample size; the effect size doesn't. A t-test on a million users per arm flags a 0.005-standard-deviation shift as significant, and it is: the shift is real. It's just too small to matter.

Python
from scipy import stats
import numpy as np
rng = np.random.default_rng(0)
a = rng.normal(0, 1, 1_000_000)
b = rng.normal(0.005, 1, 1_000_000)
stats.ttest_ind(a, b).pvalue   # ~0.0004
# Cohen's d = 0.005. Real, and irrelevant.

The standard error here is sqrt(2/1e6) ≈ 0.0014, so a 0.005 gap gives t ≈ 3.5. Shrink the sample to 10,000 per arm and the same gap is invisible (t ≈ 0.35, p ≈ 0.7). Same effect, opposite verdict, which is why the design has to name the effect size it cares about, not just the alpha.

How I'd evaluate the proposal. Four checks:

  1. Is there a pre-registered MDE and a practical-significance threshold, or only an alpha?
  2. Does the analysis compare the CI to that threshold, or to zero?
  3. Is the stopping rule fixed (no peeking), or does optional stopping inflate false positives?
  4. Are guardrail metrics (latency, error rate, revenue) tracked so a "win" on the primary metric can't hide a regression elsewhere?

Alternatives, and when each fits.

ApproachAnswersUse when
MDE / power analysis"Can this test detect the lift I care about?"Default for product experiments
Bayesian posterior"P(effect > threshold | data)"Stakeholders want a probability, not a p-value
Significance-only"Is there any effect?"Correctness fixes, bug fixes, any nonzero change is worth shipping
Sequential / always-validSame, with continuous monitoringYou can't fix the sample size in advance

Failure modes I'd flag. Optional stopping: checking daily and stopping at the first p < 0.05 can push the false-positive rate well above 5%. Multiple comparisons across segments: slicing into ten subgroups gives a ~40% chance of one spurious "significant" result at alpha 0.05. Novelty and primacy effects: early lift that decays. And segment-mix shifts (Simpson's paradox) where the pooled effect reverses within every segment.

When not to bother. If the change is a correctness fix or the effect is obviously large, skip the machinery: significance-only is fine. The design only needs the effect-size apparatus when the decision turns on a small, contested lift.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Where does choosing a test matter, and where is it irrelevant?

Answer

Assume "test" means a statistical hypothesis test, and the question is when the specific test changes the verdict versus when any reasonable one gives the same answer.

Choosing matters when the reference distribution depends on the design or on an assumption you cannot verify. It stops mattering when the sample is large enough that the central limit theorem pins the sampling distribution, or when the design itself already fixes the test.

Where it matters:

SituationWrong choiceRight choiceWhat breaks
Paired measurementsunpaired tpaired tbetween-subject variance swamps the effect
Unequal variances, unequal nStudent's pooled tWelch's tType I rate inflates above nominal
Small n, skewed datat-testWilcoxon / Mann-Whitneyp-value driven by outliers
Small counts in a 2x2chi-squaredFisher's exactchi-squared approximation invalid
Many comparisonsuncorrected pHolm / Bonferronifamily-wise error grows with k

Worked example (hypothetical figures). Ten subjects measured before and after. The differences have mean 4.0 and sd 3.0. Paired t = 4.0 / (3.0 / sqrt(10)) = 4.22, df 9, p ≈ 0.002. Now treat the same data as two independent groups: before mean 50, sd 10; after mean 54, sd 10. Unpaired t = 4 / sqrt(100/10 + 100/10) = 0.89, df 18, p ≈ 0.38. Same numbers, opposite verdicts. The pairing removed the between-subject variance; ignoring it threw that away.

Where it is irrelevant:

  • Large n. At n in the thousands the t, z and Welch statistics agree to several decimals; the CLT has already made the mean normal.
  • Design fixed. If the data are paired, you do not choose: the pairing is in the design.
  • Huge effect. If the effect sits many standard errors from zero, every test rejects.
  • Bias dominates. Test choice controls Type I error; it does nothing about a confounded design or a biased sample. That is the failure people miss: they tune the test and ignore the sampling.

Trade-offs. Welch vs Student: Welch gives up a little power when variances are truly equal and n is small, and buys protection against Type I inflation when they are not. Default to Welch. Wilcoxon vs t: Wilcoxon is robust to outliers but tests a different null (equal distributions, or a median shift under symmetry) and loses power when the data are normal. Fisher vs chi-squared: Fisher is exact but conservative and slow for large tables.

Failure modes and detection. Run the test both ways and see whether the verdict flips; if it does, the choice mattered and you must justify the assumption. Check the assumption directly (Levene's test for variance, a QQ plot for normality) rather than assuming it. Report the effect size and confidence interval, not just p, so a reader can see whether the verdict is marginal.

So the choice matters when it changes the reference distribution under a design or assumption you cannot verify; it is irrelevant when n is large, the design fixes it, the effect is huge, or bias rather than variance is the dominant error.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

How should on-call treat an alert that names one-sided versus two-sided tests as the cause?

Answer

First 90 seconds

Read the alert body literally: it names a decision rule, not a system state. An alert that says the test was one-sided is telling you how the threshold was computed, so the first question is whether something broke or whether the rule was set wrong. Assume the raw per-arm data is still queryable and the experiment config is in version control; if either is gone, that is the incident.

Treat the sidedness as a property of the detector, not of the incident. Pull the raw data, recompute the two-sided p-value, and compare it to the alert's threshold. A one-sided p of 0.04 in the observed direction is a two-sided p of 0.08: the alert fired on half the evidence it appears to have. If the two-sided p sits above your ship threshold, the page is a config bug, not a regression.

What each annotation actually means

Alert saysWhat it tells youOn-call action
one-sided, guardrail metricMonitor is blind to harm in the untested direction; it cannot have fired on harmFind which rule actually fired; the annotation is stale or wrong
one-sided, ship metric, p=0.04Evidence is half of a two-sided p=0.04Recompute two-sided (0.08); treat as inconclusive
config edited after the data freezeDirection chosen after seeing the signFreeze, page the experiment owner, do not re-run

Mechanism and the failure it invites

A one-sided test concentrates alpha in one tail. At alpha=0.05 the two-sided test needs |t| past the 97.5th percentile; the one-sided test needs it past the 95th. That is a real power gain when the direction is fixed in the plan, and a doubled false-positive rate (0.05 to 0.10) when the direction is chosen after seeing the sign. The second case is the one that pages you: someone flips alternative to make a marginal result significant, the threshold is crossed, and the rotation inherits a decision that was never valid.

Python
from scipy import stats
# a, b: per-user values pulled from the experiment's raw table
two = stats.ttest_ind(a, b, alternative="two-sided").pvalue
one = stats.ttest_ind(a, b, alternative="greater").pvalue
# The t null distribution is symmetric, so one == two/2 whenever the
# observed mean of a is above b. If two is 0.08, one is 0.04.

During the incident

Do not re-run with a flipped alternative to make the alert go away; that is the same error with the sign reversed. Freeze the decision rule, recompute both p-values from the frozen data, and hand the experiment owner the config diff. If the guardrail was one-sided in the improvement direction, the page you got came from some other rule: find that rule before you trust it. The only case where sidedness is genuinely the cause is a guardrail that fired on a metric moving in the tested direction while the untested direction was the one at risk, and there the fix is the config, not the service.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Teach the assumptions behind the t-test to an engineer who has only seen it as a rule of thumb.

Answer

The 90-second version. The t-test is a claim about the sampling distribution of a mean, not about your raw data. Three assumptions get you there: (1) observations are independent, (2) the standardized mean is approximately normal, and (3) for the two-sample pooled version, both groups share a variance. Assumption 2 is the one people worry about, and the one the CLT usually rescues. Assumption 1 is the one that actually breaks on production data, and no sample size fixes it.

Why the t-distribution, and why normality is about the mean. You compute t = (x̄ − μ)/(s/√n). If x̄ were normal and σ known, that would be a z. Replacing σ with s adds noise, and the t-distribution with n−1 df is exactly the distribution of that ratio when the x_i are normal. The requirement is on x̄, not on x_i. For iid draws with finite variance, x̄ has mean μ and variance σ²/n, and its standardized version converges to N(0,1); the skewness of x̄ is the skewness of x_i divided by √n. Raw skew of 2 at n=100 gives mean-skew 0.2: invisible. At n=10 it gives 0.63, and the p-values are off. That is the entire content of "robust at large n": it is a statement about √n shrinking skew, not about the t-test being magic.

Why dependence is different. When observations arrive in clusters (10 page views per user, 5 measurements per patient) the variance of the mean is not σ²/n. With intraclass correlation ρ and cluster size m it is σ²/n × (1 + (m−1)ρ). The design effect is constant in n. Adding users helps; adding views per user does not.

Python
import numpy as np
rng = np.random.default_rng(0)
C, m = 100, 10                      # 100 users, 10 views each
user = rng.normal(0, 1, C)          # user effect, sd 1
x = (user[:, None] + rng.normal(0, 1, (C, m))).ravel()   # noise sd 1 -> ICC = 0.5

naive_se     = x.std(ddof=1) / np.sqrt(x.size)
clustered_se = x.reshape(C, m).mean(axis=1).std(ddof=1) / np.sqrt(C)
print(round(naive_se, 3), round(clustered_se, 3), round(clustered_se/naive_se, 2))
# 0.045 0.105 2.35

Trace: total variance is 1 (user) + 1 (noise) = 2, so x.std ≈ 1.414 and naive_se ≈ 1.414/√1000 ≈ 0.045. Cluster means have variance 1 + 1/10 = 1.1, sd ≈ 1.049, so clustered_se ≈ 1.049/√100 ≈ 0.105. The ratio 2.35 matches √(1 + (m−1)ρ) = √5.5. Under the null the naive test rejects at |t| > 1.96; the true threshold is 1.96/2.35 ≈ 0.83, and P(|Z| > 0.83) ≈ 0.40. Nominal 5% becomes 40%.

What to do.

AssumptionSymptomFix
IndependenceSE too small, α inflatedCluster-robust SE, cluster-level permutation, mixed model
Normality of x̄p-values off at small n, heavy tailsBootstrap the mean, permutation test, more n
Equal variances (pooled)Wrong SE when group sizes differWelch's t-test (R's default, var.equal=FALSE)
Matched observationsBetween-pair variance inflates SEPaired t-test on differences

Trade-offs. Welch's is the right default for two independent samples: it costs almost nothing in power when variances are equal and is correct when they are not. Paired designs are strictly better when pairing is real, because they remove between-pair variance. Cluster-robust SEs need enough clusters, not enough observations: common guidance puts the floor around 40 clusters, and with 10 the interval is unreliable. Permutation at the cluster level is exact under exchangeability and needs no distributional assumption, but it tests a different null (exchangeability, not equal means). Mann-Whitney does not fix dependence and answers a different question: stochastic dominance, not a mean difference.

Detection. Compute ICC within clusters before trusting any SE; if it is non-trivial, the naive interval is wrong. Check skewness per group; if |skew| > 1 and n < 30, bootstrap. Plot the cluster means, not just the pooled histogram: the pooled view hides exactly the structure that breaks the test.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

How would you test a claim that the system depends on non-parametric alternatives?

Answer

Core answer

"The system depends on non-parametric alternatives" isn't testable as written: it names no metric, no decision, and no alternative. Pin it down first: for metric M, the ship/no-ship call flips when the rank test is replaced by its parametric counterpart, and the rank test is the one that's right. That is falsifiable, and testing it takes three steps.

  1. Enumerate the decision points. Grep the analysis code for every place a test is chosen (ttest_ind, f_oneway, pearsonr) and list the metric each one gates. The claim is per-metric, not global: a pipeline can depend on rank tests for latency and not at all for conversion rate.
  2. Run both tests on the same data and record the decision, not just the p-value. Disagreement is the signal.
  3. Where they disagree, arbitrate with a permutation test. Under exchangeability it is exact and assumes nothing about the distribution, so it settles which of the two is wrong.

Worked trace (hypothetical numbers, real pattern)

Latency A/B, n=40 per arm, right-skewed with a few 3-second outliers.

TestStatisticpWhat it licenses
Welch t-test on meanst=2.210.03"mean latency differs"
Mann-Whitney UU=6120.04"A stochastically greater than B"
Permutation, difference in means, 10k—0.14nothing
Permutation, difference in medians, 10k—0.05"median shifted"

The t-test and the rank test agree on "reject" and disagree on why. The permutation test on the mean says the mean difference is not established: it is carried by three tail points. The permutation test on the median confirms the bulk shifted. So the claim is half-true: the pipeline does depend on a rank-based view, but only because it reports a median. If it reported the mean, no test would support it.

Code for the arbiter:

Python
import numpy as np
rng = np.random.default_rng(0)

def perm_pvalue(a, b, stat, n_perm=10_000):
    obs = stat(a) - stat(b)
    pool = np.concatenate([a, b])
    n = len(a)
    count = 0
    for _ in range(n_perm):
        rng.shuffle(pool)                      # in-place, fresh uniform permutation each pass
        count += abs(stat(pool[:n]) - stat(pool[n:])) >= abs(obs)
    return (count + 1) / (n_perm + 1)          # add-one: never returns 0

perm_pvalue(a, b, np.mean) is the mean arbiter; np.median gives the median one. Checked against NumPy 1.26 / Python 3.11.

What it costs

Non-parametric is not free. Asymptotic relative efficiency of Mann-Whitney vs the t-test:

DistributionARE vs t-testSamples needed vs t-test
Normal3/π ≈ 0.955+4.7%
Uniform1.0same
Laplace1.5−33%
Exponential3.0−67%

If the metric is roughly normal, the rank test costs ~5% more samples for nothing. If it is exponential-tailed, which latency usually is, it buys a 3x efficiency gain. The deciding measurement is the tail of the actual metric, not a preference.

Failure modes

  • Testing the claim on the data that motivated it. The flip rate is then inflated by selection; hold out a window.
  • Reporting whichever test rejected. Under the null both reject at α, so they disagree at a nonzero rate even when the claim is false: bounded by 2α(1−α) ≈ 9.5% at α=0.05 if the tests were independent, less in practice because they are positively correlated. A flip rate near that baseline is noise, not dependency.
  • Silent swaps. If nobody logs which test ran, the dependency is invisible until a reviewer asks why the dashboard moved.

Detect it by logging test name, statistic, p-value and decision per metric per run, and alerting when the two disagree on a metric that gates a ship.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

What are the core differences between permutation tests and bootstrapping, and when should you choose one over the other?

Answer

Permutation tests and bootstrapping are both non-parametric resampling methods, but they target fundamentally different statistical questions through different sampling mechanisms.

A permutation test resamples without replacement across pooled groups under the sharp null hypothesis that the assignment labels are exchangeable ($H_0: F_A = F_B$). It builds the exact or Monte Carlo null distribution of a test statistic (like the difference in means or medians) assuming the treatment had zero effect on every individual observation. It yields an exact p-value for testing whether an effect exists, but does not naturally produce a confidence interval for the magnitude of that effect without computationally demanding test inversion.

Bootstrapping resamples with replacement within each group separately ($n_A$ from $A$, $n_B$ from $B$) to approximate the sampling distribution of an estimator $\hat{\theta}$. It models the population distribution $F$ via the empirical distribution $\hat{F}_n$. Its primary purpose is parameter estimation: calculating standard errors, bias, and confidence intervals for arbitrary statistics without requiring asymptotic normality.

Mechanism Comparison

PropertyPermutation TestBootstrap Resampling
Primary GoalHypothesis testing ($p$-value under $H_0$)Parameter estimation (SE, bias, confidence intervals)
MechanismSample pooled data without replacement; shuffle labelsSample each group with replacement from itself
Assumed NullExact exchangeability under $H_0$ ($Y_i \perp T_i$)No specific null assumed; models population variation
Core GuaranteeExact Type I error control at finite sample sizesAsymptotic consistency as $n \to \infty$

Minimal Implementation

Python
import numpy as np

rng = np.random.default_rng(42)
a = np.array([12.1, 14.3, 11.8, 13.9, 15.2])
b = np.array([15.5, 16.2, 14.8, 17.1, 16.0])
observed_diff = b.mean() - a.mean()

# 1. Permutation Test: Pool and resample without replacement
pooled = np.concatenate([a, b])
n_a = len(a)
perm_diffs = np.empty(10_000)
for i in range(10_000):
    shuffled = rng.permutation(pooled)
    perm_diffs[i] = shuffled[n_a:].mean() - shuffled[:n_a].mean()
p_val = np.mean(perm_diffs >= observed_diff)

# 2. Bootstrap: Resample each group with replacement
boot_diffs = np.empty(10_000)
for i in range(10_000):
    boot_a = rng.choice(a, size=len(a), replace=True)
    boot_b = rng.choice(b, size=len(b), replace=True)
    boot_diffs[i] = boot_b.mean() - boot_a.mean()
ci_95 = np.percentile(boot_diffs, [2.5, 97.5])

When to Choose Which

  • Choose a Permutation Test when running a hypothesis test on small sample sizes (e.g., $N < 30$), testing an A/B test with an unusual metric (e.g., ratio of medians), or when strict Type I error guarantees are mandatory under an exchangeable randomized design.
  • Choose Bootstrapping when you need an effect size estimate with confidence intervals (e.g., "latency improved by 42 ms [95% CI: 18 ms, 66 ms]"), when estimating variance or standard error of complex estimators, or when data is observational and groups are not exchangeable under a null condition.

Common Failure Modes

  1. Exchangeability Violation in Permutation Tests: If two groups have unequal variances under the null ($σ_A^2 \neq σ_B^2$) or cluster correlation, simple permutation inflates Type I error because units are not exchangeable.
  2. Small-Sample Bootstrap Confidence Intervals: At very small $n$ ($n < 15$), empirical distributions poorly represent tail behavior, leading naive percentile bootstrap intervals to under-cover nominal rates (often achieving $<90%$ coverage for nominal $95%$ intervals).

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

When does the non-parametric bootstrap fail for estimating confidence intervals, and how do you diagnose those failures in production data?

Answer

The non-parametric bootstrap requires observations to be independent and identically distributed (i.i.d.), the statistic to have a smooth plug-in distribution (finite variance), and the empirical distribution function $\hat{F}_n$ to be an accurate surrogate for the true distribution $F$.

It breaks down across four specific failure modes:

  1. Extreme Order Statistics (Min/Max or High Quantiles): Estimating the maximum $\theta = \max(X)$ on $U(0, \theta)$ fails because the bootstrap maximum $\max(X^)$ cannot exceed the sample maximum $\max(X)$. In fact, $P(\max(X^) = \max(X)) = 1 - (1 - 1/n)^n \approx 1 - 1/e \approx 0.632$. The bootstrap distribution has a point mass at the sample maximum and zero support above it, destroying coverage.
  2. Heavy Tails (Infinite Variance): If data follow a Pareto or Cauchy distribution where $E[X^2] = \infty$, the central limit theorem does not govern the sample mean. The bootstrap distribution of the standardized mean fails to converge to the true limit distribution.
  3. Clustered or Dependent Data: In A/B tests with multiple actions per user, resampled rows assume independence. If intra-cluster correlation $\rho > 0$, standard errors are underestimated by roughly $\sqrt{1 + (m - 1)\rho}$ for average cluster size $m$, leading to severely anti-conservative confidence intervals.
  4. Small Sample Sizes / Boundary Parameters: For $n < 30$, basic percentile intervals perform poorly due to bias and skewness.

Diagnosis and Detection

Python
import numpy as np
from scipy import stats

def diagnose_bootstrap(data, stat_fn, B=2000, rng_seed=42):
    rng = np.random.default_rng(rng_seed)
    n = len(data)
    boot_stats = np.array([stat_fn(rng.choice(data, size=n, replace=True)) for _ in range(B)])

    # 1. Check for discrete mass / boundary pinning
    unique_ratio = len(np.unique(boot_stats)) / B

    # 2. Check jackknife influence values for extreme tail points
    jack_stats = np.array([stat_fn(np.delete(data, i)) for i in range(n)])
    theta_jack_mean = np.mean(jack_stats)
    u = (n - 1) * (theta_jack_mean - jack_stats)  # Infinitesimal jackknife values
    acceleration = np.sum(u**3) / (6.0 * (np.sum(u**2))**1.5)  # 'a' in BCa

    return {"unique_ratio": unique_ratio, "bca_accel": acceleration, "boot_skew": stats.skew(boot_stats)}
Failure ModeDiagnostic IndicatorCorrective Action
Extreme Values (p99.9, Max)unique_ratio is low; ties dominate resamplesExtreme Value Theory (EVT/GPD) or parametric estimation
Heavy Tails ($E[X^2] = \infty$)Quantile-Quantile plot curvature; $m$-out-of-$n$ bootstrap ($m \ll n$) stabilizes variance$m$-out-of-$n$ bootstrap or robust M-estimators
Clustered ActionsIntraclass correlation coefficient (ICC) $> 0$Block/Cluster bootstrap resampling at cluster level
Skewness / BiasBootstrap distribution skew $\neq 0$, acceleration $a

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

How does a mismatch between the unit of randomization and unit of analysis affect hypothesis testing, and how do you correct for it?

Answer

A mismatch occurs when the entity randomized (e.g., user, classroom, device) differs from the entity measured during inference (e.g., page view, click, session). When randomization occurs at a higher level than analysis, individual observations within each randomization cluster share latent traits and violate the assumption of independent and identically distributed (i.i.d.) observations.

The Mechanism: Pseudo-Replication and Type I Error Inflation

When units within a cluster are positively correlated, the intraclass correlation coefficient (ICC, $\rho$) is positive:

$$\rho = \frac{\sigma^2_b}{\sigma^2_b + \sigma^2_w}$$

where $\sigma^2_b$ is between-cluster variance and $\sigma^2_w$ is within-cluster variance. Standard variance formulas treat sample size as the total number of sub-units $N$. The effective sample size is actually:

$$N_{\text{eff}} = \frac{N}{1 + (m - 1)\rho}$$

where $m$ is the average cluster size. The term $1 + (m - 1)\rho$ is the design effect (variance inflation factor).

If $m = 20$ views per user and $\rho = 0.20$, the variance inflation factor is $1 + (19 \times 0.20) = 4.8$. Unadjusted standard errors are underestimated by $\sqrt{4.8} \approx 2.19\times$. A nominal 5% significance test will reject the null hypothesis under $H_0$ up to 20–30% of the time, producing severe false positive inflation.

True Data Generating Process:
Cluster (User) level:  Randomized to Control / Treatment
      │
      ├─ View 1 (correlated)
      ├─ View 2 (correlated)  ──>  Naive test assumes N = 10,000
      └─ View m (correlated)       True independent signal is N_clusters = 500

Corrections

Correction MethodMechanismTrade-off / Limitation
Cluster-Level AggregationCollapse metric to cluster mean or total (e.g., CTR per user) and run a t-test across clusters.Simple and unbiased; loses statistical power if clusters vary wildly in size without weighting.
Cluster-Robust Standard Errors (CRVE / Sandwich)Replaces diagonal residuals with outer products of cluster-level residual sums ($G^{-1}(\sum u_g u_g')G^{-1}$).Asymptotically valid; anti-conservative when cluster count $G < 50$ (requires wild cluster bootstrap).
Delta Method / Ratio MetricsLinearizes ratio metrics ($Y/X$) around expectations using Taylor expansion at the cluster level.Scales well to billions of events; requires accurate estimation of covariance between numerator and denominator.
Linear Mixed-Effects Models (LMM)Models random intercepts per cluster ($y_{ij} = \beta_0 + \beta_1 X_j + u_j + \epsilon_{ij}$).Efficient and flexible; higher compute latency, relies on parametric random-effect distribution assumptions.

Practical Implementation

In online experimentation, ratio metrics (e.g., total clicks / total page views randomized by user) are corrected using cluster-robust standard errors via statsmodels or the delta method:

Python
import statsmodels.formula.api as smf

# Linear regression clustered at the unit of randomization (user_id)
model = smf.ols("clicked ~ treatment", data=df)
result = model.fit(cov_type="cluster", cov_kwds={"groups": df["user_id"]})

If clustering occurs in the opposite direction (randomizing views but analyzing users), spillover and dilution occur because a single user experiences both treatment and control.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

How does repeated peeking inflate Type I error in an A/B test, and what mathematical methods prevent it?

Answer

Peeking is continuously evaluating a fixed-sample hypothesis test as observations arrive and stopping early the moment $p < \alpha$. Fixed-sample tests (like standard two-sample $z$- or $t$-tests) assume the sample size $N$ is set in advance independent of the data. When an engineer monitors cumulative data at intermediate steps $k = 1, \dots, K$, the test statistic performs a random walk across time.

Mechanism of Error Inflation

Under the null hypothesis $H_0$, even if the probability of a false positive at any single planned check is $\alpha = 0.05$, intermediate statistics are autocorrelated across cumulative samples. The actual Type I error rate becomes the probability of the union of threshold-crossing events: $$ P\left(\bigcup_{k=1}^K {|Z_k| \ge z_{1-\alpha/2}}\right) > \alpha $$ By the Law of the Iterated Logarithm, the cumulative sum $S_n = \sum_{i=1}^n X_i$ under $H_0$ (with mean $0$ and variance $\sigma^2$) satisfies $\limsup_{n \to \infty} \frac{|S_n|}{\sqrt{2 n \sigma^2 \log \log n}} = 1$. Consequently, if you peek indefinitely and stop whenever $|Z_n| \ge 1.96$, you will reject $H_0$ with probability $1$ even when there is no true effect.

Simulated Type I Error Rate vs Number of Looks (Nominal alpha = 0.05)
Looks (K) | False Positive Rate
---------|--------------------
1 (Fixed)|  5.0%
5        | 14.2%
10       | 19.3%
50       | 32.0%
100      | 37.5%

Mathematical Mitigations

To allow valid continuous monitoring or early stopping, you must adjust the decision boundaries:

  1. Group Sequential Designs via $\alpha$-Spending Functions (Lan-DeMets): Allocate the total false positive budget $\alpha$ across continuous information fractions $\tau = t/T \in (0, 1]$ using a non-decreasing spending function $\alpha^(\tau)$ where $\alpha^(0) = 0$ and $\alpha^*(1) = \alpha$.

    • O'Brien-Fleming type: Spends very little $\alpha$ early (${\tau \le 0.5}$) to keep the boundary conservative when sample sizes are small, preserving statistical power at the final planned sample.
    • Pocock type: Spends $\alpha$ more uniformly, yielding flatter critical values across time but requiring a higher overall sample size for the same power.
  2. Sequential Probability Ratio Test (SPRT) & Mixture SPRT (mSPRT): Rather than evaluating $p$-values against a static cut-off, compute the likelihood ratio $\Lambda_n$ of observations under $H_1$ vs $H_0$. By Wald's SPRT, early stopping occurs when: $$ \Lambda_n = \prod_{i=1}^n \frac{f_1(x_i)}{f_0(x_i)} \ge \frac{1-\beta}{\alpha} $$ For continuous experimentation where the true effect size is unknown ahead of time, mSPRT integrates the likelihood over a mixing distribution $H(\theta)$ for the effect size (e.g., normal prior $N(0, \tau_0^2)$). By Ville's inequality for non-negative martingales, $P(\exists n: \Lambda_n \ge 1/\alpha) \le \alpha$, guaranteeing anytime-valid inference without a predefined stopping time.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

What failure would you inject to check a team's understanding of sequential testing done correctly?

Answer

The failure to inject is a perfect null run through a peeking, fixed-sample analysis. Ship this ticket:

EXP-4471, "checkout copy reorder". Treatment differs from control by a comment in the source; the served artifact is byte-identical. Primary metric: 7-day conversion per user. The dashboard refreshes hourly and flags the primary metric with a fixed-sample two-sided test at alpha = 0.05 on the cumulative data, resliced into 20 segments (5 platforms x 4 locales). No planned end date. The decision owner calls it when it looks significant.

Nothing is broken in the product. Everything is broken in the readout. A team that understands sequential testing tells you the analysis will declare a winner on a null, and roughly how often.

Why it will: a fixed-sample test is calibrated for one look. Applied at every look it spends the error budget repeatedly, and this dashboard does it hourly. Under a true null with K equally spaced looks, two-sided:

Looks KP(at least one look p < 0.05)
10.05
20.08
50.14
100.19
200.25

Rounded values from the classic repeated-significance tables (Armitage, McPherson and Rowe, 1969); treat them as the design target, not a measurement.

As the looks get dense the running statistic behaves like Brownian motion and the probability of ever crossing 1.96 tends to 1: with hourly refresh and no end date there is effectively no outcome in which this experiment fails to find a winner. The 20 slices compound it. Twenty-one tests per look at 5% is 1 - 0.95^21 = 0.66 chance of at least one "significant" segment in a single refresh, treating the slices as independent: they are not, but the direction of the error is right.

What separates the levels:

  • Fail: "p = 0.03, ship it", or "peek daily and stop when significant".
  • Pass: "that is peeking; 5% per look is not 5% overall; the null will flag anyway".
  • Strong: predicts the rate (~0.25 at 20 looks), names the fix by mechanism, and adds the second-order point. Estimates read at the stopping time are biased, so the winning slice reads larger than the truth because you stopped when it peaked.

The order matters more than the vocabulary. A team that says "we will switch to a confidence sequence" after watching the p-value climb has fixed nothing; changing the test in response to the data is the failure, not the repair. Ask when the method gets chosen and the answer should be "before enrollment".

Second injection, if the first passes: keep the hourly refresh, swap in a correct always-valid sequence, and seed a real effect of +0.2% relative. Now a genuine win sits under the wider boundary and reads "not yet significant". A team that understands the guarantee knows the price (wider intervals, more sample for the same power) and says so rather than ripping out the sequence when the number it wanted does not appear.

Calibration, if you want the number rather than the theory: replay 1000 simulated nulls through the team's actual analysis code and count the fraction where any look returned p < 0.05. A correct pipeline reads about 0.05; the injected one reads about 0.25 at 20 looks. Run the pipeline, not a reimplementation: the pipeline is the thing under test.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

An experiment was stopped early because the result looked significant. What can you still conclude, and what pre-commitments would have made that decision defensible?

Answer

An experiment stopped early because p < 0.05 cannot be read off that p-value. A p-value is calibrated for a fixed sample size; if you looked at the data and stopped because it looked good, the nominal p is not the false-positive probability under the null. What you can conclude depends on whether the stopping rule existed before the data.

  • Pre-specified rule, boundary crossed: confirmatory. Report the adjusted p-value and the boundary-crossing confidence interval from the same sequential design.
  • Pre-specified rule, boundary not crossed: you have not rejected the null. Continue to the next look or the planned end.
  • No pre-specified rule: exploratory only. Report the observed effect and an unadjusted interval, label both as biased, and do not ship on them.

Why the nominal p is wrong. Under the null the test statistic is a random walk in information time; each peek is a correlated draw, not an independent test. Testing at alpha = 0.05 at every look inflates the overall false-positive rate: 5 equally spaced looks give about 14%, 10 looks about 19%. The observed effect is also biased upward, the winner's curse, because you stopped on a high draw.

Worked example: O'Brien-Fleming, 5 looks. OBF spends alpha conservatively early and most of it at the end. For K = 5 equally spaced looks at two-sided alpha = 0.05, the boundary at look k is c / sqrt(t_k) with c about 2.04 (O'Brien & Fleming 1979; tabulated in Jennison & Turnbull):

LookInformation tBoundary zNominal two-sided p
10.204.565.1e-6
20.403.231.2e-3
30.602.638.5e-3
40.802.282.3e-2
51.002.044.1e-2

Planned 5 looks, stopped at look 3 with z = 2.17 (nominal p = 0.030). The boundary at look 3 is 2.63, so you have not crossed it; the adjusted p-value exceeds 0.05 and you cannot reject the null. Continue to look 4. The naive p = 0.030 is exactly the number that makes this trap dangerous.

Pre-commitments that make an early stop defensible

  • Fixed maximum sample size and duration from a power analysis for the minimum detectable effect.
  • A stopping rule: an alpha-spending function or group-sequential boundaries (O'Brien-Fleming, Pocock), or a sequential probability ratio test. Pocock uses a constant boundary, spends alpha more evenly, and stops earlier, but needs a larger maximum sample size than OBF.
  • A named decision owner and the exact criterion: adjusted p crosses the boundary, or a harm signal fires.
  • Pre-registration: primary metric, analysis plan, and how multiple metrics are handled.

Failure modes. Shipping a false positive: detected by a holdout or a fresh confirmatory experiment. Stopping for harm and then not acting because the p-value isn't adjusted: harm signals usually use a separate, more permissive threshold and a safety monitor. Reporting a naive confidence interval after an early stop: it is too narrow and centered on an inflated effect.

If you didn't pre-specify, use the data to design a confirmatory experiment, not to decide. Report the effect with an unadjusted interval and say it is likely inflated. For harm, act immediately but report the evidence as weak and follow up.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

When would you refuse a design because of bonferroni and false-discovery control?

Answer

Refuse the design, not the method. Two conditions decide it.

Refuse Bonferroni when the family is large and you expect more than one real effect. Bonferroni sets the per-test threshold at α/m. At m=200, α=0.05, that is 0.00025 per test. Worked example: a two-proportion A/B test, baseline 5%, a real 10% relative lift (5.0%→5.5%), 20,000 users per arm. The effect sits 2.24 standard errors out. At α=0.05 that is 61% power; at 0.00025 the critical z is 3.66 and power falls to about 8%. Restoring 80% power needs roughly 81,000 per arm: 4× the traffic. If the design ships 200 metrics under Bonferroni and the team expects a handful of real wins, it is dead on arrival: it finds nothing, and the null result gets misread as "no effect."

Refuse FDR when a single false positive is unacceptable. Benjamini-Hochberg controls E[V/R] ≤ α: the expected proportion of false discoveries among rejections. It permits false positives. For a safety endpoint, a regulatory claim, or a single primary metric where one wrong "ship it" is the failure, that is the wrong guarantee. Use family-wise control there.

Mechanism. Bonferroni is a union bound: P(any false positive) ≤ Σ P(reject H_i | H_i true) ≤ m·(α/m) = α. No dependence assumption, and it pays for that with power. BH works on ranked p-values: sort ascending, find the largest k with p_(k) ≤ k·α/m, reject the first k. The threshold grows with rank, so it tolerates a few small p-values among many. It controls FDR under independence or PRDS, not arbitrary dependence, if you cannot argue PRDS, use Benjamini-Yekutieli, which multiplies by Σ1/i ≈ ln m and costs power accordingly.

BH does not rescue the single-effect case: with one true effect among 200 nulls, the smallest p-value still has to clear 1·α/200 = 0.00025, identical to Bonferroni. BH's advantage appears only when a real fraction of hypotheses are non-null.

Python
from statsmodels.stats.multitest import multipletests
# m=200, alpha=0.05
multipletests(pvals, alpha=0.05, method="bonferroni")  # per-test 0.00025
multipletests(pvals, alpha=0.05, method="fdr_bh")      # ranked thresholds k*alpha/m
multipletests(pvals, alpha=0.05, method="fdr_by")      # arbitrary dependence

Other refusals. Refuse either method if the family is not fixed before looking: choosing m after seeing results voids the guarantee. Refuse both as a fix for peeking: they correct for multiplicity, not optional stopping; continuous monitoring needs a sequential method (alpha spending, group-sequential boundaries). Refuse BH on strongly dependent p-values without a PRDS argument.

Detection. Pre-register the family and the method. Before launch, simulate power at the planned n and m, if Bonferroni power is under ~20%, the design cannot answer the question. After, check the p-value histogram: nulls uniform, true effects pile near zero; a flat histogram under Bonferroni means you screened nothing.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

What is the smallest experiment that would change your mind about the garden of forking paths?

Answer

The smallest experiment is a null simulation you can run in an afternoon: no new data, one script.

Fix a data-generating process with no true effect: two groups of 40 draws from the same N(0,1). Enumerate the analysis space you would actually consider if the result mattered. For each simulated dataset, compute every analysis, keep the smallest p-value, and count how often it clears 0.05. That fraction is the false-positive rate of your forking paths. If it comes back at 5%, the worry is wrong for your space and I would drop it. If it comes back at 30%, it is confirmed and quantified.

Why selection inflates. You are taking a maximum over many statistics computed on the same data. If the 24 analyses were independent, P(at least one p < 0.05) = 1 − 0.95^24 = 0.709. They are not independent, they share the same 80 observations, so the real rate sits below that bound. The experiment exists to measure the gap between 0.709 and the truth, because that gap is the whole argument.

Python
import numpy as np
from scipy import stats

rng = np.random.default_rng(0)

def p_values(x, y):
    out = []
    for drop in (None, 2.5, 3.0):              # outlier rule
        for log in (False, True):              # transform
            for metric in ("mean", "trim10"):  # metric
                for frac in (1.0, 0.8):        # window
                    a, b = x.copy(), y.copy()
                    if drop is not None:
                        a = a[np.abs(stats.zscore(a)) < drop]
                        b = b[np.abs(stats.zscore(b)) < drop]
                    if log:
                        a, b = np.log1p(a - a.min()), np.log1p(b - b.min())
                    n = int(len(a) * frac)
                    a, b = a[:n], b[:n]
                    if metric == "trim10":
                        k = int(0.1 * len(a))
                        a, b = np.sort(a)[k:len(a)-k], np.sort(b)[k:len(b)-k]
                    out.append(stats.ttest_ind(a, b, equal_var=False).pvalue)
    return out

hits = sum(min(p_values(rng.normal(0, 1, 40), rng.normal(0, 1, 40))) < 0.05
           for _ in range(10_000))
print(hits / 10_000)

Trace: 3 × 2 × 2 × 2 = 24 analyses per run, 10,000 runs, 240,000 t-tests. The loop draws fresh x and y each iteration, so every run is an independent null dataset. The printed number is the fraction of runs where at least one of the 24 clears 0.05. Illustratively (an expectation to check, not a result I have run) a space this correlated lands in the 0.15–0.35 band, well under the 0.709 independence bound.

What would change my mind. A measured rate near 0.05 would falsify the claim for this space: the analyses would have to be so correlated that selection buys almost nothing. A rate of 0.30 confirms it and tells you the size of the correction.

Alternatives and when to use them. Pre-registration removes the space entirely, but you cannot pre-register an analysis you have not thought of, and it costs you the discovery the exploration was for. A specification curve reports all 24 p-values instead of the minimum; it is honest but pushes the aggregation onto the reader. The deciding criterion is whether the reported analysis was chosen by a rule that is a function of the data. If it was, you need the simulation or the curve. If it was fixed before, you need neither.

Failure modes. The simulation has its own garden: you picked the 24 analyses, and a different 24 gives a different rate. Detect this by reporting the specification curve, not just the minimum. And the null simulation only bounds the error rate; with a real effect, the same selection inflates the reported effect size (winner's curse), which you detect by comparing the selected estimate against the pre-registered one.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

What trade-off does practical equivalence testing force that a junior answer usually skips?

Answer

The trade-off is this: equivalence testing forces you to commit to the smallest difference that matters before you see the data, and that one number dictates your cost. Tighten the margin you want to defend by 2x and you need 4x the samples. There is no cheap test that yields a tight equivalence claim. Juniors skip it because they treat "equivalent" as a property to be discovered rather than a threshold to be declared, so they never hit the question of what the threshold costs.

Mechanism, briefly. You declare an interval [-m, +m] meaning "no meaningful difference." TOST runs two one-sided tests (H0: delta <= -m, and H0: delta >= +m) each at alpha/2, and calls equivalence only if both reject. The equivalent view, and the one to keep in your head: compute the 95% CI for the difference and check that it lies entirely inside [-m, +m]. That framing shows instantly why a wide CI answers nothing.

For a two-arm comparison at 80% power with each side at alpha = 0.025:

n per arm  =  2 * (1.96 + 0.84)^2 * sigma^2 / m^2  =  15.7 * sigma^2 / m^2

Assume sigma = 20 ms of latency jitter (hypothetical, but the shape is the point):

Margin mn per armWhat you can claim
2 ms15.7 * 100 = 1568Tight claim, expensive
5 ms15.7 * 16 = 251Usually the sweet spot
10 ms15.7 * 4 = 63Cheap, and often says nothing a stakeholder cares about

The quadratic is unforgiving. The alpha split costs you too: running each side at 0.05 instead of 0.025 drops 251 to 198 per arm, but pushes your false-equivalence rate from 5% to 10%. About 27% more samples buys the honest error rate.

Python
# Python 3.12, NumPy 2.x, SciPy 1.14; only long-stable APIs.
import numpy as np
from scipy import stats

def tost(a, b, margin, alpha_per_side=0.025):
    n1, n2 = len(a), len(b)
    s1, s2 = a.var(ddof=1), b.var(ddof=1)
    d = b.mean() - a.mean()
    se = np.sqrt(s1 / n1 + s2 / n2)
    df = (s1 / n1 + s2 / n2) ** 2 / ((s1 / n1) ** 2 / (n1 - 1) + (s2 / n2) ** 2 / (n2 - 1))
    crit = stats.t.ppf(1 - alpha_per_side, df)   # 0.025 -> 95% CI
    lo, hi = d - crit * se, d + crit * se
    return lo, hi, (lo > -margin and hi < margin)

With 63 samples per arm, sigma = 20 ms, the standard error is 20 * sqrt(2/63) = 3.56 ms and crit = 1.979, so the CI half-width is 7.05 ms. An observed difference of +1.2 ms gives [-5.85, +8.25]: equivalent at m = 10 ms, inconclusive at m = 5 ms.

Alternatives. A non-inferiority test bounds only one direction, is one-sided, and costs roughly a quarter fewer samples: right when "no worse than baseline" is the real requirement and a faster candidate is unambiguously fine. A Bayesian ROPE needs the same margin and gives a posterior probability instead of a binary, but the sample-size curve is the same shape.

Failure modes, and how you catch them.

  • Setting the margin after seeing the CI. Nominal error rates no longer hold: you've drawn an interval and renamed it a spec. Catch it by requiring the margin with a timestamp before the first sample, in the experiment spec, not the analysis notebook.
  • Reading an inconclusive TOST as "not equivalent." At m = 2 ms with 50 per arm, the CI half-width is about 8 ms, so neither null can be rejected whatever the truth is. Catch it by comparing CI half-width against m before you run; if it exceeds m, collect more or widen the margin: otherwise the finding is "inconclusive," never "different."
  • Treating p = 0.3 from a difference test as equivalence. Ten per arm at sigma = 20 ms only detects differences near 25 ms; it cannot separate 0 ms from 20 ms.

A senior answer picks the margin from the decision it drives (SLA headroom, cost per request, the point where users notice) sizes the test before it starts, and if the traffic isn't there, says so and either accepts a wider margin or runs the directional test instead. The trade-off doesn't go away; it just usually gets made silently.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

What would you ask a candidate who recites bayesian alternatives but cannot apply it?

Answer

The reciter can name the framework; the applier can produce a number and defend the assumption behind it. So I never ask "what's the Bayesian alternative to a p-value?": that question is answerable by recitation. I ask for a posterior on a concrete dataset, then move the prior, then move the stopping rule.

Question 1: produce the number. "Two arms, 120 conversions in 2,000 and 140 in 2,000. With a Beta(1,1) prior, what's P(treatment is better)?"

The reciter says "you'd use a Beta-Binomial model" and stops. The applier writes the posteriors: Beta(1+120, 1+1880) = Beta(121, 1881) and Beta(141, 1861). Means 0.0604 and 0.0704. The difference has sd ≈ 0.0078, so z ≈ 1.28 and P ≈ 0.90. That is the number a p-value never hands you.

Question 2: move the prior. "Same data, prior Beta(10,10). Does the answer move?" This is the sensitivity check. Beta(10,10) adds 10 pseudo-successes and 10 pseudo-failures per arm: posteriors Beta(130, 1890) and Beta(150, 1870), means 0.0644 and 0.0743, difference 0.0099, sd ≈ 0.0080, z ≈ 1.24, P ≈ 0.89. It barely moves, because 2,000 observations swamp a 20-pseudo-count prior. A reciter cannot tell you whether the prior matters; an applier shows it doesn't here and can say when it would: small n, or a prior that fights the data.

Question 3: the stopping rule. "You peeked five times and stopped when it looked good. Does the posterior change?" The reciter gives the slogan: "Bayesian methods don't care about peeking." The applier separates two claims: the posterior given the data does not depend on the stopping rule, but the error rate of any decision rule you build on top of it does, and that has to be simulated. That distinction is the whole point of the question.

Question 4, when not to. "When would you not reach for this?" Forces a trade-off instead of a preference.

PromptReciterApplier
P(treatment better)?"Beta-Binomial"0.90, from Beta(121,1881) vs Beta(141,1861)
Prior sensitivity?"priors matter"0.90 → 0.89 under Beta(10,10)
Peeking?"Bayesian doesn't care"posterior yes, decision-rule error rate no
When not?"it's better"small n, or when you need a calibrated frequentist guarantee

The interviewer's own failure mode is asking a question whose answer is a framework name. Detection is simple: if the candidate never writes a distribution or a number, you have learned nothing about application.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

How would you review a pull request whose risk is confidence intervals as the primary report?

Answer

I read the analysis code before the numbers. A confidence interval is only as good as the method that produced it, and the review is where you catch a method that doesn't match the metric. The PR is mergeable when the interval's construction fits the sampling distribution, the level and scale are stated, and the report says what a reader does when the interval excludes zero.

Three assumptions I state up front: what decision the report feeds (ship/no-ship, or a dashboard nobody acts on), whether the metric is a mean of a bounded variable or a ratio/heavy-tailed one, and whether the analysis runs once at a fixed sample size or recomputes every day.

Then I walk the diff against this:

CheckWhat I look forAsk if missing
Methodt/normal for a mean; bootstrap or delta method for a ratio"Which method, and what justifies it for this metric?"
Level95% stated once and used consistently"Is this two-sided?"
Scaleabsolute vs relative, with units"Is +2.1% the lift or the raw delta?"
Decision rulewhat "excludes zero" means for shipping"What do we do at the lower bound?"
Multiplicityhow many metrics, any correction"Twenty metrics at 95%..."
Sequentialfixed-sample or always-valid"Does this recompute daily?"

The most common defect is a normal-approximation interval on a ratio metric. This diff:

Python
lift = (treat.mean() - ctrl.mean()) / ctrl.mean()
se = np.sqrt(treat.var()/n_t + ctrl.var()/n_c) / ctrl.mean()
ci = (lift - 1.96*se, lift + 1.96*se)   # relative lift

treats the denominator as a constant. It isn't: ctrl.mean() has its own variance, and the delta method carries a term for it. The interval comes out too narrow, so a null result can look decisive. Detection: bootstrap the same data and compare; if the analytic interval is materially tighter, the approximation is the problem, not the effect.

Two more failure modes worth naming. Peeking: if the job recomputes this interval every day and the team ships the first day it excludes zero, the nominal 95% is not 95%. A fixed-sample interval read repeatedly inflates the false-positive rate. Detect it by checking whether the analysis is scheduled or one-shot. Multiplicity: with 20 independent metrics at 95%, P(at least one excludes zero by chance) = 1 - 0.95^20 ≈ 64%. If the PR reports 20 intervals and no correction, the "significant" one is expected noise.

The trade-off I'd put to the author: intervals alone versus intervals plus a p-value. Intervals alone are better when the reader needs the effect size and the decision has a threshold: a lift whose lower bound sits below the minimum effect that justifies shipping is not shippable even though it excludes zero. A p-value adds nothing there. But if the report feeds an automated gate that only reads a boolean, keep the p-value alongside so the gate and the human read the same verdict. My deciding criterion is the consumer: a human deciding on magnitude gets the interval; a machine reading a flag gets both.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

What belongs in a runbook section on the significance threshold is a convention, and what does not?

Answer

The 90-second answer

A runbook section on the significance threshold should be split into two labelled blocks, because the lines are not the same kind of claim. The convention block holds the choices you can change without breaking the test: the value of α (0.05 is Fisher's convenience, not a law), the power target (0.8 is Cohen's rule of thumb), the test statistic, and the guardrail metric list. The invariant block holds what stays true whatever you pick: under the null the p-value is uniform on [0,1], so P(p < α | H0) = α exactly; α bounds the false-positive rate and says nothing about power; and α is fixed before the first look at the data. The test for which block a line belongs in: if you can move it into the convention block without changing the error rates, it is convention; if moving it changes the error rates, it is not.

Runbook lineConvention?Why
α = 0.05YesAny pre-registered α is defensible; 0.05 is a habit
α = 0.01 for irreversible changesValue: yes. Direction: noLower α buys safety with power; the cost asymmetry forces the direction
"reject when p < α"NoDefinition of the test; P(reject | H0) = α exactly
Fix α before data collectionNoOptional stopping inflates the false-positive rate
Power target 0.8YesCohen's rule of thumb
Guardrail metric listYesDomain choice, not statistics

Arithmetic for the invariant: ten independent interim looks at α = 0.05 gives a family-wise false-positive rate of 1 − 0.95^10 ≈ 0.40. A runbook that says "check daily for ten days, stop when p < 0.05" is not a 5% test; it is a 40% test. That number does not move when you change the convention.

Failure modes, with detection:

  • Optional stopping. Count looks in the experiment log against the α-spending schedule; alert when looks exceed the plan.
  • Threshold drift between the runbook and the tooling default. Assert the configured α in CI against the runbook value.
  • Cost-blind threshold: 0.05 applied to an irreversible pricing change. Require a cost-ratio field in the experiment plan; a missing field fails plan review.

Runbook entry:

YAML
significance:
  alpha: 0.05             # convention: pre-registered, changeable
  fixed_before_look: true # invariant: do not edit after first look
  looks_planned: 1        # invariant: >1 requires alpha spending
  power_target: 0.80      # convention
  cost_ratio_fp_fn: 1.0   # drives alpha; required field

What does not belong: a line that states the threshold as a property of the data ("significant at 5%") without the pre-registration and look count beside it, and any line that changes α mid-experiment.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

How would you brief product on why assumption checking delays a ship date?

Answer

The 90-second version

Don't brief the statistics. Brief the decision, the date, and the cost of being wrong.

"Friday we planned to ship the new checkout. The test says +3.1% revenue per user. That number assumes the two groups' revenue varies the same way. Ours doesn't: the treatment arm has a handful of large orders the control arm doesn't. Under that condition the test's 5% false-positive rate isn't 5%; it's closer to 11%. So the honest read is: the lift is somewhere between -1% and +7%, and I can't tell you which side of zero we're on. Two days of re-analysis, Welch's t-test plus a bootstrap on the revenue metric, turns that into a number you can ship on. Ship Friday on the current number and we're making a hard-to-reverse change on a coin flip."

That's the whole brief. Everything after is answering questions.

(Numbers above are hypothetical; the mechanism: Student's t inflating the false-positive rate when variances and group sizes are unequal: is not.)

Why the two days, concretely

Assumption checking isn't one step. It's diagnose → re-analyze → re-decide, and each has a cost:

StepWhat it isTime
DiagnoseWhich assumption fails, how badly, on which metric2-3 h
Re-analyzeWelch, bootstrap CI, or a variance-stabilising transform4-6 h
Re-decideRe-run the ship/no-ship call on the corrected interval1 h
BufferThe corrected interval moves the answer and someone re-litigates1 day

The buffer is the part engineers forget to quote and the part that actually slips.

The arithmetic you show product

naive Student t-test:   p = 0.031   -> "ship"
Welch (unequal var):    p = 0.084   -> "don't ship yet"
bootstrap 95% CI:       [-0.9%, +7.2%]  -> point estimate alone doesn't decide it

One line: the method choice moved the p-value across the threshold. That's not pedantry; that's the difference between shipping and not.

Trade-offs, when not to delay

Delay is only worth it when the decision is hard to reverse. If the change sits behind a flag and ships to 5% of traffic, ship Friday and let the guardrail metric (revenue per user, refund rate) run for a week: you get the same information without spending the date. If it's a one-way door (pricing, a contract, a migration) the two days are cheap against the cost of being wrong.

Failure modes

  • Briefing the math. Product hears "the engineer is being precious" and escalates. Lead with the decision and the date; the statistics are the evidence, not the message.
  • Giving a date with no reason. "Two more days" invites "why?" and then you're defending a method instead of a decision. Give the date and the reason in the same sentence.
  • Letting product pick the method. They'll pick the one that ships. You own the method; they own the risk appetite.
  • Shipping on the naive number. Detection: the guardrail metric regresses 2-3 weeks later, after the change is baked into the roadmap, and the rollback is now a project.

What "done" looks like

You've briefed well when product can repeat back: what we're deciding, what number we'd ship on, what number we have, and what the two days buy. If they can't, you briefed statistics.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

How does replication interact with rollback, and where do people ignore that?

Answer

The 90-second answer

"Replication" and "rollback" meet in three places, and which one you get depends on the replication you mean. Physical replication ships the primary's write stream; logical replication ships only committed transactions. So the first thing to pin down is whether a rolled-back transaction is visible to the replica at all.

Direct answer: in PostgreSQL physical streaming replication a rolled-back transaction is replicated. Its WAL records stream to the replica, which applies them, then applies the abort record and marks the changes dead. In MySQL the binary log is written at commit, so a rolled-back transaction never reaches a replica. On failover, any transaction without a commit record in the replicated stream is rolled back during crash recovery, and that is where the client-visible ambiguity lives.

Mechanism

PostgreSQL writes WAL as changes happen, for durability, and the WAL sender streams it as it is flushed. A transaction that later aborts has already emitted heap inserts and index inserts. The replica replays all of it, then hits the ABORT record and marks those tuples dead. The work is done and undone. A 50 GB bulk load that rolls back at the end still costs the replica 50 GB of writes and leaves dead tuples for autovacuum.

MySQL is different: InnoDB writes the transaction to the binary log at commit, so an aborted transaction produces no binlog events and replicas never see it. PostgreSQL logical replication behaves the same way: logical decoding only emits committed transactions.

ReplicationRolled-back txn reaches replica?Cost of a large rollback on the replica
PostgreSQL physical (WAL streaming)Yes: records streamed, then abort replayedFull I/O plus dead tuples until vacuum
PostgreSQL logicalNo: only committed txns decodedNone
MySQL binlog (ROW)No: binlog written at commitNone

Failover: where the commit goes

Trace: async streaming replication, replica lag 200 ms, synchronous_commit=on (local flush only).

  • t=0 ms: client sends COMMIT.
  • t=2 ms: primary flushes the commit record locally and returns success.
  • t=100 ms: primary crashes; the WAL sender had not shipped the commit record.
  • t=5 s: replica promoted; crash recovery replays to the last valid record, finds no commit record, rolls the transaction back.

The client saw success. The row is gone. RPO is bounded by replication lag: here up to 200 ms of committed transactions.

With synchronous_standby_names set and synchronous_commit=on, the primary waits for the standby to flush before acking: RPO=0, but every commit pays one network round trip (roughly 0.5 ms in-region, ~30 ms cross-region). That is the trade.

Failure modes and how to detect them

  1. Replica bloat and lag from aborted bulk work (PostgreSQL physical). Detect via pg_stat_replication lag, table bloat, autovacuum activity.
  2. Lost commit after failover under async replication. Detect by comparing last-received LSN/GTID against application-level reconciliation.
  3. Duplicate writes on retry after an ambiguous COMMIT. A timeout on COMMIT does not mean rollback: the transaction may have committed. Detect with idempotency keys and unique constraints.
  4. Dangling prepared transactions after failover. Detect via pg_prepared_xacts.

Where people ignore it

  • Assuming rollback is free on the replica. Under PostgreSQL physical replication it is not.
  • Assuming a failed COMMIT means nothing happened. It means unknown, and a blind retry can duplicate.
  • Assuming DDL rolls back. MySQL before 8.0 has non-atomic DDL, so a failed ALTER can leave partial state that then replicates.

If the decision turns on durability rather than throughput, make the standby synchronous and accept the round trip; if it turns on throughput, keep async and make writes idempotent so a lost or duplicated commit is recoverable.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How would you document reporting a test honestly so the next owner can operate it?

Answer

The 90-second answer

A test report is a handoff artifact, not a victory lap. The test of whether it's honest is simple: could the next owner re-run the analysis and re-make the decision without asking you anything? If not, it isn't documented.

The minimum set is: the pre-registered hypothesis and primary metric, the design (unit of randomisation, duration, exposure), the sample size and how it was chosen, the effect with a confidence interval, a deviations log, and the decision rule agreed before launch. Then the operational pointers, where the raw data sits, the analysis code and the version it ran against, and what result would have flipped the call. Each item is on the list because it's what makes the result falsifiable by someone who wasn't in the room.

MARKDOWN
Primary metric: checkout conversion (pre-registered 2024-03-01)
Design: user-level randomisation, 14 days (2 full weeks)
n: 24,180 control / 24,090 treatment (SRM check p = 0.68)
Result: 3.11% -> 3.29%, +5.8% relative, 95% CI [+0.9%, +10.9%]
Deviations: none
Decision rule: ship if CI lower bound > 0 and no guardrail regression
Data: s3://exp/checkout-2024-03/  Code: analysis@v3 (pinned)

How heavy should the report be?

WeightWhen it's rightWhat it costs
One tracker lineDecision already made, no follow-up, low blast radiusNext owner can't re-derive; a re-run means redoing the analysis
One-page memoStandard product experiment, next owner may extend itAbout an hour to write
Full doc + pinned notebookMetric feeds a model, audit or regulatory need, or the next owner will re-runDays; needs the notebook pinned to a data snapshot

The deciding criteria are the reversibility and blast radius of the decision, and whether anyone downstream will re-run or extend the test. A reversible UI tweak earns a tracker line; a pricing change that feeds a forecasting model earns the full doc.

Failure modes, and how you catch them

  • Post-hoc metric swap (HARKing). Detected by diffing the reported metric against the pre-registration timestamp. Cost: the decision gets reversed after rollout, and the rollout window is wasted.
  • Sample ratio mismatch. Detected by a chi-square on the assignment counts. Here: 24,180 vs 24,090, expected 24,135 each, chi-square = 2 × 45² / 24,135 = 0.168, p ≈ 0.68. No mismatch. Cost if missed: the whole result is invalid and the test must be re-run.
  • No deviations log. Detected when the next owner can't reproduce the numbers. Cost: days of re-analysis and a lost week of the rollout window.
  • A p-value with no interval. The next owner can't size the rollout. Cost: either an over-rollout or a needless re-test.

The figures above are a worked example, not a real experiment.

Curated: · Written: · Reviewed:

Difficulty: Medium