Quality Metrics and Test Reporting Questions
Defining, computing, and communicating software quality. Covers choosing meaningful quality and test metrics (defect escape rate, defect detection effectiveness, defect density, MTTD/MTTR, pass rate, regression frequency, automation suite health and maintenance cost) versus vanity numbers; baselining, trend interpretation (real change versus normal variation), and alert thresholds; dashboards, weekly stability reports, and release-quality reports for engineering, product, and executive audiences, including composite go/no-go scores; framing unfavourable results; guarding against gamed metrics and reading what numbers such as code coverage or a high pass rate hide; investigating contradictory or shifting metrics and testing whether a quality signal really predicts customer outcomes; metric definitions, ownership, and governance; computing metrics from test-run and bug-tracker data (SQL and scripts); designing test-results reporting pipelines, storage schemas, real-time versus batch reporting, alerting, and failure fingerprinting and grouping for triage; and tying quality signals to product and business outcomes. Deciding what to automate and diagnosing individual flaky tests are covered elsewhere.
Tell me about a time you built or improved a test-reporting dashboard or automated summary. Which metrics did you put on it, which did you leave off, and what changed as a result?
Sample Answer
Direct answer
I turned a nightly "wall of red" into a one-screen summary that showed failures grouped by root cause instead of one row per failing test. The result was that people reviewed a handful of causes each morning instead of hundreds of individual failures, and the team started fixing causes instead of re-running builds. (Below is a story skeleton; swap in your own real numbers, but keep the shape.)
Situation and task
- Our CI (continuous integration, the automated build-and-test system) ran about 2,000 automated tests overnight. The default report was a flat list of failing test names, so on a bad night 240 tests failed and nobody could tell whether that was 240 problems or one.
- I was asked to make the report usable for QA, developers and the engineering manager, who each wanted something different.
Action: metrics I put on it (each tied to a decision)
- Failures grouped by signature (a signature is a short fingerprint of a failure's error and location, so identical failures group together). Decision: which cause to fix first.
- Pass rate on the main branch only (the trunk, the shared branch releases are cut from), trended over 14 days. Decision: is the trunk healthy enough to release from?
- Flake rate per test (a flaky test is one that passes and fails on the same code; rate = runs whose result differs from the previous run divided by total runs). Decision: which tests to quarantine (temporarily stop them from blocking the build while they keep running) or repair.
- Time from first red build to first fix. Decision: is triage keeping up?
Metrics I deliberately left off
- Total test count and code coverage percentage (they go up whether or not quality does).
- Overall pass rate across every branch (draft branches drown the trunk signal).
- Per-person failure counts (it turns a data tool into a blame tool and invites people to game it).
Technical decision
I added a signature column to the results table (one row per test per run) and a second table linking a signature to its ticket. The dashboard's top panel was a simple query grouping failed rows by signature, with a count of distinct tests and builds. That schema choice, not the chart styling, is what made the rest possible. Here is that query run on a tiny sample (7 result rows, builds 41 and 42, the ticket table linking a signature to its ticket):
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE results (test TEXT, status TEXT, signature TEXT, build INTEGER);
CREATE TABLE signature_ticket (signature TEXT PRIMARY KEY, ticket TEXT);
""")
db.executemany("INSERT INTO results VALUES (?,?,?,?)", [
("test_login", "fail", "expired-credential", 41),
("test_profile", "fail", "expired-credential", 41),
("test_export", "fail", "expired-credential", 41),
("test_login", "fail", "expired-credential", 42),
("test_search", "fail", "timeout-search-db", 42),
("test_cart_tax", "fail", "assert-rounding", 42),
("test_billing", "pass", None, 42),
])
db.execute("INSERT INTO signature_ticket VALUES ('expired-credential', 'QA-311')")
query = """
SELECT r.signature,
COUNT(*) AS failed_results,
COUNT(DISTINCT r.test) AS distinct_tests,
COUNT(DISTINCT r.build) AS builds,
COALESCE(t.ticket, 'none yet') AS ticket
FROM results r
LEFT JOIN signature_ticket t ON t.signature = r.signature
WHERE r.status = 'fail'
GROUP BY r.signature
ORDER BY failed_results DESC, r.signature
"""
for row in db.execute(query):
print(row)
('expired-credential', 4, 3, 2, 'QA-311')
('assert-rounding', 1, 1, 1, 'none yet')
('timeout-search-db', 1, 1, 1, 'none yet')
Six failed rows became three lines: GROUP BY signature collapses rows with the same signature, and the counts show how big each cause is. The same query over the real 240 failed rows is what produced the 9 signatures below.
Result (derived from the example data, not a benchmark)
On the first night we ran it, 240 failing results collapsed into 9 signatures, and the top signature (one expired test credential) explained 150 of them, so 240 items to read became 9. Beyond that, the 15-minute weekly review shifted from arguing about which tests to blame to assigning owners to signatures.
Trade-offs and pitfalls
- Over-grouping can hide a second, unrelated bug behind a large signature, so I kept a drill-down to individual tests.
- A metric nobody acts on is decoration. I kept a metric only if I could name the decision it feeds.
- Be ready to say what you would do differently (for example, I would have interviewed the consumers before choosing metrics, not after).
What strategies do you use to set alert thresholds on quality metrics so they are sensitive without turning into noise? Walk me through a concrete rule for weekly regression failures.
Sample Answer
Direct answer
Set the threshold from the metric's own history, not from a round number like "5 percent". Learn what a normal week looks like and how much it naturally wobbles, then alert only when a week is both unusual and big enough to matter. Use two rules, because failures show up in two shapes: a spike (one bad week) and a drift (a slow climb no single week would trip). Every alert needs an owner and a first action, otherwise it is just noise. This answer stays on quality-metric thresholds, not service-level objective (SLO) or error-budget design.
Structured elaboration
- Measure a rate, not a count. Weekly regression failures (regression means previously working behaviour that broke) = failed test executions divided by total executions. A week that ran more tests would otherwise look worse for no real reason.
- Learn the baseline (what "normal" is) from recent weeks. Use the median of the last 8 weeks and the MAD (median absolute deviation: the median distance of each week from the median). Unlike the standard deviation, one terrible week barely moves it. Multiplying MAD by 1.4826 gives a "robust standard deviation" on the same scale as the ordinary one. (Why that number: for normally distributed data, the MAD comes out at about 0.6745 of the standard deviation, and 1 / 0.6745 = 1.4826, so the multiplier converts MAD into what the standard deviation would have been.)
- Spike rule: one week above median + max(3 robust standard deviations, 1 percentage point). A percentage point is the plain difference between two percentages: going from 2.1 percent to 3.1 percent is 1 percentage point (a 48 percent relative rise, which is a different thing). The 1-point floor stops a very quiet history from producing a hair-trigger alert on a 0.3-point wobble nobody cares about.
- Drift rule: three consecutive weeks above median + 1 robust standard deviation. This catches slow rot.
- Route by severity. A spike gets triaged next working day; a drift becomes a ticket for the suite owner. A weekly metric should not page anyone.
- Keep the baseline honest. Leave out weeks with a declared outage, and re-baseline after a deliberate change (for example a big batch of new tests).
- Review the rule itself monthly. Mark each alert actionable or not; if most were not, loosen the rule.
Worked example
Save as weekly_alert.py and run it. The numbers are illustrative weekly failure rates in percent.
import statistics
# Weekly regression-suite failure rate in percent (failed executions / total executions)
weeks = [2.1, 1.8, 2.4, 2.0, 2.2, 1.9, 2.3, 2.1, 2.6, 4.6, 2.0, 2.8, 3.1, 3.4]
baseline_weeks = weeks[:8] # trailing window used to learn "normal"
med = statistics.median(baseline_weeks)
mad = statistics.median(abs(x - med) for x in baseline_weeks)
rsd = 1.4826 * mad
spike = med + max(3 * rsd, 1.0) # one week above this = alert (never closer than 1 point)
drift = med + 1 * rsd # three weeks in a row above this = alert
print("median %.2f MAD %.2f robust sd %.3f" % (med, mad, rsd))
print("spike line %.2f drift line %.2f" % (spike, drift))
streak = 0
for i, r in enumerate(weeks, start=1):
streak = streak + 1 if r > drift else 0
flags = []
if r > spike:
flags.append("SPIKE")
if streak >= 3:
flags.append("DRIFT")
print("week %2d rate %.1f %s" % (i, r, " ".join(flags)))
Output:
median 2.10 MAD 0.15 robust sd 0.222
spike line 3.10 drift line 2.32
week 1 rate 2.1
week 2 rate 1.8
week 3 rate 2.4
week 4 rate 2.0
week 5 rate 2.2
week 6 rate 1.9
week 7 rate 2.3
week 8 rate 2.1
week 9 rate 2.6
week 10 rate 4.6 SPIKE
week 11 rate 2.0
week 12 rate 2.8
week 13 rate 3.1
week 14 rate 3.4 SPIKE DRIFT
By hand: the eight baseline weeks sorted are 1.8, 1.9, 2.0, 2.1, 2.1, 2.2, 2.3, 2.4, so the median is the average of the middle two, (2.1 + 2.1) / 2 = 2.10. Each week's distance from 2.10 is 0, 0.3, 0.3, 0.1, 0.1, 0.2, 0.2, 0 in week order (2.1, 1.8, 2.4, 2.0, 2.2, 1.9, 2.3, 2.1); sorted that is 0, 0, 0.1, 0.1, 0.2, 0.2, 0.3, 0.3, and the median of those is (0.1 + 0.2) / 2 = 0.15. So weeks 1 to 8 give median 2.10 and MAD 0.15, so the robust standard deviation is 0.222. The spike line is 2.10 + max(0.67, 1.0) = 3.10 and the drift line is 2.10 + 0.222 = 2.32. Week 10 (4.6) trips the spike rule, and the next week is back at 2.0, which points to a one-off such as an environment problem. Weeks 12, 13 and 14 (2.8, 3.1, 3.4) each sit above the drift line, so the drift rule fires at week 14 even though no earlier week in that run crossed the spike line. Week 9 (2.6) is above the drift line but is only a streak of one, so it stays quiet.
Trade-offs and pitfalls
- A fixed limit ("fail above 5 percent") is either too late for a suite that normally runs at 2 percent or constant noise for one that runs at 4.
- Mean and standard deviation are dragged by the very outliers you want to detect; median and MAD are not.
- More sensitivity means more false alarms. The 1-point floor and the three-week requirement are the deliberate brakes, and both numbers are tunable conventions, not laws.
- Teams can game any threshold, for example by quarantining failing tests. Report the quarantined-test count next to the rate.
- If a suite runs very few tests per week, a rate is too jumpy. Fall back to counts or widen the window to a month.
Design the alerting for CI test failures: when does a failure notify a team channel, when does it page someone, and when is it suppressed? Choose thresholds and de-duplication windows and defend them.
Sample Answer
Direct answer
Notify the team channel for failures that need a human to look but not right now, page (wake or interrupt an on-call person through a pager or phone alert) only when the failure blocks a release or signals production risk, and suppress everything that is noise or already known. I would deduplicate by failure signature (a fingerprint of the error and location) plus branch, so one root cause produces one alert, not one per test. Every number below is a starting value to tune against a few weeks of your own alert history.
The three tiers
| Tier | Trigger | Why |
|---|---|---|
| Suppress | Failure on a feature branch or draft pull request (the author sees it in the pull request, nobody else is told); a test currently flagged quarantined (a known-unreliable test that is parked outside the blocking set but still recorded); failures during a declared CI infrastructure outage; a failure that passes on one automatic rerun | These are noise or already handled |
| Notify channel | Same signature fails on the main branch on 2 consecutive runs (after the automatic rerun); or a nightly suite's pass rate falls more than 5 percentage points below its own 14-day median (for a suite that normally sits at 97%, that means below 92%) | A real regression is likely, but a working-hours fix is fine |
| Page | A post-deploy smoke test (a small check run against the live deployment) fails twice in a row; or main is red and blocking the deploy pipeline for 60 minutes with no acknowledgement; or 30% or more of suites fail in the same run (mass failure suggests a shared cause) | Users or the release are at risk |
De-duplication windows
- Channel notification: one thread per signature and branch. Repeats inside a 4-hour window add a reply ("seen 6 more times") rather than a new message. Reason: a nightly job might legitimately fail again the next morning, but not within hours as a new event.
- Page: one open incident per signature until it is acknowledged and resolved. Repeats never re-page, they append to the incident.
Why 5 points: on a suite with a few hundred tests, a handful of flaky tests can move the pass rate by a point or two on an ordinary night, so a 5-point drop is comfortably outside normal wobble. If your own 14-day history shows wider swings, widen the margin. Tune it until at most a few channel alerts a week are false alarms.
Escalation and back-off for repeated alerts
(On-call is the person or rotation responsible for responding out of hours; primary is the first person paged, secondary is the backup. Acknowledgement means that person confirms in the paging tool that they have seen the alert and are working on it.)
- Page the primary on-call. No acknowledgement after 15 minutes: page the secondary.
- Still no acknowledgement after 30 minutes: notify the engineering manager.
- For a channel alert that is still open: reminder after 4 hours, then 24 hours, then move it into a daily digest. Back-off stops a stale alert from becoming wallpaper.
Flaky tests (pointer only)
A flaky test is one that passes and fails on the same code. Detecting and repairing flaky tests is a separate discipline. Here the rules only consume its output: a test with a quarantine flag is suppressed from paging and channel alerts but still recorded, and a quarantined test that fails while running alone still shows on the dashboard. Rerun-on-failure is a suppression aid, not a fix.
Worked example
The main-branch suite runs every hour, plus the longer nightly suite. At 02:10 the main run fails: 30 tests, 3 signatures. After auto-rerun 26 still fail and all 26 share signature A. The next hourly run fails identically at 03:10 (second consecutive run), so the channel gets one message: "Signature A, 26 tests, 2 runs, owner: payments". The smoke test after the 09:00 deploy passes, so nobody is paged. Had that smoke test failed twice, payments on-call would be paged once, with the same signature attached.
Trade-offs and pitfalls
- Lower thresholds catch bugs earlier and train people to ignore alerts. The 2-consecutive-run rule trades up to one run of delay for far fewer false alarms.
- Paging on test failures alone is usually wrong. Page on impact (deploys blocked, production signal), not on test count.
- What would change my call: a very slow suite (a run takes hours) argues for notifying on the first confirmed failure, since waiting a second run is too costly.
Design the data behind a nightly quality summary email that lists newly failing tests, tests that have become less reliable, the most common failure causes and suggested owners. Which tables and queries would you need, and how would you suggest owners?
Sample Answer
Direct answer
Store every test result as a raw row (test, day, status, failure signature), keep a small tests table that maps each test to the file defining it, and add two small lookup tables for ownership (the code-owners rules and the file commit history), four tables in all. The email is then four queries over a recent window: newly failing (fails now, no failures in a baseline period), less reliable (failure rate this week minus the baseline rate), top failure causes (group by failure signature, a short fingerprint of the error text), and suggested owner (the team named in the code-owners file for the test's path, otherwise whoever changed that file most often recently, otherwise "unassigned").
Tables you would need
| Table | Key columns | Purpose |
|---|---|---|
tests | test_id, file_path | Which file defines each test |
test_runs | test_id, day, status, signature | One row per result; the fact table (the big table of recorded events that everything else is computed from) |
code_owners | path_prefix, team | Loaded from the repo's code-owners (CODEOWNERS) file |
file_commits | file_path, author, day | From version-control history, used as a fallback owner |
A daily rollup (a small pre-summed table of runs and fails per test per day) can sit on top of test_runs when volume grows, but the queries below read the fact table so the logic is easy to follow.
Worked example (run it)
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE tests (test_id TEXT PRIMARY KEY, file_path TEXT);
CREATE TABLE test_runs (test_id TEXT, day INTEGER, status TEXT, signature TEXT);
CREATE TABLE code_owners (path_prefix TEXT, team TEXT); -- from CODEOWNERS
CREATE TABLE file_commits (file_path TEXT, author TEXT, day INTEGER);
""")
db.executemany("INSERT INTO tests VALUES (?,?)", [
("t_pay", "tests/payments/test_refund.py"),
("t_cart", "tests/cart/test_totals.py"),
("t_srch", "tests/search/test_rank.py"),
("t_misc", "tests/misc/test_utils.py"),
])
db.executemany("INSERT INTO code_owners VALUES (?,?)", [
("tests/payments/", "payments-team"),
("tests/cart/", "cart-team"),
])
db.executemany("INSERT INTO file_commits VALUES (?,?,?)", [
("tests/search/test_rank.py", "ana", 28), ("tests/search/test_rank.py", "ana", 20),
("tests/search/test_rank.py", "raj", 5),
])
runs = []
def add(test, days, status, sig=None):
for d in days:
runs.append((test, d, status, sig))
# Today is day 30. Windows: last 24h = day 30, recent = days 24-30, baseline = days 3-23 (21 days, the range the queries use; day-2 rows are extra history they skip).
# A test may have several runs on one day, so a day can hold both a pass row and a fail row.
add("t_pay", range(2, 30), "pass"); add("t_pay", [30], "fail", "TimeoutError@gateway") # newly failing
add("t_cart", range(2, 24), "pass")
add("t_cart", [24, 25, 26, 27, 28, 29, 30], "pass"); add("t_cart", [26, 28, 30], "fail", "AssertionError@totals")
add("t_srch", range(2, 24), "pass"); add("t_srch", [24, 26, 28], "pass")
add("t_srch", [25, 27, 29, 30], "fail", "TimeoutError@gateway")
add("t_misc", range(2, 31), "pass")
db.executemany("INSERT INTO test_runs VALUES (?,?,?,?)", runs)
print("1) newly failing (fails today, no fail in prior 21 days):")
for r in db.execute("""
SELECT DISTINCT t.test_id FROM test_runs t
WHERE t.day = 30 AND t.status = 'fail'
AND NOT EXISTS (SELECT 1 FROM test_runs p WHERE p.test_id = t.test_id
AND p.status = 'fail' AND p.day BETWEEN 9 AND 29)
ORDER BY 1"""):
print(" ", r[0])
print("2) less reliable (7-day fail rate minus 21-day baseline rate, min 5 runs):")
for r in db.execute("""
WITH w AS (
SELECT test_id,
SUM(CASE WHEN day >= 24 THEN status='fail' ELSE 0 END) * 1.0 /
NULLIF(SUM(day >= 24), 0) AS recent_rate,
SUM(CASE WHEN day < 24 THEN status='fail' ELSE 0 END) * 1.0 /
NULLIF(SUM(day < 24), 0) AS base_rate,
SUM(day >= 24) AS recent_runs
FROM test_runs WHERE day >= 3 GROUP BY test_id)
SELECT test_id, ROUND(recent_rate,3), ROUND(base_rate,3), ROUND(recent_rate-base_rate,3)
FROM w WHERE recent_runs >= 5 AND recent_rate - base_rate > 0.10 ORDER BY 4 DESC"""):
print(" ", *r)
print("3) top failure causes, last 7 days (distinct tests per signature):")
for r in db.execute("""
SELECT signature, COUNT(*) AS fail_runs, COUNT(DISTINCT test_id) AS tests
FROM test_runs WHERE status='fail' AND day >= 24
GROUP BY signature ORDER BY tests DESC, fail_runs DESC"""):
print(" ", *r)
print("4) suggested owner (CODEOWNERS first, else top recent committer):")
for r in db.execute("""
SELECT t.test_id,
COALESCE(
(SELECT team FROM code_owners o WHERE t.file_path LIKE o.path_prefix || '%'
ORDER BY LENGTH(o.path_prefix) DESC LIMIT 1),
(SELECT author FROM file_commits c WHERE c.file_path = t.file_path AND c.day >= 0
GROUP BY author ORDER BY COUNT(*) DESC, MAX(day) DESC LIMIT 1),
'unassigned') AS owner,
CASE WHEN EXISTS (SELECT 1 FROM code_owners o WHERE t.file_path LIKE o.path_prefix || '%')
THEN 'codeowners' WHEN EXISTS (SELECT 1 FROM file_commits c WHERE c.file_path = t.file_path)
THEN 'history' ELSE 'none' END AS source
FROM tests t ORDER BY t.test_id"""):
print(" ", *r)
Output:
1) newly failing (fails today, no fail in prior 21 days):
t_pay
2) less reliable (7-day fail rate minus 21-day baseline rate, min 5 runs):
t_srch 0.571 0.0 0.571
t_cart 0.3 0.0 0.3
t_pay 0.143 0.0 0.143
3) top failure causes, last 7 days (distinct tests per signature):
TimeoutError@gateway 5 2
AssertionError@totals 3 1
4) suggested owner (CODEOWNERS first, else top recent committer):
t_cart cart-team codeowners
t_misc unassigned none
t_pay payments-team codeowners
t_srch ana history
How the SQL works, in plain words. Query 1 keeps tests that failed on day 30 and asks NOT EXISTS (is there no earlier failure between day 9 and day 29, the 21 days before today?). Query 2 counts failures per window: status='fail' is true (1) or false (0) in SQLite, so SUM(day >= 24) counts the rows in the recent window by adding up 1s, and SUM(CASE WHEN day >= 24 THEN status='fail' ELSE 0 END) counts only the failing ones. NULLIF(x, 0) turns a zero divisor into NULL so a test with no runs in a window gives NULL instead of a divide-by-zero error. Query 4 uses COALESCE(a, b, c), which returns the first non-NULL of its arguments, so the owner is the code-owners team if one matches, else the top committer, else 'unassigned'. Each inner query is a correlated subquery (it is re-run for each test row, using that row's file_path). t.file_path LIKE o.path_prefix || '%' means the path starts with the prefix (|| joins strings, % matches anything after), and ORDER BY LENGTH(o.path_prefix) DESC LIMIT 1 keeps the longest, most specific prefix.
Where the counts come from. In the last 7 days (days 24 to 30) t_cart has 7 passing rows plus 3 failing rows (days 26, 28, 30), so 3 failures out of 10 runs is 0.3. t_srch has 3 passing rows (24, 26, 28) and 4 failing rows (25, 27, 29, 30), so 4 of 7 is 0.571. t_pay has 6 passes (24 to 29) and one fail on day 30, so 1 of 7 is 0.143. Every baseline day for all three was a pass, so their baseline rate is 0.
Reading it: t_pay had 28 clean days and failed today, so it is newly failing. t_srch failed on 4 of its 7 runs this week against a spotless baseline (0.571), and t_cart on 3 of 10 (0.3). The signature TimeoutError@gateway hits two tests in different areas, which hints at a shared cause (probably a gateway problem, not two test bugs), so the email should list causes by number of distinct tests, not just failure count. t_pay appears in both sections one and two, so the email builder should drop tests already shown as newly failing from the "less reliable" list.
How owners are suggested
- Code ownership first: longest matching path prefix in
code_owners(a more specific rule wins). - History second: the author with the most commits to the test file, ties broken by most recent. This suits files no one formally owns, like
t_srchhere. - Signature-based hint (optional third step): if the stack trace points at a source file, suggest that file's owner, because the failing code is often not in the test file.
- Show the source ("codeowners" or "history") so readers can judge confidence, and let people correct an owner, storing corrections as an override table that beats the guesses.
Trade-offs and pitfalls
- Minimum runs: the
recent_runs >= 5guard stops a test with two runs from topping the list. - Baseline pollution: the baseline should describe normal behaviour, so if a test was already flaky (passes and fails on identical code) in the baseline, a rising rate is muted. Excluding known-flaky tests from "newly failing" but listing them separately keeps signal clean.
- Signature quality: if raw error text (with timestamps and ids) is used as the signature, every failure looks unique and the causes section is useless. Normalize first: replace the parts that change from run to run with placeholders, then keep the exception type and the component. For example the raw text
TimeoutError: no reply from gateway-7f3a9c (10.0.2.15:443) after 30sbecomesTimeoutError: no reply from gateway-<ID> (<ADDR>) after <N>s, and the short signatureTimeoutError@gatewaykeeps the exception and the component. Two failures of the same cause now produce the same string. - History owners go stale: someone who wrote a file two years ago and left is a bad owner, so limit history to a recent window and check the person is still on the team. The demo query keeps all history (
c.day >= 0); in production replace 0 with a cutoff such as today minus 90 days. - Cost: the email queries are small over a few weeks of data. Stop them scanning all history by partitioning by day.
Pass rate for a large suite has drifted downward over several weeks. How would you decide whether that is a real change in quality or ordinary variation, and how would you have it flagged automatically next time?
Sample Answer
Direct answer
I would not react to the slope. First I would check that the measurement itself did not change, then compare the drop with the normal day-to-day wobble of this suite, then slice the drop to see whether it is concentrated in a few tests, one component or one date. Only then do I call it real. For next time, I turn that comparison into an automatic alert built on the suite's own history.
Step 1: did what we measure change?
- Was the set of tests different (new tests added that fail more, old ones deleted, more skipped or quarantined, meaning moved out of the gate that blocks merges)? Recompute the rate on the tests that existed at the start of the window. A falling overall rate with a flat rate on that fixed set means the mix changed, not the quality.
- Did the definition, retry policy, runner image or test data change? Infrastructure changes often show up as a spread-out drop across many unrelated suites.
Step 2: is it more than ordinary variation?
Measure the normal wobble from a stable baseline: the mean and standard deviation (sd, how far daily values typically stray from the mean) of the daily pass rate. Treat the day or the run, not the individual test, as the unit, because failures are clumped: one broken dependency can fail hundreds of tests at once, so a textbook binomial error bar (the range you would expect if every test failed independently, like coin flips) would be far too narrow. Adjust for known patterns: compare weekdays with weekdays if daily builds differ at weekends, pool sparse tests over a longer window instead of judging them daily, and use rates rather than counts when suite sizes differ.
Step 3: slice it. A genuine quality loss usually concentrates: a handful of tests, one owning team, one component, or one merge date. Then reproduce a sample of the new failures on a clean environment. Real bugs reproduce; test rot and infrastructure trouble often do not.
Step 4: automate the flag. This is a control chart approach: plot the series against limits computed from its own history and alarm when it leaves them. If you adopt only one rule first, take 8 in a row below the mean, then add the 3 sd limit for crashes. Three simple rules on the daily series, each with a different trade-off:
| Rule | Catches | Weakness |
|---|---|---|
| One day beyond mean minus 3 sd (sigma is just another name for sd; 3 is a convention that leaves very few false alarms when data is roughly bell-shaped) | Sudden drops | Slow to notice a gradual slide |
| 8 consecutive days below the mean | Sustained small shifts | Blind to a one-day crash if used alone |
| CUSUM (cumulative sum: adds up each day's shortfall and alarms when the total passes a threshold) | Small persistent drifts, early | Needs tuning of its allowance and threshold |
Change-point methods, which estimate when a shift began, are rarely needed in interviews and are useful after an alarm to date the change against releases; pairing that with the rules above is enough for most teams.
Worked example (synthetic data, seed pinned; run it unchanged)
import random
from statistics import mean, stdev
rng = random.Random(7)
# Synthetic daily pass rates (percent): 28 stable baseline days, then 21 days of slow decline.
baseline = [rng.gauss(97.0, 0.6) for _ in range(28)]
recent = [rng.gauss(97.0 - 0.06 * d, 0.6) for d in range(1, 22)]
series = baseline + recent
mu, sd = mean(baseline), stdev(baseline)
lower = mu - 3 * sd
print(f"baseline mean={mu:.2f} sd={sd:.2f} lower limit={lower:.2f}")
# Rule 1: any single day below the 3-sigma lower limit
first_limit = next((i for i, x in enumerate(series) if x < lower), None)
# Rule 2: 8 consecutive days below the baseline mean
first_run = None
streak = 0
for i, x in enumerate(series):
streak = streak + 1 if x < mu else 0
if streak == 8:
first_run = i
break
# Rule 3: one-sided CUSUM (allowance k = 0.5 sd, decision threshold h = 4 sd)
k, h, s, first_cusum = 0.5 * sd, 4 * sd, 0.0, None
for i, x in enumerate(series):
s = min(0.0, s + (x - mu) + k)
if s < -h:
first_cusum = i
break
def day(i):
return "none" if i is None else f"day {i + 1}"
print("drift starts: day 29")
print("3-sigma limit alarm:", day(first_limit))
print("8-in-a-row below mean:", day(first_run))
print("CUSUM alarm:", day(first_cusum))
baseline mean=96.98 sd=0.51 lower limit=95.46
drift starts: day 29
3-sigma limit alarm: day 44
8-in-a-row below mean: day 38
CUSUM alarm: day 38
How the CUSUM line reads: each day it adds (today's value minus the mean, plus the allowance k). Days near the mean add about zero, and the min(0.0, ...) keeps the total from drifting upward, so only shortfalls accumulate. When the running total drops below minus h, the shortfall has persisted long enough to alarm. k = 0.5 sd ignores tiny wobble; h = 4 sd is a common starting point, tuned on past data.
Days 1 to 28 are a stable baseline; from day 29 the true rate slides by 0.06 points a day. None of the rules fired during the baseline. The 8-in-a-row rule and CUSUM alarm on day 38, roughly 0.6 points below baseline, while the strict 3-sd limit needs until day 44. This is one synthetic series, so the exact days illustrate the trade-off, not a promise.
Trade-offs and pitfalls
- Tighter rules alert sooner but cry wolf more, and an alert nobody trusts is ignored. Tune on past data and review alert precision monthly (the share of alerts that turned out to be real problems; for example 3 real out of 10 alerts is 30 percent, too noisy).
- Sending the alert with the slice (which tests, which team, first bad date) makes it actionable; a bare percentage prompts a meeting.
- The method assumes the past is a fair baseline. After a deliberate change, such as a suite migration, reset the baseline.
Unlock Full Question Bank
Get access to all Quality Metrics and Test Reporting interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.