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.
Walk me through how test results get from CI runners into a store your dashboards can query. What stages would the pipeline have, what would you record per result, and what would break first as volume grows?
Sample Answer
Direct answer
Treat it as a small data pipeline: collect the raw report at the end of every CI run (CI is continuous integration, the automated system that builds and tests each change), parse it into one row per test attempt, enrich it with run metadata, load it idempotently (so that loading the same data twice has the same effect as loading it once) into a store, and serve dashboards from pre-aggregated summaries (totals such as daily pass counts, computed once and stored, rather than recomputed from raw rows on every page view). The first thing that breaks as volume grows is dashboard reads over the raw table, and my design puts summaries in front of it from day one.
Pipeline stages
- Emit: test runners write JUnit-style XML or JSON (a standard result format) into the job workspace.
- Collect: a shared, reusable pipeline step that always runs, even when tests fail, and uploads the report.
- Parse and normalize: convert each report to uniform records. This includes turning each failure message into a failure signature: a short fingerprint made by stripping run-specific parts (timestamps, ids, memory addresses) from the error text, so the same bug always produces the same signature.
- Enrich: add commit, branch, pull request, runner, environment and pipeline id.
- Ingest: send records through a queue (a buffer that holds incoming records so a burst of uploads does not overwhelm the database), then batch-insert with an idempotency key (a unique identifier per record, here run id plus test id plus attempt, so a repeated upload is recognised and ignored).
- Store: a hot store (fast, indexed storage for recent rows), a summaries table (rollups: pre-computed totals per day, suite or test), and cold storage (cheap, slower storage for old data).
- Serve: dashboards and alerts read summaries; drill-down reads the hot store.
What to record per result
A stable test id (suite, class and name, so history survives renames of files), run id, attempt number (to see retries), status (passed, failed, error, skipped), duration, commit, branch, runner, a normalized failure signature, a link to the full log in object storage (cheap file-style storage for large blobs such as logs and screenshots), and a finish timestamp. This is the schema, run for real:
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE test_result (
run_id TEXT NOT NULL, -- CI run
test_id TEXT NOT NULL, -- stable id: suite + class + name
attempt INTEGER NOT NULL DEFAULT 1,
status TEXT NOT NULL CHECK (status IN ('passed','failed','error','skipped')),
duration_ms INTEGER NOT NULL,
commit_sha TEXT NOT NULL,
branch TEXT NOT NULL,
runner TEXT NOT NULL,
signature TEXT, -- normalized failure signature, NULL when passed
finished_at TEXT NOT NULL,
PRIMARY KEY (run_id, test_id, attempt) -- makes re-uploads idempotent
);
CREATE INDEX idx_result_test_time ON test_result (test_id, finished_at);
""")
rows = [
("run1", "api.Login.ok", 1, "passed", 120, "abc", "main", "r1", None, "2026-09-01T02:00"),
("run1", "api.Pay.refund",1, "failed", 900, "abc", "main", "r1", "Timeout|db", "2026-09-01T02:00"),
("run1", "api.Pay.refund",2, "passed", 850, "abc", "main", "r1", None, "2026-09-01T02:01"),
("run2", "api.Login.ok", 1, "passed", 130, "def", "main", "r2", None, "2026-09-02T02:00"),
("run2", "api.Pay.refund",1, "passed", 880, "def", "main", "r2", None, "2026-09-02T02:00"),
]
for _ in range(2): # upload the same batch twice: the second pass must be a no-op
db.executemany("INSERT OR IGNORE INTO test_result VALUES (?,?,?,?,?,?,?,?,?,?)", rows)
print("rows stored:", db.execute("SELECT COUNT(*) FROM test_result").fetchone()[0])
# A test is "flaky in a run" when a failed attempt is followed by a passing attempt of the same test.
flaky = db.execute("""
SELECT test_id, COUNT(DISTINCT run_id) AS flaky_runs
FROM test_result f
WHERE status IN ('failed','error') -- a skipped attempt is not a failure
AND EXISTS (SELECT 1 FROM test_result p
WHERE p.run_id = f.run_id AND p.test_id = f.test_id
AND p.attempt > f.attempt AND p.status = 'passed')
GROUP BY test_id""").fetchall()
print("flaky:", flaky)
Output:
rows stored: 5
flaky: [('api.Pay.refund', 1)]
The batch was uploaded twice yet 5 rows are stored, so retried uploads cannot double count. Plain-language walkthrough of the flaky query: take every row f that did not pass (status failed or error). Keep it only if the same run has another row p for the same test with a later attempt number that passed. Count the distinct runs where that happened, per test. Here api.Pay.refund failed on attempt 1 and passed on attempt 2 in run1, so it counts once; in run2 it simply passed. Nothing else failed, so nothing else appears. The store here is SQLite for demonstration; a production system would use a server database or warehouse with the same shape.
Latency versus history (two access patterns)
- Near-real-time summary: at the end of each run, write one small summary row (counts, duration, top signatures) so the run page shows within seconds to minutes.
- 90-day history and signature search: the indexed hot store, partitioned by date (split into one chunk per day so queries and cleanups touch only the days they need).
- Two years of data: keep daily rollups per test and suite (pass rate, flake count, 95th-percentile duration, the time that 95% of runs come in under) indefinitely, move raw rows past 90 days to compressed files in object storage (a warehouse, meaning a database built for large analytical queries, is the other common home), and query those only for investigations.
What breaks first as volume grows
- Dashboard queries scanning the raw table (fix: rollups, indexes, partitions).
- Write spikes when many pipelines finish at once (fix: queue and batch inserts).
- Storage bloat from stack traces and logs kept inline (fix: store a truncated signature, put full logs in object storage).
- Unstable test ids, which quietly break history, and unnormalized error text, which explodes distinct signatures.
Hooking collection into every pipeline, safely
- Ship it as a shared template step so teams opt out rarely, and make it best effort: a reporting failure must never fail the build, but should alert, and "runs with no report" should itself be a tracked metric.
- Security: give each pipeline a write-only token (it can upload results but not read or delete anything) with narrow scope, kept in a secret store (a service that holds credentials outside the code), and do not expose it to pull requests from forks (copies of the repository made by outside contributors, whose code you do not trust), scrub secrets and personal data from logs before upload, validate and size-limit uploads, and enforce access control on dashboards.
- Performance: upload asynchronously, compress, and cap payload size so collection adds little to the run time.
Given defects(id INT, title TEXT, found_in_env TEXT, introduced_in_release INT, found_at TIMESTAMP) and releases(id INT, name TEXT, release_date TIMESTAMP), write an ANSI SQL query for defect escape rate per release, returning release id, name, escape count, total count and percent to two decimals. Treat a defect as an escape when it was found in production and introduced in that release. What would make this number misleading for a recent release?
Sample Answer
Direct answer
Attribute each defect to the release that introduced it, count how many of those were found in production, and divide by all defects for that release. Use a LEFT JOIN from releases so a release with no defects still shows, and guard the division. The number is misleading for a recent release mainly because production defects surface over weeks (discovery lag), so a young release looks better than it is.
Structured elaboration
Approach. One row per release (LEFT JOIN from releases), grouped on the release. Escape count = defects where found_in_env = 'production'. Total = all defects with introduced_in_release equal to that release, wherever found. Percent = escapes divided by total times 100, rounded to two decimals. Only standard constructs are used (LEFT JOIN, CASE, SUM, COUNT, GROUP BY). ROUND(x, 2) exists in every major engine, though strict standard SQL would write CAST(... AS DECIMAL(5,2)).
Reading the query, clause by clause (core)
LEFT JOIN defects d ON d.introduced_in_release = r.id: start from every release and attach its defects. Unlike a plain join, a release with zero defects (release 5) still gets a row.CASE WHEN d.found_in_env = 'production' THEN 1 ELSE 0 ENDinsideSUM: turns each defect into 1 if it escaped and 0 if not, so the sum is the escape count. Release 1's four defects give 0 + 1 + 0 + 0 = 1.COUNT(d.id): counts only defects that exist. For release 5 there are none, so it is 0 (COUNT(*)would wrongly count the empty join row as 1).COALESCE(x, 0): replaces NULL with 0.SUMover a release with no defects returns NULL, and the escape count should read 0.100.0 * ... / COUNT(...): the100.0(a decimal, not the integer 100) forces decimal division; with integers, 1 / 4 would truncate to 0 in some engines.ROUND(..., 2)gives two decimals.CASE WHEN COUNT(d.id) = 0 THEN NULL: dividing by zero is an error, so a release with no defects shows a blank rate instead.
Key points
- Release 1: 1 escape out of 4 defects = 25 percent. Release 3: 1 of 3 = 33.33 percent.
- Release 5 has no defects, so its rate is NULL (unknown), not 0. The
CASE WHEN COUNT(d.id) = 0guard prevents a divide-by-zero. - Optional extra (not asked for): detection rate (the sibling metric: share of a release's defects found before production) equals 100 minus the escape rate here (75.0 for release 1) because "found before production" is the exact complement. They diverge if you count only defects found by QA, or if unattributed defects are handled differently in the two queries.
Complexity (rarely asked; a brief mention is enough). One pass over the join: O(R + D) with a hash join, where R is releases and D is defects. An index on defects(introduced_in_release) keeps the join cheap; memory is one group per release.
Edge cases
- Inconsistent environment labels ("prod" versus "production") silently undercount escapes. Normalise the values.
- Defects with a NULL
introduced_in_releasedrop out of every group. Count them separately. - A defect found in production but introduced in an older release counts against the older release, which is right but means past rates get restated.
Worked example
Save as defect_escape.sql and run sqlite3 -header -column :memory: < defect_escape.sql. The first query is the answer. The second is an optional extra, detection rate, and it uses two things you can skip in an interview: the FILTER clause (a shorthand for counting only rows that match a condition; PostgreSQL syntax, also accepted by SQLite 3.30 and later) and NULLIF(COUNT(d.id), 0), which turns a zero denominator into NULL so the division returns NULL instead of an error.
CREATE TABLE releases (id INT, name TEXT, release_date TIMESTAMP);
CREATE TABLE defects (id INT, title TEXT, found_in_env TEXT, introduced_in_release INT, found_at TIMESTAMP);
INSERT INTO releases VALUES
(1,'2.1','2026-01-10 09:00:00'),
(2,'2.2','2026-02-14 09:00:00'),
(3,'2.3','2026-03-21 09:00:00'),
(4,'2.4','2026-04-25 09:00:00'),
(5,'2.5','2026-05-30 09:00:00');
INSERT INTO defects VALUES
(1,'Login timeout','qa',1,'2026-01-05 10:00:00'),
(2,'Wrong tax rounding','production',1,'2026-01-20 14:00:00'),
(3,'Export header typo','staging',1,'2026-01-08 11:00:00'),
(4,'Search crash','qa',1,'2026-01-06 15:00:00'),
(5,'Cart total drift','production',2,'2026-02-25 08:30:00'),
(6,'Profile save fails','qa',2,'2026-02-10 09:15:00'),
(7,'Slow report page','production',2,'2026-03-02 16:45:00'),
(8,'Email link broken','qa',2,'2026-02-11 13:00:00'),
(9,'Coupon stacking','qa',3,'2026-03-15 10:20:00'),
(10,'Refund rounding','production',3,'2026-03-28 12:00:00'),
(11,'Avatar upload','staging',3,'2026-03-16 17:00:00'),
(12,'Sort order flips','qa',4,'2026-04-20 11:00:00'),
(13,'Tooltip overlap','qa',4,'2026-04-21 09:45:00'),
(14,'Password reset loop','staging',4,'2026-04-22 15:30:00');
SELECT r.id AS release_id,
r.name,
COALESCE(SUM(CASE WHEN d.found_in_env = 'production' THEN 1 ELSE 0 END), 0) AS escape_count,
COUNT(d.id) AS total_count,
CASE WHEN COUNT(d.id) = 0 THEN NULL
ELSE ROUND(100.0 * SUM(CASE WHEN d.found_in_env = 'production' THEN 1 ELSE 0 END) / COUNT(d.id), 2)
END AS escape_pct
FROM releases r
LEFT JOIN defects d ON d.introduced_in_release = r.id
GROUP BY r.id, r.name
ORDER BY r.id;
SELECT r.id AS release_id,
COUNT(*) FILTER (WHERE d.found_in_env <> 'production') AS found_before_prod,
COUNT(d.id) AS total_count,
ROUND(100.0 * COUNT(*) FILTER (WHERE d.found_in_env <> 'production') / NULLIF(COUNT(d.id), 0), 2) AS detection_pct
FROM releases r
LEFT JOIN defects d ON d.introduced_in_release = r.id
GROUP BY r.id
ORDER BY r.id;
Output (SQLite prints 25.0 where PostgreSQL prints 25.00):
release_id name escape_count total_count escape_pct
---------- ---- ------------ ----------- ----------
1 2.1 1 4 25.0
2 2.2 2 4 50.0
3 2.3 1 3 33.33
4 2.4 0 3 0.0
5 2.5 0 0
release_id found_before_prod total_count detection_pct
---------- ----------------- ----------- -------------
1 3 4 75.0
2 2 4 50.0
3 2 3 66.67
4 3 3 100.0
5 0 0
Trade-offs and pitfalls
What makes this misleading for a recent release
- Discovery lag (technically called right-censoring: the outcomes for a young release are still arriving, like judging a race before everyone has finished): production defects appear over weeks. Release 4 shows 0 escapes and 100 percent detection only because it shipped recently, not because it is the best release. Compare releases at equal age, for example only defects found within 30 days of the release date (in standard SQL,
d.found_at < r.release_date + INTERVAL '30' DAY; the interval syntax varies by engine), and mark younger releases as immature. - Tiny denominators: with 3 defects, one escape moves the rate by 33 points.
- Severity mix: a cosmetic escape and a data-loss escape count the same. Report critical escapes separately.
- Restatement: a later production find attributed to an old release changes that release's number.
You own quality reporting across 200 services and several CI systems. Design the platform that computes the organisation's core defect and detection metrics consistently, including how test records and bug-tracker records are tied to the same release.
Sample Answer
Direct answer
The platform works if three things are true: every fact enters through one normalised schema, every metric is computed by one versioned piece of code from immutable raw events, and every test result and bug can be tied to the same release identity. Everything else is plumbing around those three.
Terms. Immutable raw events means each fact is stored once as it arrived and never edited. Normalised schema means one agreed set of columns for facts from every source. Append-only means rows are only added. Telemetry is data the running product emits, such as error rates. A service registry is a list of every service with its owning team. Contract tests on adapters are tests that check each adapter still produces the fields and status meanings the schema promises.
1. Release identity. Define one key, for example service plus version (checkout@2.5.0), stored with its git commit and deployment time in a release table. Test runs carry it when CI produces them; bugs get it from tracker fields (affected version) and links to the fixing pull request. Where the tracker lacks it, trace the fixing commit back to the change that introduced the bug (blame-based, heuristic: git blame shows which earlier commit last touched the lines the fix changed, and that is a good guess, not proof), and let a person override the result for severe bugs. Example: bug B4 is fixed by a commit editing pricing.py lines 40 to 52; blame shows those lines last changed in the 2.4.0 release, so B4 is attributed to checkout@2.4.0 even though a customer reported it after 2.5.0 shipped.
2. Sources. CI systems (each with a small adapter that emits a common event format), the bug tracker, the deploy system, and production telemetry such as error rates or incident records. Telemetry corroborates escapes: a production incident with no linked bug is a data hole.
3. Storage and reproducibility.
- Land raw events append-only and never edit them; corrections arrive as new events.
- Build curated tables from raw with versioned SQL kept in git. Every metric row records the definition version and the data snapshot time, so a number can be recomputed exactly and an old number explained.
- Keep pre-aggregated tables for dashboards, but only as rebuildable products of raw data.
4. The core metrics. Defect escape rate for a release is escaped defects divided by all defects attributed to it (escaped plus caught before release). Detection by stage shows where defects are caught (this needs a found_stage column on the bug, such as unit, integration, e2e or production, which the small schema below leaves out). Time to detect is release to discovery. In the example below, introduced_release says whose defect it is (that is what escape rate groups by), while found_release says when it surfaced. B4 was introduced in 2.4.0 (deployed 1 September) and found in 2.5.0 (deployed 15 September), so it lived through a whole release cycle, at least 14 days here, and time to detect can be computed from that gap.
Worked example (illustrative data; run unchanged)
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE release (release_id TEXT PRIMARY KEY, service TEXT, version TEXT,
git_sha TEXT, deployed_at TEXT);
CREATE TABLE test_run (run_id TEXT, release_id TEXT, ci_system TEXT, stage TEXT,
passed INT, failed INT);
CREATE TABLE bug (bug_id TEXT PRIMARY KEY, introduced_release TEXT, found_release TEXT,
found_in TEXT); -- 'pre_release' or 'production'
INSERT INTO release VALUES
('checkout@2.4.0','checkout','2.4.0','a1b2c3','2026-09-01'),
('checkout@2.5.0','checkout','2.5.0','d4e5f6','2026-09-15');
INSERT INTO test_run VALUES
('r1','checkout@2.4.0','jenkins','integration',480,3),
('r2','checkout@2.4.0','github','e2e',110,1),
('r3','checkout@2.5.0','github','integration',492,0);
INSERT INTO bug VALUES
('B1','checkout@2.4.0','checkout@2.4.0','pre_release'),
('B2','checkout@2.4.0','checkout@2.4.0','pre_release'),
('B3','checkout@2.4.0','checkout@2.4.0','pre_release'),
('B4','checkout@2.4.0','checkout@2.5.0','production'),
('B5','checkout@2.5.0','checkout@2.5.0','pre_release'),
('B6','checkout@2.5.0','checkout@2.5.0','production');
""")
q = """
SELECT r.release_id,
SUM(b.found_in = 'production') AS escaped,
SUM(b.found_in = 'pre_release') AS caught,
ROUND(100.0 * SUM(b.found_in = 'production') / COUNT(*), 1) AS escape_rate_pct,
(SELECT SUM(t.failed) FROM test_run t WHERE t.release_id = r.release_id) AS failed_tests
FROM release r JOIN bug b ON b.introduced_release = r.release_id
GROUP BY r.release_id ORDER BY r.release_id"""
for row in db.execute(q):
print(row)
('checkout@2.4.0', 1, 3, 25.0, 4)
('checkout@2.5.0', 1, 1, 50.0, 0)
Release 2.4.0 introduced 4 defects, 3 caught before release and 1 escaped: 1 / 4 = 25.0%. Release 2.5.0 shows 1 of 2 = 50.0%, but it is only two weeks old, so treat it as immature. In the query, SUM(b.found_in = 'production') works because SQLite evaluates a comparison as 1 (true) or 0 (false), so summing counts the matching rows. Detection by stage would be the same query grouped by a found_stage column, which this small schema does not carry; with only the two-valued found_in column, all it can show for 2.4.0 is 3 of 4 defects caught before release, or 75% detection. The failed test count comes from the test-run table joined on the same release key, so quality and test data line up.
5. Consistency across 200 services and several CI systems
- A service registry of owners and teams, so every result maps to an owner. At scale nothing in the design changes: the same release key and the same query run per service, then roll up to teams and the organisation. As an illustration, 200 services releasing a few times a week produce on the order of a thousand release rows a week, tiny next to the test-result volume, so cost is driven by test results, not release records.
- Coverage checks: which services reported in the last day, what share of bugs lack a release, how fresh the data is. A dashboard shows these gaps instead of hiding them.
- Contract tests on the adapters, so a CI upgrade cannot silently change status meanings.
Trade-offs and pitfalls
- Attribution is imperfect, so publish the unmapped share beside every metric instead of pretending it is zero.
- Mature-cohort reporting (only reporting releases old enough to have had their defects found, using escapes found within a fixed window such as 30 days) trades timeliness for honesty.
- Central definitions can annoy teams with different release styles (continuous deployment versus versioned releases). Support both through the same release key rather than two metric definitions.
Given a CSV of defect or incident records with creation, detection and resolution timestamps, write code that computes time to detect and time to restore. How do you treat missing timestamps, overlapping records and mixed time zones?
Sample Answer
Direct answer
Normalise every timestamp to UTC (Coordinated Universal Time) first, then take differences. Define the two metrics explicitly: time to detect is detected_at - created_at (how long a defect or incident existed before someone noticed) and time to restore is resolved_at - detected_at (from noticing to fixed). I use detection as the start of restore time because that is the team's response window; measuring from created_at instead gives total time in production, and I would say which one I picked. Missing values are excluded from the metric that needs them (and counted, never treated as zero), duplicate rows are removed, and overlapping incidents on one service are merged when reporting total downtime.
Terms. ISO 8601 is the standard text format for date-times, such as 2025-03-01T10:00:00+05:30. A UTC offset like +05:30 says how far local clock time is ahead of UTC. A naive timestamp has no offset, so you cannot know which zone it was written in. A CTE (WITH ... AS) in SQL is a named temporary result that the next query can read from.
Approach
- Parse ISO 8601 timestamps (the standard
2025-03-01T10:00:00+05:30format that carries its offset) and convert to UTC. - Drop exact duplicate ids (re-exports of the same record).
- Compute both durations per record, skipping records missing a needed timestamp or with a negative duration, and report how many were skipped. In the code below, missing timestamps and negative restore times are listed; a negative time to detect is silently left out of that metric (none occur in the sample), so a production version should list those ids too.
- For distinct downtime, sort by start per service and merge overlapping windows.
Code (Python standard library, runs as is)
import csv, io, statistics
from datetime import datetime, timezone, timedelta
CSV_TEXT = """id,service,created_at,detected_at,resolved_at
1,api,2025-03-01T10:00:00+00:00,2025-03-01T10:12:00+00:00,2025-03-01T11:00:00+00:00
2,api,2025-03-02T09:00:00-05:00,2025-03-02T09:30:00-05:00,2025-03-02T11:00:00-05:00
3,web,2025-03-03T08:00:00+00:00,,2025-03-03T09:00:00+00:00
4,api,2025-03-01T10:30:00+00:00,2025-03-01T10:40:00+00:00,2025-03-01T11:30:00+00:00
1,api,2025-03-01T10:00:00+00:00,2025-03-01T10:12:00+00:00,2025-03-01T11:00:00+00:00
5,web,2025-03-04T15:00:00+05:30,2025-03-04T15:20:00+05:30,2025-03-04T16:20:00+05:30
6,db,2025-03-05T12:00:00,2025-03-05T12:10:00,2025-03-05T12:50:00
7,db,2025-03-06T12:00:00+00:00,2025-03-06T12:30:00+00:00,2025-03-06T12:10:00+00:00
"""
def parse(ts, naive_flags, row_id):
if not ts:
return None
dt = datetime.fromisoformat(ts)
if dt.tzinfo is None: # no offset given: assume UTC and record that we guessed
naive_flags.add(row_id)
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
def load(text):
seen, rows, notes = set(), [], {"duplicates": 0, "naive_assumed_utc": set(), "bad_order": []}
for r in csv.DictReader(io.StringIO(text)):
if r["id"] in seen: # exact re-export of the same record
notes["duplicates"] += 1
continue
seen.add(r["id"])
c, d, s = (parse(r[k], notes["naive_assumed_utc"], r["id"]) for k in ("created_at", "detected_at", "resolved_at"))
rows.append({"id": r["id"], "service": r["service"], "created": c, "detected": d, "resolved": s})
return rows, notes
def minutes(a, b):
return None if a is None or b is None else (b - a).total_seconds() / 60
def metrics(rows, notes):
ttd, ttr, skipped = [], [], []
for r in rows:
d1, d2 = minutes(r["created"], r["detected"]), minutes(r["detected"], r["resolved"])
if d1 is None or d2 is None:
skipped.append(r["id"])
if d1 is not None and d1 >= 0: ttd.append(d1)
if d2 is not None and d2 < 0: notes["bad_order"].append(r["id"])
elif d2 is not None: ttr.append(d2)
return ttd, ttr, skipped
def union_downtime(rows):
"""Minutes of distinct impact per service, merging overlapping created..resolved windows."""
total = {}
by_service = {}
for r in rows:
if r["created"] and r["resolved"] and r["resolved"] >= r["created"]:
by_service.setdefault(r["service"], []).append((r["created"], r["resolved"]))
for svc, spans in by_service.items():
spans.sort()
merged = [list(spans[0])]
for a, b in spans[1:]:
if a <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], b)
else:
merged.append([a, b])
total[svc] = sum((b - a).total_seconds() / 60 for a, b in merged)
return total
rows, notes = load(CSV_TEXT)
ttd, ttr, skipped = metrics(rows, notes)
print("records kept:", len(rows), "| duplicates dropped:", notes["duplicates"])
print("naive timestamps assumed UTC for ids:", sorted(notes["naive_assumed_utc"]))
print("resolved-before-detected ids excluded from TTR:", notes["bad_order"])
print("ids missing a timestamp (skipped for the metric they need):", skipped)
print("time to detect (min): n=%d mean=%.1f median=%.1f" % (len(ttd), statistics.mean(ttd), statistics.median(ttd)))
print("time to restore (min): n=%d mean=%.1f median=%.1f" % (len(ttr), statistics.mean(ttr), statistics.median(ttr)))
print("distinct downtime per service (min):", union_downtime(rows))
SQL alternative (SQLite), appended below the code above so it reuses the same data
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE raw (id TEXT, service TEXT, created_at TEXT, detected_at TEXT, resolved_at TEXT)")
db.executemany("INSERT INTO raw VALUES (?,?,?,?,?)",
[tuple(r.values()) for r in csv.DictReader(io.StringIO(CSV_TEXT))])
# strftime('%s', ...) converts any ISO offset to UTC epoch seconds; NULL or '' stays NULL via NULLIF.
query = """
WITH dedup AS (SELECT DISTINCT * FROM raw),
t AS (
SELECT id,
strftime('%s', created_at) AS c,
strftime('%s', NULLIF(detected_at, '')) AS d,
strftime('%s', NULLIF(resolved_at, '')) AS r
FROM dedup)
SELECT COUNT(d - c) AS n_ttd,
ROUND(AVG(d - c) / 60.0, 1) AS mean_ttd_min,
COUNT(CASE WHEN r >= d THEN 1 END) AS n_ttr,
ROUND(AVG(CASE WHEN r >= d THEN r - d END) / 60.0, 1) AS mean_ttr_min
FROM t
"""
print(db.execute(query).fetchone())
Output
records kept: 7 | duplicates dropped: 1
naive timestamps assumed UTC for ids: ['6']
resolved-before-detected ids excluded from TTR: ['7']
ids missing a timestamp (skipped for the metric they need): ['3']
time to detect (min): n=6 mean=18.7 median=16.0
time to restore (min): n=5 mean=57.6 median=50.0
distinct downtime per service (min): {'api': 210.0, 'web': 140.0, 'db': 60.0}
(6, 18.7, 5, 57.6)
Checking the numbers by hand: detect times are 12, 30, 10, 20, 10 and 30 minutes (id 3 has no detection time), so the mean is 112 / 6 = 18.7 and the median is 16. Restore times are 48, 90, 50, 60 and 40 (id 3 is missing a time and id 7 resolved before it was detected, so both are excluded), so 288 / 5 = 57.6. The api incidents 1 and 4 overlap (10:00 to 11:00 and 10:30 to 11:30 UTC), so they merge into 90 minutes, plus 120 for record 2 (09:00 at offset -05:00 is 14:00 UTC): 210.
Why web is 140 and db is 60. Web has two incidents: id 3 (08:00 to 09:00 UTC, 60 minutes, it has no detection time but downtime uses created and resolved) and id 5 (15:00 to 16:20 at +05:30, which is 09:30 to 10:50 UTC, 80 minutes). They do not overlap, so 60 + 80 = 140. Db has id 6 on 5 March (12:00 to 12:50, 50 minutes, naive so assumed UTC) and id 7 on 6 March (12:00 to 12:10 UTC, 10 minutes). They are on different days, so they do not overlap and are not merged: 50 + 10 = 60. Note id 7 is excluded from restore time because it resolved before it was detected, but its created-to-resolved window still counts for downtime.
Reading the SQL. strftime('%s', x) converts a timestamp text into seconds since 1970 in UTC, so subtraction is plain arithmetic. NULLIF(detected_at, '') turns an empty string into NULL, which SQL ignores in averages. COUNT(d - c) counts only rows where the difference is not NULL, so it counts rows that have both timestamps (6 here). SELECT DISTINCT * in the first CTE removes exact duplicate rows. SQLite here is just a convenient in-memory database; the same idea works in any SQL engine, including columnar ones.
Handling the three named problems
| Problem | Treatment | Why |
|---|---|---|
| Missing timestamps | Exclude from that metric only; report the count | Filling with zero or "now" biases the mean, and dropping the whole row loses a valid other metric |
| Overlapping records | Remove exact duplicate ids; merge overlapping windows per service for total downtime; keep incident-level times for per-incident statistics | Otherwise the same outage is counted twice |
| Mixed time zones | Require offsets, convert to UTC; naive timestamps get an explicit assumption (UTC here) that is recorded and reported | Comparing 09:00 -05:00 with 10:00 +00:00 as plain clock times gives wrong differences |
Complexity: parsing and durations are O(n); merging is O(n log n) for the sort. Memory is O(n). The SQL version does one pass after deduplication.
Edge cases and pitfalls
- Negative durations (resolved before detected) are data errors, so exclude and list them for repair.
- Report the median next to the mean; one long outage dominates a mean.
- Daylight saving changes create 23 or 25 hour days if you store local time without an offset.
- Naive timestamps are a guess. Ask the source system what zone it writes, and fix it at the source.
- Naming: DORA (dora.dev) now calls its recovery metric failed deployment recovery time, the time to recover from a deployment that fails and needs immediate intervention, measured from the failed deployment rather than from a detection timestamp. Older material calls it MTTR or time to restore service. State which start point your CSV supports before comparing with published benchmarks.
How do you define an escaped defect, attribute it to the release or environment that introduced it, and compute the rate per release? What minimal data has to be tagged consistently?
Sample Answer
Direct answer
An escaped defect is a confirmed defect (not a feature request or duplicate) that was present in a released build and was first found after release, normally in production. Attribute it to the release that introduced it, not the release in which it was found, and compute the rate per release as escapes divided by all defects attributed to that release. This works only if a handful of tags are recorded consistently at close time.
Structured elaboration
Definition and attribution
- Escape: first found in production (or, if you also measure stage leakage, found in any stage after the one that should have caught it).
- Attribution: the fix commit (the code change that repaired the bug) shows which lines were changed to repair it; looking up the history of those lines (for example
git blame) usually names the commit that introduced the bug, though it is a heuristic that refactors, reformatting or a fix that only adds missing code can mislead, so confirm by reading the change, and the release table tells you which release shipped that commit. If the history is unclear, a bisect (a search that tests commits to find the first bad one) does the same job. Record it during triage (reviewing and classifying a new bug report), not when the ticket is filed. A config change is attributed the same way: the release is whichever deployment or config push first put the bad setting into that environment. - Rate: escapes in release N divided by all defects introduced in release N, as a percentage.
- Stage attribution: record which stage should have caught it first (unit tests, integration tests, code review, QA, staging).
Minimum tags that must be consistent
| Field | Why it matters |
|---|---|
| Defect type (defect, not enhancement or duplicate) | Keeps the denominator clean |
| Severity, set by triage | Enables severity-split rates |
| Environment where first found, from a fixed list | Defines the escape |
| Found-at timestamp | Enables windows (for example within 30 days of release) |
| Introduced-in release | Attribution |
| Stage that should have caught it | Shows where to invest |
| Release table with deploy timestamps | Gives the join for the rate |
Worked example
Illustrative data. Release 7 introduced 10 confirmed defects: 4 found in development or CI (continuous integration, the automated build-and-test pipeline), 3 found in QA, 3 found in production.
- Escape rate = 3 / 10 = 30 percent.
- By severity: 5 of the 10 defects were severity 1 or 2, and 2 of those escaped, so the serious-defect escape rate is 2 / 5 = 40 percent. Reporting both stops a cosmetic-heavy release from hiding serious escapes.
- Stage attribution for the 3 escapes: one missed by integration tests (no test covered the flow), one by QA (staging data differed from production), one by code review.
Filled-in example for one defect, so you can see the tags on a real ticket:
| Field | Value |
|---|---|
| Type | defect |
| Severity | Sev2 (severity 2, a major feature broken with a workaround) |
| Environment first found | production |
| Found-at | 2026-07-09 14:20 |
| Introduced-in release | 7 (fix commit touches lines added in release 7 code) |
| Stage that should have caught it | integration tests |
The 5 severity 1 or 2 defects in release 7 are 5 rows like this one, and 2 of the 5 have Environment first found = production, which is where the 2 / 5 comes from.
Environment case: a bug appears in production only after a config push at release 7's deploy. Attribute it to release 7, tag the stage as "staging config differs", and note that the trigger was configuration, not code.
Restatement: a production defect found during release 8 is traced to a commit from release 6. Release 6 had 8 defects and 1 escape (1 / 8 = 12.5 percent). It now has 9 and 2, so 2 / 9 = 22.2 percent. This is why rates are reported "as of" a date and older releases are restated.
Trade-offs and pitfalls
- Gaming: production bugs relabelled as enhancements, severities downgraded, reports delayed. Guard with triage-owned severity, a monthly audit of ten closed tickets, and a reconciliation of support tickets against defects.
- Free text: use required dropdowns at close instead.
- Equal age: compare releases at equal age, since recent releases have not had time for escapes to surface.
- Scope: the rate measures the safety net, not a person; do not use it to compare individuals.
Unlock Full Question Bank
Get access to all 11 Quality Metrics and Test Reporting interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.