MTTR for Test Failures When Agents Do the Fixing

Most teams measure MTTR for production incidents: an alert fires, someone acknowledges, a timer starts. The same loop runs many times a day inside CI and almost nobody times it. A test goes red, a notification goes out, and then the failure is either fixed in minutes or left for days because the message is vague and the owner is unclear. That elapsed time is MTTR for test failures, and it shapes delivery speed more than most incident targets do.

Agentic quality engineering changes who closes the loop. Coding agents can now pick up a red build, propose a fix and push it, which can drive test-failure MTTR down sharply. Whether that is good news depends on how the failure was resolved. An agent that fixes the code improves MTTR honestly; an agent that loosens an assertion, adds a retry or skips the test improves the number and makes the suite worse.

This article shows how to capture the timestamps MTTR needs, store them in PostgreSQL or ClickHouse, compute failure episodes in SQL, avoid the pitfalls that make the numbers lie, and record how each failure was resolved once agents are part of the repair loop.

Build an API Automation Framework With Node.js

Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.

Learn more

Test Failure MTTR: What You're Actually Measuring

MTTR for test failures is the median (or P75/P95) elapsed time between a test's first failing run in a given branch or pipeline and the commit that makes it green again. It is not the same as build duration, flakiness rate, or failure frequency — those are inputs, not outcomes. A test that fails once and gets fixed in 8 minutes has a low MTTR. A test that fails intermittently for two weeks before anyone quarantines it has a catastrophic one, even if it only blocked three builds.

In a modern test architecture, MTTR sits at the intersection of your CI event stream and your test result store. It requires at minimum: a stable test identifier (suite + class + method, not just test name), a first_failed_at timestamp per failure episode, and a resolved_at timestamp when the same identifier passes again on the same branch. Everything else — owner attribution, root-cause tags, retry noise — is enrichment on top of that core model. Teams that skip the stable identifier step end up with MTTR numbers that are meaningless because renamed or parameterized tests look like new failures on every run.

Instrumenting, Storing, and Querying Test Failure MTTR

Start at the JUnit XML parser. Most CI systems (GitHub Actions, Jenkins, CircleCI) expose test results as XML artifacts but don't persist the run timestamp alongside each test case. Add a post-process step that enriches the XML with pipeline metadata before ingestion. Here's a minimal Python snippet that reads a JUnit XML file and emits structured rows ready for insertion:

import xml.etree.ElementTree as ET
import csv, sys
from datetime import datetime, timezone

def parse_junit(xml_path: str, pipeline_meta: dict) -> list[dict]:
    tree = ET.parse(xml_path)
    root = tree.getroot()
    rows = []
    run_ts = datetime.now(timezone.utc).isoformat()
    for suite in root.iter("testsuite"):
        for case in suite.iter("testcase"):
            failure = case.find("failure")
            if failure is None:
                failure = case.find("error")  # an Element with no children is falsy, so never use `or` here
            rows.append({
                "test_id": f"{suite.attrib.get('name')}.{case.attrib.get('classname')}.{case.attrib.get('name')}",
                "status": "failed" if failure is not None else "passed",
                "duration_ms": int(float(case.attrib.get("time", 0)) * 1000),
                "message": ((failure.get("message") or failure.text or "")[:2000]) if failure is not None else None,
                "run_at": run_ts,
                **pipeline_meta,   # branch, commit_sha, pipeline_id, job_url
            })
    return rows

if __name__ == "__main__":
    meta = {"branch": sys.argv[2], "commit_sha": sys.argv[3], "pipeline_id": sys.argv[4], "job_url": sys.argv[5]}
    rows = parse_junit(sys.argv[1], meta)
    if rows:
        writer = csv.DictWriter(sys.stdout, fieldnames=list(rows[0].keys()))
        writer.writeheader()
        writer.writerows(rows)

Pipe that CSV output into a PostgreSQL test_runs table. Once you have a stream of rows with test_id, status, run_at, and branch, computing MTTR is a window-function query away:

-- PostgreSQL: compute MTTR per test_id per failure episode
WITH episodes AS (
  SELECT
    test_id,
    branch,
    status,
    run_at,
    LAG(status) OVER (PARTITION BY test_id, branch ORDER BY run_at) AS prev_status
  FROM test_runs
),
failure_starts AS (
  SELECT test_id, branch, run_at AS first_failed_at
  FROM episodes
  WHERE status = 'failed' AND (prev_status = 'passed' OR prev_status IS NULL)
),
resolutions AS (
  SELECT test_id, branch, run_at AS resolved_at
  FROM episodes
  WHERE status = 'passed' AND prev_status = 'failed'
)
SELECT
  fs.test_id,
  fs.branch,
  fs.first_failed_at,
  r.resolved_at,
  EXTRACT(EPOCH FROM (r.resolved_at - fs.first_failed_at)) / 60 AS mttr_minutes
FROM failure_starts fs
JOIN LATERAL (
  SELECT MIN(res.resolved_at) AS resolved_at
  FROM resolutions res
  WHERE res.test_id = fs.test_id AND res.branch = fs.branch
    AND res.resolved_at > fs.first_failed_at
) r ON r.resolved_at IS NOT NULL
ORDER BY mttr_minutes DESC;

The lateral join matters: each failure episode is paired only with the first passing run after it, not with every later resolution of the same test. For teams running at high volume, a columnar store such as ClickHouse with a MergeTree table handles append-heavy result data and large scans better than a general-purpose row store, and avoids the VACUUM overhead PostgreSQL carries on that workload. Benchmark it on your own data before migrating.

