Detecting Flaky Tests with pytest-rerunfailures in AQE
The usual way to adopt pytest-rerunfailures is to add --reruns 3 and move on. The suite goes green and flaky tests disappear under retry noise. But a test that passes on its third attempt is a reliability event that got recorded as a pass. The useful signal is the retry count, the failure message from the first attempt and the pattern across runs.
Used deliberately, the plugin is the cheapest flaky-test detector you have. Agentic quality engineering adds two reasons to be deliberate. Coding agents asked to make a red pipeline green reach for reruns readily, so a rerun setting can change without anyone choosing to accept the flakiness it hides. And tests that call a model or drive an agent must never be retried until they pass: they are meant to be run several times and measured, and a rerun turns a pass rate into a misleading green.
This article covers what the plugin records and what it does not, a conftest.py hook that captures retry telemetry, SQL and a Grafana panel for the trend, the instrumentation mistakes that lose the signal, and how to keep reruns away from model-calling tests and unreviewed agent changes.
Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.
What pytest-rerunfailures Actually Measures (and What It Doesn't)
pytest-rerunfailures hooks into pytest's runtest protocol and re-executes a failing test up to N times before marking it failed. The final status written to JUnit XML is the last attempt's result — which means a test that fails twice and passes on attempt three is recorded as passed with zero evidence of the retries, unless you add instrumentation. The plugin reports each retried attempt to pytest's hooks with a custom rerun outcome, but nothing surfaces those counts in standard JUnit output by default.
In a modern test architecture, this plugin sits at the collection/execution layer — before any result aggregation in Allure, ReportPortal, or a ClickHouse/BigQuery warehouse. That position is actually ideal: you can intercept retry metadata in a conftest.py hook and emit it as structured JSON alongside the JUnit XML, giving downstream consumers the full picture. Without that step, your pass/fail rates are technically accurate but operationally misleading — and identifying flaky tests with real data becomes impossible when the data is already sanitized.
Building Retry Telemetry: From conftest.py to Grafana
Start by capturing retry counts in a conftest.py hook. The pytest_runtest_logreport hook fires for every attempt, including reruns. Accumulate counts per node ID and flush to a JSON Lines file at session end — this becomes your raw telemetry stream.
# conftest.py
import json, os, pytest
from collections import defaultdict
from datetime import datetime, timezone
_retry_counts = defaultdict(int)
_final_outcomes = {}
def pytest_runtest_logreport(report):
if report.when == "call":
# attempts that will be retried are reported with outcome "rerun"
if report.outcome == "rerun":
_retry_counts[report.nodeid] += 1
else:
_final_outcomes[report.nodeid] = report.outcome
def pytest_sessionfinish(session, exitstatus):
now = datetime.now(timezone.utc).isoformat()
rows = []
# one row per test, retried or not, so rates have a real denominator
for nodeid in set(_final_outcomes) | set(_retry_counts):
rows.append({
"nodeid": nodeid,
"retries": _retry_counts.get(nodeid, 0),
"final_outcome": _final_outcomes.get(nodeid, "unknown"),
"run_id": os.environ.get("GITHUB_RUN_ID", "local"),
"branch": os.environ.get("GITHUB_REF_NAME", "unknown"),
"recorded_at": now,
})
with open("retry_telemetry.jsonl", "w") as f:
for row in rows:
f.write(json.dumps(row) + "\n")
Wire this into your GitHub Actions workflow so the JSONL file is uploaded as an artifact and optionally shipped to a warehouse. The --reruns-delay 1 flag adds a one-second back-off between attempts, which reduces timing-sensitive false negatives without hiding the retry signal.
# .github/workflows/test.yml (relevant excerpt)
- name: Run tests with rerun telemetry
run: |
pytest tests/ \
--reruns 3 \
--reruns-delay 1 \
--junit-xml=results.xml \
-p no:randomly # disable random ordering during flake investigation
- name: Upload retry telemetry
if: always()
uses: actions/upload-artifact@v4
with:
name: retry-telemetry
path: retry_telemetry.jsonl
Once retry telemetry lands in PostgreSQL or BigQuery (a nightly ingest job works fine), this query gives you a CI reliability dashboard with flaky test trend output — retry rate by test, ranked by impact over the last 30 days:
-- PostgreSQL: flaky test retry rate, last 30 days
SELECT
nodeid,
COUNT(*) AS total_runs,
SUM(retries) AS total_retries,
ROUND(SUM(retries)::numeric / COUNT(*), 2) AS avg_retries_per_run,
COUNT(*) FILTER (WHERE retries > 0) AS flaky_run_count,
ROUND(
COUNT(*) FILTER (WHERE retries > 0)::numeric / COUNT(*) * 100, 1
) AS flakiness_pct
FROM retry_telemetry
WHERE recorded_at >= NOW() - INTERVAL '30 days'
GROUP BY nodeid
HAVING COUNT(*) >= 10 -- filter low-sample noise
ORDER BY flakiness_pct DESC
LIMIT 25;
For the Grafana panel, use a time-series query grouped by week to build a quarterly trend line scorecard — the kind that belongs in a quarterly reliability scorecard review. A panel JSON fragment using the PostgreSQL data source:
{
"type": "timeseries",
"title": "Weekly Flakiness Rate (retry > 0)",
"targets": [{
"rawSql": "SELECT DATE_TRUNC('week', recorded_at) AS time, ROUND(COUNT(*) FILTER (WHERE retries > 0)::numeric / COUNT(*) * 100, 1) AS flakiness_pct FROM retry_telemetry GROUP BY 1 ORDER BY 1",
"format": "time_series"
}],
"fieldConfig": {
"defaults": { "unit": "percent", "thresholds": {
"steps": [{"color": "green", "value": 0}, {"color": "yellow", "value": 5}, {"color": "red", "value": 15}]
}}
}
}
Wiring this dashboard to your Loki log stream, so the retry count in the panel links directly to the structured log line from the first failed attempt, removes the "which run do I look at?" loop from triage.
Two Instrumentation Mistakes That Kill the Signal
Mistake one: treating reruns as a pass/fail toggle rather than a metric. The default JUnit XML output from pytest-rerunfailures records only the final outcome. Teams ingest that XML into Allure or ReportPortal, see a green suite, and never build the retry-count dimension. The fix is the conftest.py hook above — it costs 30 lines and pays back immediately. Without it, you're auto-detecting flaky tests in CI blind, because the evidence is discarded before it reaches any analytics layer.
Mistake two: setting --reruns globally without a per-test cap or marker filter. A slow integration test that takes 90 seconds and reruns three times adds 4.5 minutes to your critical path on every failure — including real regressions. Use pytest markers to scope reruns to known-flaky tests: @pytest.mark.flaky(reruns=3), the per-test marker pytest-rerunfailures provides,, or a custom marker combined with a pytest_collection_modifyitems hook that applies --reruns only to marked tests. Global reruns on a large suite also inflate wall-clock time in ways that make CI observability metrics beyond flaky tests — queue depth, P95 duration — much harder to interpret.
Keep reruns away from model-calling tests and unreviewed changes
A test that checks an LLM feature or an agent passes some fraction of the time by design. If pytest-rerunfailures applies to it, a case that succeeds on 40% of runs will usually pass within four attempts and be reported green. That is the opposite of what the test is for. Write such tests to run the case several times and assert a minimum pass rate, mark them, and make sure reruns never apply to them:
# conftest.py: no reruns for model-calling tests
import pytest
def pytest_collection_modifyitems(config, items):
for item in items:
if item.get_closest_marker("eval"):
# an explicit reruns=0 marker takes precedence over --reruns
item.add_marker(pytest.mark.flaky(reruns=0))
Check the result in your telemetry: no eval test should ever appear with a retry count above zero. Report those tests by measured pass rate per model and prompt version instead, on their own panel.
For deterministic tests, treat rerun configuration as something a person decides. When a coding agent is asked to fix a failing pipeline, adding --reruns or a flaky marker is an easy route to green, and the retry telemetry above is what exposes it later. Say in your repository's agent instructions that reruns and flaky markers are not to be added or raised without flagging it in the pull request, and have CI fail or warn when a diff adds them. An agent that reports "this test is flaky, here is the first-attempt failure and its retry history" has done more useful work than one that silently made it pass.
Three Myths About Retry-Based Flaky Test Detection
Myth: a test that eventually passes isn't a problem. A 30% flakiness rate means roughly one in three pipeline runs is burning retry time and developer attention on a test that isn't catching real bugs. The pass/fail outcome is not the signal — the retry rate over time is. A test with zero failures but a 40% retry rate is costing you more than a test that fails cleanly once a week and gets fixed.
Myth: high retry counts mean the test is flaky. Retry counts are a symptom. The root cause could be a genuinely flaky test, an environment issue (network timeouts, shared state, resource contention), or a real intermittent regression that looks flaky but isn't. pytest-rerunfailures surfaces the signal; it can't classify it. You need the failure message from attempt one — not just the retry count — to distinguish environment noise from code-level non-determinism. Myth: adding reruns is free. Every rerun is a pipeline slot, a container spin-up, and CI minutes. On a 500-test suite with --reruns 3, a 10% flakiness rate adds up to 150 extra test executions per run. That's real cost, and it compounds across branches.
pytest-rerunfailures is most useful when it's treated as a telemetry source, not a reliability band-aid. Capture retry counts in conftest.py, ship them to a warehouse, and build a trend query that shows flakiness rate over time — not just today's pass/fail. Start with the SQL query above against your last 30 days of data; the top five rows will tell you more about your suite's health than any coverage report. From there, a per-test rerun policy and a weekly Grafana alert threshold will keep the signal clean.
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.