What You'll Learn
- 1Build the ML test pyramid from tensor shape checks up to canary rollouts
- 2Compute the sample size an A/B test needs to detect a lift you actually care about
- 3Score generative code models with pass@k and set regression gates on offline evaluations
- 4Decompose a p99 latency budget across gateway, features, model, and post-processing
Why This Matters
ML systems have unique testing challenges beyond traditional software. Models can degrade silently, produce biased outputs, or fail catastrophically on edge cases. Comprehensive testing ensures reliability, fairness, and performance in production.
â ī¸
ML bugs are 5x more expensive to fix in production than in development. 85% of ML projects fail to reach production due to insufficient testing.
ML Testing Architecture
Unit Testing Framework
ML unit testing validates individual model components and behaviors. Key test categories include: shape validation (verifying input/output tensor dimensions), numerical stability (testing model behavior with extreme values like zeros, infinities, and very large numbers), batch inference (ensuring model handles varying batch sizes correctly), determinism (confirming identical inputs produce identical outputs when dropout is disabled), output range validation (checking predictions fall within expected bounds), performance benchmarks (measuring accuracy against minimum thresholds), and latency testing (ensuring inference meets latency requirements). A comprehensive test report summarizes pass/fail rates and identifies areas requiring attention.
A/B Testing Framework
A/B Testing Implementation
ML A/B testing uses statistical hypothesis testing to compare model variants. Key components include: deterministic user assignment (hashing user IDs for consistent variant allocation), minimum sample size requirements to achieve statistical power, appropriate statistical tests (chi-squared for binary metrics like conversion, t-tests for continuous metrics), effect size calculations (Cohen's d or odds ratio), confidence interval estimation, and automated recommendations based on significance, lift, and power analysis. The framework should track control vs treatment performance, detect statistically significant differences, and provide actionable recommendations for model deployment decisions.
Sample Size and Statistical Power
Before launching any experiment, decide the smallest lift worth detecting, , then derive the per-arm sample size for a two-sided test at level with power :
Suppose conversion sits at percent, you want to detect a 1.5 percentage point lift (), and you accept 5 percent false-positive risk with 80 percent power, so and . Substituting gives
At 20,000 eligible users per day split 50/50, each arm collects 10,000 users, so the test needs about 15 days - run it shorter and you are reading noise. Two failure modes dominate: peeking daily and stopping at the first significant result inflates the false-positive rate well beyond 5 percent unless you use sequential testing or an alpha-spending plan, and switching the primary metric after seeing the data does the same thing. Fix , , and the metric in the experiment plan before the first assignment.
The canary phase solves the same problem in miniature. With a 5 percent canary on 100,000 daily requests and a baseline error rate of 0.5 percent, the canary sees 5,000 requests, and the standard error of its error rate is , or 0.1 percentage points. A real 0.5 percentage point regression is therefore a 5-sigma event and is visible within one day, while a 0.1 point regression is not - which is why the canary gate should assert on changes larger than roughly 0.3 percentage points rather than on every wobble.
Shadow Testing
Shadow testing runs a candidate model alongside the production model without affecting users. Requests are processed by both models, but only the primary model's response is returned to the user. The framework compares predictions, latencies, and behavior patterns between models. Key features include: configurable sampling rates to control shadow traffic volume, concurrent model execution for accurate latency comparison, result mismatch detection, and performance analysis comparing latency impact and prediction agreement rates. Shadow testing is ideal for pre-production validation as it carries zero risk to users while providing real-world performance data.
Shadow runs need an explicit agreement threshold, because raw disagreement is always high for generative models. On classification workloads a disagreement rate above 2 to 3 percent versus the incumbent deserves investigation; on free-form text, compare semantic similarity and task success instead, since two phrasings of a correct answer will differ literally 100 percent of the time. Shadow testing also doubles peak compute for the sampled fraction, so cap the sample (1 to 5 percent of traffic is typical) and budget the duplicate GPU hours before you start.
Offline Regression Gates and pass@k
For generative and code models, a single greedy prediction is a poor test: the same prompt can sample differently, and a model that is right 6 times out of 20 draws may still be excellent. The standard estimator draws samples per problem, counts correct ones, and reports
With samples and correct on a problem, , while . The gate then becomes a floor rather than a point estimate: block the release if pass@1 on the held-out set drops more than 1 point, or if pass@5 drops more than 2 points versus the incumbent, because those movements are larger than the sampling noise you get from 20 draws. Keep the prompt, temperature, and sample count fixed across versions - changing any of them moves the metric without changing the model.
Canary Deployment
Latency Budgets in Acceptance Tests
A rollout is not green because the accuracy held; it is green because every SLO held. Split the end-to-end p99 budget across the stages that compose it:
A 100 ms interactive budget might be 5 ms gateway, 10 ms feature lookup, 75 ms model, and 10 ms post-processing. The subtlety is that percentiles do not add: if each of the four stages independently blows its own p99 one percent of the time, the chance that at least one stage misbehaves on a given request can reach 4 percent by the union bound, so the end-to-end p99 silently degrades toward p95. To actually hold an end-to-end 1 percent tail, each stage needs roughly a 0.25 percent tail, which means testing each stage at about p99.75. This is why canary dashboards should watch per-stage p99.9 and error budgets, not only the aggregate p99.
Interview Q&A
Q1: How would you design a comprehensive testing strategy for an ML system?
Answer: Testing Strategy Layers:
-
Unit Tests (70% of tests)
- Model component testing
- Data pipeline validation
- Feature engineering verification
-
Integration Tests (20% of tests)
- End-to-end pipeline testing
- API contract testing
- Model serving validation
-
System Tests (10% of tests)
- Performance testing
- Security testing
- Fairness and bias testing
-
Acceptance Tests
- A/B testing
- Shadow testing
- Canary deployments
Q2: Explain the difference between shadow testing and A/B testing
Answer:
| Aspect | Shadow Testing | A/B Testing |
|---|---|---|
| User Impact | None (silent) | Direct impact |
| Risk Level | Low | Medium |
| Metrics | Technical only | Business metrics |
| Duration | Hours to days | Days to weeks |
| Use Case | Pre-production validation | Production optimization |
Q3: How do you test for model fairness and bias?
Answer:
- Pre-processing: Audit training data for representation bias
- In-processing: Use fairness constraints during training
- Post-processing: Test model outputs across demographic groups
- Metrics: Disparate impact, equalized odds, demographic parity
- Continuous Monitoring: Track fairness metrics in production
Common Mistakes
Shipping a model because offline accuracy went up
Fix: Gate on shadow agreement, a powered A/B test, and per-stage latency, never on a single offline number.
Running the experiment until it looks significant
Fix: Pre-register the metric, minimum detectable effect, and sample size; use sequential testing if early reads are required.
Treating percentiles as additive
Fix: Budget each stage at a tighter tail than the end-to-end target; four p99 stages compose to roughly p95 overall.
Best Practices
- Keep a seeded golden set of edge cases that runs on every pull request with tensor shape and determinism checks
- Shadow every candidate on 1 to 5 percent of traffic and compare agreement before any user sees it
- Promote through 5, 25, 75, and 100 percent canary phases with automatic rollback on SLO breach
Key Takeaways
- Sample size is n = 2 (z_alpha + z_beta)^2 p (1 - p) / Delta^2: at p = 0.12 and Delta = 1.5 points you need about 7,360 users per arm
- pass@k = 1 minus C(n-c, k) / C(n, k): 6 correct of 20 gives pass@1 of 0.30 and pass@5 of 0.871
- Percentiles do not add: four stages at p99 compose to about p95, so test each stage near p99.75
- A 5 percent canary on 100,000 requests with a 0.5 percent error rate has a standard error of 0.1 points, enough to see a 0.5 point regression in a day
Frequently Asked Questions
Why did my A/B test show significance on day two and nothing on day fourteen?
Because you peeked. Each time you check a p-value and optionally stop, you spend part of the 5 percent false-positive budget; checking daily for two weeks can push the effective false-positive rate above 20 percent for a truly flat metric, and early reads also happen to coincide with novelty effects that decay. The fix is to compute the required sample size up front from the minimum detectable effect, run to that sample, and only then look - or to use a sequential design such as a group-sequential or always-valid test that formally accounts for repeated peeking.
How many offline test cases does CI need to catch a real regression?
Enough that the regression exceeds the noise floor. For binary metrics the standard error scales as one over the square root of n, so detecting a 1 point drop on a base rate of 90 percent with 95 percent confidence needs on the order of several thousand examples per slice. In practice, a few hundred curated edge cases catch catastrophic breakage, while slice-level monitoring on production traffic catches the subtle drift; CI is a smoke test, not the evaluation of record.
What is the difference between a shadow test and a canary?
A shadow test sends real requests to both the incumbent and the candidate but returns only the incumbent's answer, so it measures latency, errors, and agreement with zero user risk, typically over hours to days. A canary actually serves a fraction of users with the candidate, so it measures business metrics like conversion and revenue, at real risk, over days to weeks. Shadow first answers "does it behave on live traffic", canary then answers "does it help people".
Interview Questions
Q1: Design the rollout plan for a new ranking model that must reach 100 percent of traffic.
Offline gates first: golden set, slice metrics, and latency benchmarks must pass. Then 7 days of shadow on 5 percent of traffic to check agreement and p99. Next a 50/50 A/B sized for a 1 point CTR lift, which at a 12 percent base rate needs about 7,360 users per arm. Finally phased canaries at 5, 25, 75, and 100 percent with automatic rollback if error rate or p99 crosses the error budget.
Q2: Offline accuracy improved 1.2 points but the canary shows flat conversion. What do you check?
First check for distribution shift between the eval set and live traffic - often a stale slice or a leakage column that stopped being predictive. Then verify the canary actually has power: compute the standard error for its sample size and the lift you expect. Finally look at guardrail metrics such as latency and zero-result rate; a model that is more accurate but 40 ms slower can erase its quality gain in click-through.
Q3: How do you test for fairness without an infinite test matrix?
Pick the protected slices that matter for the domain, measure the metric gap per slice with confidence intervals rather than point estimates, and gate on the largest gap rather than the average. Automate it into the same regression suite as accuracy so a fairness regression blocks the release, and re-baseline quarterly as the population shifts.