Once the data is in place, wire a Grafana dashboard to it. A time-series panel showing P50/P75/P95 MTTR per week — grouped by team label or test suite — gives engineering leaders the signal they actually need. A stat panel showing "tests with MTTR > 48 hours (open)" is more actionable than any flakiness percentage. Linking each panel row directly to the Loki log stream for that test_id removes the hunt across five tabs during triage. For richer failure context during triage, connecting test failures to production logs closes the last gap between a red test and the service-level cause. If you want to go further and attach trace context to each test run, OpenTelemetry spans for test runs give you the full latency breakdown per test case alongside your MTTR data.

For GitHub Actions, a reusable workflow step can automate the entire ingestion pipeline after any test job:

# .github/workflows/test-ingest.yml (called from any test job via `uses:`)
on:
  workflow_call:
    inputs:
      junit_path: { required: true, type: string }
      branch:     { required: true, type: string }

jobs:
  ingest:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/download-artifact@v4
        with: { name: test-results, path: results/ }
      - run: |
          python scripts/parse_junit.py \
            "${{ inputs.junit_path }}" \
            "${{ inputs.branch }}" \
            "${{ github.sha }}" \
            "${{ github.run_id }}" \
            "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}" \
          | psql "${{ secrets.TEST_DB_URL }}" \
            -c "\copy test_runs (test_id, status, duration_ms, message, run_at, branch, commit_sha, pipeline_id, job_url) FROM PSTDIN WITH (FORMAT csv, HEADER true)"

Where MTTR Instrumentation Breaks Down in Practice

The most common failure mode is unstable test identifiers. Parameterized tests in Pytest or JUnit 5 often emit names like test_checkout[param0] where param0 changes between runs as fixture order shifts. Your episode-detection query sees a "new" test every run and MTTR is always zero — technically, every failure is immediately "resolved" because the next run has a different name. Fix this by normalizing test IDs at parse time: strip dynamic parameter suffixes or hash them consistently. It's unglamorous work, but without it your MTTR data is noise. CI test summaries undercount failures for exactly this reason — the aggregation layer hides what the raw event stream would reveal.

The second pitfall is conflating retry noise with resolution. If your CI runner retries a failed test three times and it passes on the third attempt, that looks like a resolved episode with a 90-second MTTR. It isn't — it's a flaky test that happened to pass. Filter out same-run retries before computing episodes: only mark an episode resolved when the test passes on a subsequent pipeline run with a different pipeline_id. This single filter eliminates the majority of artificially low MTTR readings that make dashboards look better than reality.

MTTR when an agent is doing the repair

When a coding agent is allowed to respond to red builds, test-failure MTTR usually drops, and that drop needs a second column before anyone celebrates it: how the episode was resolved. Record a resolution type on every closed episode, set from the diff of the commit that turned the test green:

  • code_fix: production code changed, test unchanged.
  • test_edit: the test file changed, especially its assertions.
  • retry_or_skip: a retry decorator, skip marker or quarantine tag was added.
  • env_fix: configuration, fixtures or infrastructure changed.

With that column, the MTTR report can be split by resolver and resolution type:

SELECT resolver,            -- 'agent' or 'human', from the fixing commit's author or PR label
       resolution_type,
       percentile_cont(0.5) WITHIN GROUP (ORDER BY mttr_minutes) AS p50_minutes,
       COUNT(*) AS episodes
FROM failure_episodes
WHERE resolved_at >= now() - INTERVAL '30 days'
GROUP BY resolver, resolution_type
ORDER BY resolver, resolution_type;

A fast agent MTTR made up mostly of code_fix episodes is a real gain. A fast agent MTTR made up of test_edit and retry_or_skip episodes is the agent optimizing for green. Those should require human review before merge, and your repository instructions for agents (for example .github/copilot-instructions.md) should say plainly that weakening an assertion or adding a skip is not an acceptable fix without approval.

For tests that call a model, define an episode on pass rate over repeated runs rather than on a single failure, or every sampling wobble opens and closes a fake episode. And measure the time an agent's proposed fix waits for human review as its own stage; it is often where the remaining MTTR lives. For the triage side, see auto-triaging failures with LLMs.

Myths That Keep Teams Flying Blind on Test Repair Time

Myth 1: Failure rate is a good proxy for repair cost. A suite with a 2% failure rate but a P95 MTTR of 5 days is far more expensive than one with a 10% failure rate and a P95 MTTR of 30 minutes. Failure rate tells you how often something breaks; MTTR tells you how much engineering time it consumes. Teams that optimize only for green build percentage end up with a long tail of quietly rotting tests that nobody fixes because the dashboard looks acceptable. Tracking MTTR surfaces that tail explicitly.

Myth 2: Flaky tests are a separate problem from MTTR. Flakiness is a MTTR driver, not a separate category. A test that fails 30% of the time and is never quarantined contributes an ongoing, open-ended MTTR episode. Treating flakiness as a tagging exercise rather than a time-cost problem means it never gets prioritized correctly. Model flaky tests as failure episodes with no resolution date — their "MTTR" is the time since they were first observed flaky, still accruing. If you're using AI tooling to speed up root-cause identification, be aware that AI root-cause suggestions misfire on environment failures, which are disproportionately responsible for long-tail MTTR outliers.

MTTR for test failures is a first-class engineering metric, not a vanity dashboard addition. Start with a stable test identifier scheme, a simple append-only results table, and the episode-detection query above — you can have a working P50/P95 MTTR panel in Grafana within a day. Once the baseline is visible, the high-MTTR outliers will tell you exactly where to invest: better error messages, ownership tagging, quarantine policies, or faster feedback loops. The data makes the argument for you.

Note: This article is for informational purposes only and is not a substitute for professional advice. If you need guidance on specific situations described in this article, consider consulting a qualified professional.

Understanding how systems actually work is the first step toward navigating them effectively.

Browse all articles