Overview
At 2 AM, the main branch of an e-commerce platform went red again. The on-call developer’s reaction was well-practiced: open the pipeline, glance at the failing test case name, skip the logs, and post “just rerun it” in the chat. Ten minutes later: green. Merge continues.
This is not an isolated case. Whenever I review CI health for clients, I run into the same phenomenon almost every time: a team’s first reaction to a red build is not “what broke?” but “run it again.” This is not laziness — it is a conditioned reflex trained over months by flaky tests. When three out of ten runs are false alarms, people naturally learn to rerun first and think later.
The problem is that once this reflex sets in, the CI red light is ruined. It no longer answers the most basic question: is the code actually broken or not? Developers gradually start ignoring red builds, release owners fall back on gut feeling, and by the time a real incident happens they discover that the gate which should have caught the defect was hollowed out long ago by “rerun until green.”
This article breaks down the 6 engineering decisions I’ve applied while governing flaky tests on our in-house CI/CD platform and at multiple client sites: how to detect, how to classify, how to quarantine, how to set the gate, how to define metrics, and who fixes what. It covers the data design behind detection, the debt ceiling for quarantine, the correct use of retry, and the trade-offs of tiered gates — with code and configuration kept as complete and copy-pasteable as possible.
One conclusion up front, so you don’t have to read halfway: a flaky test is not a small problem of “badly written tests” — it is a signal-integrity problem for CI. The goal isn’t to drive every flaky test to zero (that isn’t realistic); it’s to make the red light trustworthy again.
Decision 1: Define the Problem First — Why “Rerun Until Green” Turned CI Into the Boy Who Cried Wolf
What “Flaky” Actually Means
Let’s start with a definition you can act on, instead of stopping at the mantra “test is flaky”:
On exactly the same code revision, with the same dependencies and the same execution environment, a test case sometimes passes and sometimes fails, where the failure has no causal relationship with any code change — that is a flaky test.
Note the “same code revision” premise, because it determines which detection techniques you choose later. Many teams equate “it went red even though I didn’t change anything” with flakiness, but that isn’t enough — it could be an environment failure, or an upstream dependency hiccup. These three categories must be examined separately, otherwise every governance action that follows will go off the rails.
In data Google published in 2016, about 16% of tests were flagged as flaky — a figure the industry keeps citing, because it says two things: first, flakiness is a systematic problem at scale, not a handful of twitchy test cases; second, even an organization with Google’s level of test infrastructure can’t drive it to zero, so hoping that “just be careful when writing tests” will solve it is unrealistic.
Three Types of Red Signal Must Be Kept Apart
This is the first hurdle where governance fails for many teams: they lump three fundamentally different events into one “failure” bucket and then try to handle them with a single logic.
| Signal type | Characteristics | Correct stance toward merge |
|---|---|---|
| Real failure (actual defect) | Caused by this change, reproducibly | Must block the merge |
| Flaky (unstable) | Random outcome under the same code and environment, no causal link to the change | Don’t block, but keep the books |
| Environment / infrastructure failure | Node down, image pull timeout, dependency service flapping | Don’t block, but make retries meaningful |
The consequences of conflating them are concrete:
- If real failures and flaky tests are mixed together, the team can’t tell which one to trust, and ends up trusting none — the breeding ground for “rerun until green.”
- If you tag environment failures as flaky, you’ll “fix” a test defect that doesn’t exist, while what actually needs fixing is your runner infrastructure.
- If you bluntly decide that “red means broken, everything must be fixed,” the team burns its patience on a flood of false alarms and then collectively gives up.
I hit this wall in our in-house Go CI scheduling engine: early on we only recorded test results in two states, pass/fail. When we later wanted to compute whether a given case was flaky, the data simply wasn’t enough — you don’t know whether that failure came after the retries were exhausted, and you don’t know whether another execution of the same commit came back green. Without structured, traceable execution history, every analysis downstream is a castle in the air. That’s why Decision 2 starts by solving “where does the data come from.”
Why Retry Is Both the Cure and the Poison
Nearly every CI system ships with rerun. It’s handy, so it gets abused.
Retry solves “occasional failures,” not “flaky tests.” The two phrases look alike, but they mean completely different things in engineering terms:
- An occasional failure is a phenomenon — one particular run went red.
- A flaky test is a property — this case is nondeterministic and can go red in any single run.
Retry erases the phenomenon; the property remains. Worse, retrying to green destroys the evidence: if CI keeps only the final result (green), you will never know “a case was red a moment ago,” and you lose the very data source that reveals flakiness. The team’s flaky debt rolls over year after year, until one day some flaky case happens to mask a real bug.
So my first engineering decision is simple and counter-intuitive:
Retry can stay, but the retry process must be recorded. Every execution that “failed first, passed after retry” must be captured as candidate flaky evidence, instead of being overwritten by the eventual green.
Skip this one, and the remaining five decisions have no data to stand on.
Doing the Math: Flaky Test Costs Are Quantifiable
Nobody argues with “stable tests matter,” but nobody schedules work for it either. To get flaky-test governance onto the team’s backlog, you first have to put a number on the cost. The math isn’t hard — three inputs will do:
| Cost item | How to calculate | Notes |
|---|---|---|
| Rerun wait time | Each false alarm × average pipeline duration × number of people affected | One person waits 12 minutes per rerun; 8 false alarms a day is 96 minutes |
| Investigation time | Each false alarm × average debugging time | Open the logs, walk the stack, confirm it’s unrelated to this change — usually 5-10 minutes |
| Loss of trust | Not directly quantifiable, but the heaviest consequence | Real bugs get buried, or the team starts working around CI |
For a 30-person team, assume the main branch goes red 40 times a day and two-thirds of those are flaky. The “rerun + investigate” line item alone eats roughly 10 person-hours a day. That’s 200 person-hours a month — a full engineer-month thrown into waiting and confirming. This isn’t a scare story I made up; it’s what you get by multiplying the real red-build counts and retry counts in your logs.
The third item is the expensive one. Once trust shatters, the repair cost is non-linear — the effort you later spend getting everyone to believe in CI again is far greater than fixing dozens of test cases.
A Real Incident: Duplicate Charges Hidden Behind a Flaky Test
The most textbook case I’ve seen was at a financial SaaS client. Their payment idempotency test failed with roughly a 1-in-6 probability. The team investigated several times without locating the root cause, so they finally added @pytest.mark.flaky(reruns=3) to the test code, stamped a flaky_ignored marker into the CI config, and pretended it didn’t exist.
Three months later, a duplicate charge appeared in production. During the retrospective, they found that the “ignored” idempotency test had already started failing consistently two weeks earlier — but its failures had been swallowed by the reruns, and nobody had seen them.
Three mistakes compounded here: first, retry was used to mask a signal; second, the flaky marker was treated as a pardon rather than a to-do item; third, nobody periodically revisited whether those marked cases had degraded into real failures. The most dangerous thing about a flaky test isn’t the flakiness itself — it’s the invisibility cloak it gives to real defects.
Decision 2: How to Fish Flaky Tests Out of the Noise
Why Static Detection Can’t Be the Workhorse
Mention “detect flaky tests” and many people’s first instinct is static analysis of test code: look for sleeps, unfixed random seeds, shared state. Such tools do exist, and some achieve decent benchmark scores in research papers.
But at client sites I almost never treat them as the workhorse, and a 2026 paper explains why clearly: How Far Are We from Detecting Flaky Tests? On the Limits of Code-Based Detection points out that flakiness is not a static property of test code — the test source often contains none of the information needed to decide whether it is flaky. The authors analyzed three code-based detectors and found “shortcuts” in the commonly used benchmark datasets that inflate reported F1 scores; once a stricter project-isolation protocol is applied, those detectors perform no better than a constant baseline.
In engineering terms: static detection is fine as a hint, but don’t expect it to produce a trustworthy flaky list. Whether a case is flaky is decided by its execution history, not by its source code.
That matches my intuition too. The same assertEquals runs green ten thousand times in a stable test, and occasionally goes red in a flaky one because of a timing dependency — the code looks identical; the difference lives at runtime.
The Workhorse: Data-Driven Detection From Execution History
So the workhorse strategy comes down to one sentence: accumulate the structured result of every test execution, then mine the history for cases whose outcomes swing under the same code.
To compute flakiness, you need to record at least these dimensions:
| Field | Purpose |
|---|---|
| Test identity (suite + test name) | Uniquely identifies “the same test case” |
| Code revision / commit SHA | Establishes the “same code” premise |
| Environment fingerprint (runner image, dependency lockfile hash) | Establishes the “same environment” premise |
| Attempt number | Separates “failed on the first try” from “failed after retry” |
| Outcome (pass / fail / flaky / skipped) | The core state |
| Duration | Helps spot timeout-style flakiness |
| Timestamp | Windowed statistics |
Where the Data Comes From: Reporting Conventions on the CI Side
However strong data-driven detection is, someone has to feed it data first. That step happens inside CI: every time the test framework finishes an attempt, it reports one row. Reporting itself must be lightweight so it never becomes the pipeline bottleneck, so our rule is: write local JSONL synchronously, then batch-load into the database asynchronously after the pipeline finishes.
A workable approach is to have the test runner emit structured results directly, then wrap it in a thin layer that annotates attempt information. In Go, for example, go test -json already streams per-case events; we only need the retry layer to inject the attempt number:
// Pseudocode: the retry layer stamps each attempt with a sequence number and reports it
type Report struct {
Suite string `json:"suite"`
Test string `json:"test"`
CommitSHA string `json:"commit_sha"`
EnvPrint string `json:"env_fingerprint"`
Attempt int `json:"attempt"`
Outcome string `json:"outcome"` // pass/fail/error/skipped
DurationMs int64 `json:"duration_ms"`
PipelineID int64 `json:"pipeline_id"`
}
func runWithReport(pkg, test string, maxAttempts int) (string, error) {
for attempt := 1; attempt <= maxAttempts; attempt++ {
outcome, dur := runOnce(pkg, test)
report(Report{
Suite: pkg, Test: test,
CommitSHA: os.Getenv("CI_COMMIT_SHA"),
EnvPrint: os.Getenv("CI_ENV_FINGERPRINT"),
Attempt: attempt,
Outcome: outcome,
DurationMs: dur,
PipelineID: pipelineID(),
})
if outcome == "pass" {
return "pass", nil
}
}
return "fail", nil // all attempts failed -> real failure
}
The key is reporting every attempt, regardless of the final outcome. Only then does the path “failed on attempt 1, passed on attempt 2” leave a trace — and that is exactly what flakiness most typically looks like.
The Core Detection SQL
With data in hand, the core SQL looks for cases that produced both a pass and a fail for the same commit in the same environment:
-- Test cases judged flaky over the last 30 days (outcome swings within the same commit)
SELECT
suite,
test_name,
COUNT(*) AS runs,
COUNT(*) FILTER (WHERE outcome = 'fail') AS fails,
ROUND(
100.0 * COUNT(*) FILTER (WHERE outcome = 'fail') / COUNT(*), 1
) AS fail_rate_pct,
COUNT(DISTINCT commit_sha) AS distinct_commits
FROM test_executions
WHERE created_at >= now() - INTERVAL '30 days'
AND outcome IN ('pass', 'fail')
GROUP BY suite, test_name, commit_sha -- key: group by commit
HAVING COUNT(*) FILTER (WHERE outcome = 'pass') > 0
AND COUNT(*) FILTER (WHERE outcome = 'fail') > 0
ORDER BY distinct_commits DESC, fail_rate_pct DESC;
Including commit_sha in the GROUP BY is the crucial part — it guarantees you are measuring swings within one code revision, not differences between two different changes. Many homegrown detectors get this wrong: they count “failure caused by a code change” as flakiness, so the resulting list is full of genuine regressions and nobody trusts it.
If you want more confidence, require the swing to appear across at least N distinct commits before calling something flaky, so a single infrastructure hiccup isn’t misclassified as flaky. The threshold I use at client sites is 3.
Why Low-Frequency Flaky Tests Are Harder, and How to Catch Them
Data-driven detection has a natural blind spot: low-frequency flakiness. A case that fails 1% of the time may go red once a month, and “occasionally a pass, occasionally a fail” won’t pull it out. This is why many teams’ detection lists always catch the big fish and miss the small ones.
There are two backup approaches, used together:
- Repeated execution of the same case: for high-risk cases (those with a history of problems, or assertions involving time or concurrency), run them N times in nightly and look at the outcome distribution.
go test -count=10or pytest’s parametrized repetition both do the job. It’s expensive, so it only runs at night. - Cross-build comparison on the same code: exploit the fact that the same commit gets built repeatedly by multiple pipelines. The same commit running at different times on different runners and producing inconsistent results is a signal — even if it only goes red once per build, aggregating across builds makes it visible. This is exactly the path Develocity’s cross-build detection takes.
| Detection layer | Flakiness it catches | Cost | Where it runs |
|---|---|---|---|
| In-build retry | High frequency (passes on retry) | Low | Every CI run |
| Cross-build data aggregation | Medium frequency (same commit, inconsistent outcomes) | Medium | Background schedule |
| Proactive repeated execution | Low frequency (1%-class) | High | Nightly |
Only with all three layers stacked do you have a complete detection net. With in-build retry alone, you will never know that a batch of “goes red twice a year” cases is quietly corroding the credibility of your red light.
Comparing Detection Approaches
| Approach | Principle | Strengths | Limits | My recommendation |
|---|---|---|---|---|
| Static code analysis | Analyze test source for suspicious patterns | Needs no history, runs instantly in CI | Unreliable precision; papers show benchmark shortcuts | A hint, not a verdict |
| In-build retry detection | fail→retry→pass within one execution | Simplest to implement; most CI ships it | Only catches “passes on rerun,” misses low-frequency flakiness | The starting point, mandatory |
| Cross-build data detection | Aggregate history to find same-code swings | Covers low-frequency flakiness, high credibility | Needs structured reporting + storage | The workhorse, strongly recommended |
| Proactive injection (repeated execution) | Run the same case N times and inspect the distribution | Quantifies flakiness probability | Expensive, unsuited to every CI run | Nightly, for high-risk cases |
Gradle’s Develocity calls the first two intra-build and cross-build detection, with the same idea: in-build catches “only passes on retry,” cross-build catches “low-frequency, invisible within a single run.” The two are complementary, not either/or — in-build detection gives you instant feedback, cross-build detection gives you the complete list.
A Minimal Detector You Can Actually Run
If you don’t want to stand up heavy infrastructure right away, start with a Python script that pulls execution history from the CI API every day, computes the flaky list, and emits it as JSON for gates and dashboards:
#!/usr/bin/env python3
"""Compute the flaky case list from CI execution history and emit quarantine candidates."""
import json
from collections import defaultdict
def load_executions(path):
# one record per line: {suite, test, commit, env, outcome, attempt}
with open(path, encoding="utf-8") as f:
return [json.loads(line) for line in f if line.strip()]
def detect_flaky(rows, min_flip_commits=3):
"""Aggregate by (suite, test, commit, env) and find cases with swinging outcomes."""
buckets = defaultdict(set) # key -> {pass, fail}
for r in rows:
if r["outcome"] not in ("pass", "fail"):
continue
key = (r["suite"], r["test"], r["commit"], r["env"])
buckets[key].add(r["outcome"])
flaky_commits = defaultdict(set) # (suite, test) -> {commit...}
for (suite, test, commit, env), outcomes in buckets.items():
if outcomes == {"pass", "fail"}: # same code, same env: it both passed and failed
flaky_commits[(suite, test)].add(commit)
result = []
for (suite, test), commits in flaky_commits.items():
if len(commits) >= min_flip_commits: # only call it flaky if it swings across multiple commits
result.append({
"suite": suite,
"test": test,
"flip_commits": len(commits),
})
result.sort(key=lambda x: -x["flip_commits"])
return result
if __name__ == "__main__":
rows = load_executions("test_executions.jsonl")
flaky = detect_flaky(rows)
with open("flaky-report.json", "w", encoding="utf-8") as f:
json.dump(flaky, f, ensure_ascii=False, indent=2)
print(f"Detected {len(flaky)} flaky cases, written to flaky-report.json")
This script isn’t elegant, but it turns “flaky” from a perpetually debated adjective into an object that can be computed, versioned, and consumed by a gate. It is the foundation of the entire governance system. Without it, the quarantine, the gate, and the dashboard are all just talk.
The Time-Series Route: If You Already Run Prometheus
Some teams have no relational database handy but already run Prometheus. In that case, turning test results into metrics is one option — one time series per case, with suite/test/commit on the labels, and changes() to observe outcome churn:
# Number of outcome flips (pass/fail switches) for one case over the past 7 days
# A result of 1 means pass, 0 means fail
changes(ci_test_result{suite="pkg/payment", test="TestPaymentIdempotency"}[7d]) > 1
The upside of a time-series store is reusing existing monitoring infrastructure and building dashboards quickly; the downside is that high-cardinality labels (one timeline per case) will blow up Prometheus. So my advice is: details go into the relational database, aggregate metrics go into the time-series store. Details serve precise detection and attribution; aggregate metrics (flaky rate, red-build trust) serve dashboards and alerts. Don’t put details in a time-series store — that’s asking for trouble.
Decision 3: Classify by Root Cause Into Four Categories So Fixes Have Direction
Detecting the list is only step one. With a heap of names on the table, a team’s first reaction is usually “these tests are terrible, whoever wrote them should fix them” — and then nobody does. Because nobody knows where to start.
Flaky-test causes classify remarkably well. The industry’s fairly consensual four-way split is roughly: time-sensitive ~38%, resource contention ~29%, state leakage ~22%, external dependency ~10%. Exact proportions vary by project, but the ranking of these four holds in most projects.
| Root-cause type | Typical characteristics | Common pitfalls | Fix direction |
|---|---|---|---|
| Time-sensitive | Depends on sleep, now(), timeouts set too tight | Fixed sleeps instead of real waits; asserting on system current time | Replace sleeps with condition waits; inject a controllable clock |
| Resource contention | Concurrency / port / temp file / DB connection conflicts | Multiple cases fighting over the same port; shared connection pool without isolation | Randomize the resource pool (random ports, dedicated schemas) |
| State leakage | Global variables, static caches, test-order dependence | Dirty data from the previous case isn’t cleaned, so the next one fails | Enforce isolated fixtures; detect order dependence |
| External dependency | Calling real third parties, real networks, real time services | Treating flaky external services as stable dependencies | Stub/mock, or isolate with contract tests |
Time-Sensitive: Replace sleep With Condition Waits
This is the largest category and the easiest to fix. The typical symptom is sleep(2) and time.sleep(1) sprinkled everywhere — a developer casually adding a fixed wait so it can “get ready.” The problem: 2 seconds is enough locally, but not on a heavily loaded CI node.
The fix is to replace fixed waits with condition waits:
# Anti-pattern: fixed sleep, falls over the moment CI gets busy
time.sleep(2)
assert widget.is_visible()
# Correct: poll until the condition holds, with a timeout ceiling
def wait_until(predicate, timeout=5.0, interval=0.1):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if predicate():
return True
time.sleep(interval)
return False
assert wait_until(lambda: widget.is_visible()), "widget was not visible within 5s"
For assertions about “the current time,” don’t read the system clock directly — inject a controllable clock:
# Anti-pattern: depends on real time, breaks across midnight or time zones
assert record.created_at.hour == datetime.now().hour
# Correct: make the time source injectable
class Clock:
def now(self):
return datetime.now(timezone.utc)
# Inject a fixed clock in tests
fake = lambda: datetime(2026, 1, 1, 12, 0, tzinfo=timezone.utc)
record = create_record(clock=fake)
Resource Contention: Randomize the Resource Pool
Multiple cases grabbing the same port, the same database table, the same temp directory is the classic conflict under CI concurrency. There is only one fix direction: give every case resources it exclusively owns.
# Anti-pattern: hardcoded port, guaranteed to conflict under concurrency
PORT = 8080
# Correct: let the kernel allocate a free port
import socket
def free_port():
with socket.socket() as s:
s.bind(("127.0.0.1", 0)) # 0 = let the kernel choose
return s.getsockname()[1]
For databases, give each test case its own schema — or simply wrap it in a transaction and roll back at the end:
# pytest fixture: a dedicated transaction per case, rolled back on completion
@pytest.fixture
def db_session(engine):
conn = engine.connect()
trans = conn.begin()
session = Session(bind=conn)
try:
yield session
finally:
session.close()
trans.rollback()
conn.close()
State Leakage: Fixture Isolation and Order-Dependency Detection
This category is the most insidious. It doesn’t error out, it doesn’t time out — it just “happens to fail this time because the order was wrong.” It tends to be tied to execution order: running alphabetically locally is fine, but concurrent out-of-order execution in CI fails.
One particularly useful, less mainstream trick: enable random ordering in the test framework and record the seed. With pytest that’s pytest-randomly, which shuffles case order and prints the random seed on failure so you can reproduce it:
# Shuffle execution order; the seed is printed on failure and reproduces the same run
pytest -p randomly --randomly-seed=last -n auto tests/
# Reproduce the order under a specific seed
pytest -p randomly --randomly-seed=1704067200 tests/
If you want to actively hunt for order dependencies, run the suite twice — once in the original order, once reversed — and diff the results:
# Run forward then backward; cases with differing results are very likely order-dependent
pytest tests/ -p no:randomly
pytest tests/ --reverse # pytest-reverse plugin
There’s a more hidden trap on the Go side: the test cache. go test caches passing results by default, so you think you reran the test while it never executed at all and simply returned the previous green. You must disable caching when detecting flakiness:
# -count=1 forces re-execution and disables result caching; repeat 3 times to check stability
go test -count=3 ./...
# Track a single suspicious case for flakiness
go test -run '^TestOrderIdempotency$' -count=10 ./pkg/payment/
For front-end and end-to-end layers, Playwright’s trace is a debugging weapon — it records network, DOM, and console snapshots at failure time, making flakiness’s “nondeterminism” concrete as “what exactly happened in those 200ms”:
# Keep the trace on failure to debug mid-flight timing issues
npx playwright test --trace=on-first-retry
External Dependencies: Stubbing and Contract Testing
The smallest category, but not the least destructive — the test really does call a third-party API, really does send network requests. The repair approach is isolation in place:
- Stub whenever you can: replace external calls with controllable fakes so the test only validates its own logic.
- Verify the contract, not the implementation: use consumer-driven contract tests to separately verify “whether the interface agreement between us and them has changed,” running in a dedicated pipeline rather than mixed in with unit tests.
- When you really must call the real service: add timeouts + retries + a distinct network marker so this class of failure is identified as an “environment problem” rather than a “code problem.”
Auto-Classification: From Log Keywords to Labels
Classification can be automated — tag by keywords in the failure log, and let humans review:
| Log keyword | Root cause classification |
|---|---|
timeout, deadline exceeded | Time-sensitive |
address already in use, too many connections, lock | Resource contention |
duplicate key, already exists, dirty read | State leakage |
connection refused, EOF, 5xx | External dependency |
My third engineering decision: classify by root cause the moment detection finishes, or the list will rot in somebody’s inbox. Once classified, assign a different owner to each category: time-sensitive and state leakage go to the test authors, resource contention goes to infrastructure, external dependencies go to the owning service. The moment responsibility is clear, the fix rate changes.
Decision 4: Quarantine Instead of Deleting — and Don’t Blindly Retry
Why Quarantine Instead of Delete
Once flaky cases are detected, teams most easily take one of two extremes:
- Delete them — out of sight, out of mind. The price is permanently losing the scenarios those cases covered, and the same bugs will slip through again later.
- Keep everything and treat everything as blocking — correct but unsustainable; the team gets stuck at the gate by false alarms every day, and it eventually degenerates into everyone rerunning until green.
The right move is to quarantine: mark the case as “known flaky,” remove it from the blocking gate, but keep it in the suite, keep executing it, keep recording its results, and give it an explicit owner and a fix deadline.
Quarantine isn’t forgiveness; it’s “deferred enforcement + bookkeeping.” The case still runs; its failures just no longer block merges. Its failure records keep accumulating into the flaky-debt dashboard.
The Quarantine Lifecycle State Machine
A case should have a clear state path from the moment it is judged flaky to the moment it leaves the quarantine zone, rather than “it’s on the list and waits for someone to remember it”:
| State | Entry condition | Blocks merges? | Next step |
|---|---|---|---|
| Suspect | Detector first flags a swing | Still blocks | Watch for 2 weeks to confirm |
| Quarantined | Confirmed flaky and owner registered | Doesn’t block | Enters the fix queue |
| Fixing | Owner has claimed it | Doesn’t block | Verify after the fix |
| Watching | Fixed, green for N consecutive runs | Still doesn’t block | Release once stable |
| Released | Watching period passed | Blocking restored | Back to the normal gate |
| Overdue | SLA exceeded without a fix | Blocking restored | Force scheduling |
The key is in the last two rows: overdue automatically restores blocking. That single rule is the fuse that keeps the whole mechanism alive — process forces “quarantined cases nobody owns” to never be left lying flat indefinitely.
A Minimal Viable Quarantine Mechanism
The mechanism itself can be very light. Use a versioned quarantine file that CI reads to decide which cases don’t block:
{
"quarantined": [
{
"test": "TestPaymentIdempotency",
"suite": "pkg/payment",
"state": "quarantined",
"reason": "time-sensitive: asserts on a real timestamp",
"owner": "payment-team",
"since": "2026-11-01",
"sla_days": 14,
"issue": "PAY-2841"
}
]
}
Used in a CI gate like this (GitLab CI example):
# Gate step: real failures block, quarantined cases are recorded but don't block
test:
script:
- go test -count=1 -json ./... > test-report.json || true
- python scripts/ci_gate.py test-report.json flaky-quarantine.json
The core logic of ci_gate.py: with the quarantine list in hand, drop failures from known flaky cases out of the “blocking set,” while real failures still exit non-zero as usual:
#!/usr/bin/env python3
"""Decide whether the pipeline blocks, based on the quarantine list."""
import json, sys
report_path, quarantine_path = sys.argv[1], sys.argv[2]
quarantined = {
(q["suite"], q["test"])
for q in json.load(open(quarantine_path, encoding="utf-8"))["quarantined"]
}
blocking_failures = []
for event in map(json.loads, open(report_path, encoding="utf-8")):
if event.get("Action") != "fail":
continue
key = (event.get("Package", ""), event.get("Test", ""))
if key in quarantined:
print(f"[quarantined] {key} failed; not blocking (debt recorded)")
continue
blocking_failures.append(key)
if blocking_failures:
print(f"{len(blocking_failures)} real failures found, blocking the merge:")
for k in blocking_failures:
print(" -", k)
sys.exit(1)
print("No failures beyond known flaky cases; merge allowed")
Debt Ceiling: The Quarantine Zone Must Not Become a Dumping Ground
The biggest risk of a quarantine mechanism is that it turns into an unclaimed dumpster — once a case goes in, it never comes out. I saw an extreme case at a client: the quarantine list grew from 12 to 190 cases in 4 months, which amounts to waving through every unstable test and turning the test gate into a rubber stamp.
The countermeasure is to impose a debt ceiling and admission constraints on the quarantine zone:
- Count ceiling: once quarantined cases exceed X% of all cases (I use 5%), freeze new admissions — anyone who wants to quarantine a case must first fix an old one to earn a slot.
- Time limits: every quarantine record carries
sla_days; on expiry it automatically escalates to blocking, forcing the fix. - Mandatory reason:
reasonmust be a root-cause category plus one sentence; entering “unknown” is forbidden. - Visible on the dashboard: quarantine count, expiring count, and average dwell time go on the CI health dashboard so debt has nowhere to hide.
Quarantine Isn’t Forever: Automatic Release
What goes in must come out. If releasing quarantine depends on someone hand-editing a file, it will surely be forgotten. Make “automatic release” a script: once the watching period passes and the case has been green for N consecutive days, strip the tag automatically:
#!/usr/bin/env python3
"""Scan execution history and move quarantined cases that stayed green for N days out of quarantine."""
import json
from datetime import datetime, timedelta
from collections import defaultdict
STABLE_DAYS = 7 # release only after 7 consecutive green days
quarantine = json.load(open("flaky-quarantine.json", encoding="utf-8"))
rows = [json.loads(l) for l in open("test_executions.jsonl", encoding="utf-8") if l.strip()]
cutoff = datetime.utcnow() - timedelta(days=STABLE_DAYS)
recent = defaultdict(list)
for r in rows:
ts = datetime.fromisoformat(r["created_at"])
if ts >= cutoff and r["outcome"] in ("pass", "fail"):
recent[(r["suite"], r["test"])].append(r["outcome"])
still_flaky = []
released = []
for item in quarantine["quarantined"]:
outcomes = recent.get((item["suite"], item["test"]), [])
if outcomes and all(o == "pass" for o in outcomes):
released.append(item["test"]) # watching period passed, untag it
else:
still_flaky.append(item)
quarantine["quarantined"] = still_flaky
json.dump(quarantine, open("flaky-quarantine.json", "w", encoding="utf-8"),
ensure_ascii=False, indent=2)
print(f"Released {len(released)} cases: {released}")
This script runs in a daily background job; humans only handle the cases that “fail to be released and then regress.” Automatic entry, automatic exit — that’s the only way people have energy left for the genuinely hard cases.
The Right Way to Use Retry
Retry isn’t unusable either — but retry only known flaky cases, and always record the retry outcome. Blindly retrying every case three times hands every real bug three escape routes.
| Retry strategy | Effect | My verdict |
|---|---|---|
| Retry all cases 3 times | Fewer false alarms, but real bugs can also be erased by retries | Not recommended |
| Retry only the quarantine list | Fewer false alarms; real failures still block as usual | Recommended |
| Forbid retry altogether | The most honest signal, but the team is driven mad by false alarms | Aggressive; only for small, stable suites |
Gradle’s Develocity calls this outcome control — detection is detection, and deciding whether the end result counts as pass or fail is a separate, configurable decision. That layering is smart: detection (is this flaky?) and disposition (should flaky count as a failure?) are two different things, so don’t knead them together in one place.
Decision 5: Gate Design — Should a Red Build Block the Merge
Separate “Blocking” From “Alerting”
Many teams’ gates have exactly one tier: red blocks. As soon as flakiness grows, that tier turns the gate into the team’s public enemy. The right approach is to tier the signals so events of different nature take different paths.
| Event | Blocks the merge? | Notification | Bookkeeping |
|---|---|---|---|
| Real failure | Blocks | Immediately @ the committer | Enters the defect system |
| Quarantined flaky failure | Doesn’t block | Daily digest | Enters the flaky-debt dashboard |
| New flaky case (not yet quarantined) | Blocks (first-offense warning) | Immediately @ the committer | Reminder to quarantine it |
| Environment / infrastructure failure | Doesn’t block (auto-retry) | Daily digest | Enters the infrastructure-failure dashboard |
| Flaky debt over threshold | Blocks new quarantines | @ all engineers | Freeze admissions |
This table is the traffic rules of the entire governance system. It separates “not blocking” from “not caring” — a flaky test doesn’t block the merge, but it enters a ledger with names, owners, and accountability.
The Trade-Offs of Tiered Gates
Gate strictness must track signal quality. When the signal isn’t trustworthy, the stricter the gate, the more the team will work around it. This is the deepest pit I’ve fallen into.
One client started with a hard gate of “any failure blocks the merge,” while the flaky rate was as high as 30%. Developers were blocked and rerunning every day; two weeks later people started routing around CI — test locally, then force merge. The strict gate actually lowered quality.
So we moved to a staged strategy:
- Stage 1 (establishing the signal): flaky tests don’t block; spend a month accumulating detection data so the flaky list stabilizes.
- Stage 2 (paying down debt): start capping the quarantine zone and force teams to fix the existing flaky backlog. The goal for this stage is to push the flaky rate below 10%.
- Stage 3 (trustworthy signal): once the red light is credible enough (real failures > 90%), tighten the gate step by step, and finally land “an unquarantined flaky test blocks on first appearance.”
I’ve measured the value of this data at a client site: before governance, the main branch averaged 40 red builds a day, fewer than a third of them real failures. After two months of classification + quarantine + bookkeeping, red builds dropped to around 15 a day, but the share of real failures rose to 87%. Fewer red builds — and every one of them deserves to be taken more seriously than before. That is the real outcome of governance: not fewer red builds, but credible red builds.
This is the same reasoning we apply to alert governance. In monitoring work, we cut alert delivery from minutes down to 5 seconds and fault localization from 30 minutes down to 8 (Related: MTTR from 40 Minutes to 8: Cutting Fault Localization Time by 5x with a Four-Layer Defense) — never through “more sensitive alerts,” but through the signal-to-noise ratio. A CI red build is like a P0 alert: both are essentially asking “should this wake a human up?” Get the judgment wrong and the signal is worthless.
The pitfalls of CI security gates are isomorphic — when the false positive rate is high, teams systematically ignore gate results (Related: False Positive Rate from 70% to 5: A Four-Layer Security Gate Design and False Positive Management in CI/CD). Flaky-test governance and false-positive governance are two faces of the same “signal credibility” problem.
A Complete Gate Pipeline Implementation
Stringing the rules above together, a workable gate pipeline looks roughly like this (GitLab CI):
stages: [test, gate]
unit-test:
stage: test
script:
- go test -count=1 -json ./... > test-report.json || true
artifacts:
when: always
paths: [test-report.json]
flaky-gate:
stage: gate
needs: [unit-test]
script:
# 1) Run the gate decision: known flaky doesn't block, real failures do
- python scripts/ci_gate.py test-report.json flaky-quarantine.json
# 2) Update flaky-debt dashboard metrics (this step must not fail the build)
- python scripts/report_flaky_metrics.py test-report.json || true
# 3) Check whether the debt has exceeded the ceiling (block new quarantines if so)
- python scripts/check_quarantine_budget.py flaky-quarantine.json
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
The division of labor among the three scripts is clear: ci_gate.py decides “can this go out,” report_flaky_metrics.py only keeps the books and must not fail, and check_quarantine_budget.py asks “is the quarantine zone about to blow up?” Split the three responsibilities — decision, bookkeeping, budget — and each script can be tested and maintained on its own, with failures easy to localize.
Combining With a Merge Queue So the Gate Actually Blocks
If your team uses a merge queue (GitHub’s, or GitLab’s merge train), one detail deserves attention: the gate must run against the snapshot the queue is about to merge, not against the branch’s stale state. Otherwise you get the classic embarrassment of “green locally, red on the main branch after the queue merges” — because the queue re-composes and runs on the latest baseline, and if the gate is still judging the branch’s own old commit, the two don’t line up.
Our approach is to keep the commit dimension used by flaky detection identical to the composed commit the queue actually runs, so the “same-code swing” judgment is accurate. Skip this step, and data-driven detection produces a flood of “phantom swings” — in reality, results from two different commits being compared against each other.
Decision 6: Metrics and Organization — Governance Without an Owner Is Bound to Stall
Turn Flakiness Into a CI Health Metric
Governance must be measurable to be sustainable. I suggest one metric as the core SLI for CI health:
CI Flakiness Rate = number of cases judged flaky / total number of cases, paired with two derived metrics: red-build trust (real failures as a share of all red builds) and average quarantine dwell time.
These three metrics tell you at a glance whether governance is progressing or stalling:
- Flaky rate down, red-build trust up → improving.
- Average quarantine dwell time keeps growing → someone is throwing things in and nobody is clearing them out.
- Flaky rate flat while red-build counts drop → most likely everyone is rerunning to green and hiding the dirty data.
These three metrics can be built as Prometheus recording rules and wired into your existing monitoring (we already run Prometheus/Grafana):
# recording rules: turn flaky metrics into periodic series for dashboards and alerts
groups:
- name: ci_health
interval: 1h
rules:
- record: ci:flakiness_rate
expr: >
count(ci_test_flaky_cases) / count(ci_test_cases) * 100
- record: ci:red_build_trust
expr: >
sum(rate(ci_build_failures_total{kind="real"}[7d]))
/ sum(rate(ci_build_failures_total[7d])) * 100
- alert: CIQuarantineGrowing
expr: ci_quarantine_case_count > 0.05 * ci_test_cases
for: 1d
labels:
severity: warning
annotations:
summary: "Quarantined cases exceed 5% of the total; new quarantine slots frozen"
What a Healthy CI Dashboard Should Look Like
Metrics must land on a dashboard everyone can understand, not scatter across a pile of script output. I usually use four panels:
| Panel | What it shows | What question it answers |
|---|---|---|
| Red-build trust trend | Real failures / total red builds, 7-day rolling | Is the gate still worth trusting |
| Flaky-debt waterline | Quarantine count, expiring count, overdue count | Is it about to blow up |
| Top 10 flaky | Highest failure-rate cases and their owners | Who to fix first this week |
| Governance progress | Month-over-month flaky rate | Is this effort still moving |
The value of a dashboard isn’t that it looks good — it’s that it turns “debt” into public information. When a case sits on the Top 10 flaky list for months, its owner starts to feel awkward — and that peer-visibility pressure works better than any process rule.
Who Fixes It: Ownership Principles
The thing governance fears most is the question of “who fixes it” hanging in the air. My ownership principles:
- The case has a clear author/owning team: time-sensitive, state leakage, and wrong-assertion cases go to the business team that owns the test author.
- The case is a platform/infrastructure test: resource contention and environment isolation issues go to the CI platform team.
- External dependency cases: go to the owner of the depended-on service, or the case author takes responsibility for stubbing as a fallback.
- Unattributable cases: default to the CI platform team as a catch-all, but they must enter an “unclaimed” queue — never left dangling.
The key is that every quarantine record must carry an owner field, and that field is mandatory in the gate. Quarantine without an owner = debt with no end date.
Time Boxes and Budget
Don’t count on “fixing one in passing.” Flaky-test fixes are work that needs sustained attention, and squeezed into business iteration they will be postponed indefinitely. What we do now:
- A fixed 2-hour time box every week (say Wednesday afternoon), for exactly one thing: clear flaky debt, fixing from the highest failure rate down.
- No flaky fixes before a release: don’t touch tests inside the release window, to avoid “the test fix introduced a new problem.”
- Shift it left: put test stability on the code-review checklist — a new case only passes if it can run green 20 times in a row.
This sounds like process overhead, but it’s the only way to turn “governance” from a one-off campaign into a daily habit. I’d rather compare it to how we built an SLO system for a new-energy logistics platform — not through one sprint, but by turning reliability into a number someone looks at every day. CI stability works exactly the same way.
A Runbook: Standard Workflow for One Flaky Test
To make the “2-hour time box” genuinely efficient, I’ve hardened the workflow into a runbook you can simply follow:
- Locate: take the Top 1 case from the flaky report and open its failure log.
- Classify: determine the root-cause category from keywords (timeout / address in use / duplicate key / connection refused).
- Reproduce: rerun locally with
-count=20or--randomly-seed=lastto confirm the nondeterminism reproduces reliably. - Quarantine (if it can’t be fixed right away): register owner + sla_days and unblock the team first.
- Fix: apply the matching technique for the category (condition waits / resource randomization / fixture isolation / stubbing).
- Verify: 20 consecutive green runs, then enter the watching period.
- Archive: the automatic script untags it after the watching period; if it regresses, go back to step 2.
Write the process down so that every flaky fix doesn’t restart from “what on earth is this thing.” Our team keeps this runbook pinned next to the CI dashboard; a new hire used it to handle a case in their first week, far faster than word-of-mouth training.
Common Anti-Patterns
After stepping in enough pits, you end up with a few “looks useful, actually harmful” practices worth listing to save the next person some time:
| Anti-pattern | Apparent benefit | Real cost |
|---|---|---|
| Blind retry on everything | False alarms drop immediately | Real bugs get swallowed; the red signal dies completely |
| Deleting flaky cases | A clean dashboard | Coverage gaps become permanent; bugs reach production |
| Quarantine with no ceiling | Nobody gets blocked | The quarantine zone balloons; the gate exists in name only |
| Detect without classifying | A comprehensive list | Nobody knows where to start; the list rots in an inbox |
| Treating environment failures as flaky | Simple attribution | You fix the wrong place; runner infrastructure problems never get fixed |
| Hard gate right away | Looks strict | The team routes around CI; quality actually declines |
These anti-patterns share one thing: they all trade short-term convenience for long-term loss of trust. Flaky-test governance is ultimately an engineering campaign against short-term temptation — every “just rerun it” digs a pit for the future.
Comparing Alternatives: Build In-House or Adopt a Platform
There are two paths for flaky-test governance, depending on your scale and team.
| Approach | Capabilities | Adoption cost | Suitable scale |
|---|---|---|---|
| Fully in-house (SQL + scripts + quarantine file) | Detection + quarantine + gate; capability sufficient | Low; runnable in 1-2 weeks | Small and mid-size teams, 1-20 repositories |
| Open-source tools (rerun frameworks with built-in flaky reporting) | Detection-focused; quarantine must be built | Medium | Teams that already have a mature CI |
| Commercial platform (Develocity-class) | Detection + outcome control + Tests API, a complete chain | High; per-seat/per-usage pricing | Large orgs, many languages and repositories |
My recommendation has a clear dividing line:
- Under 20 repositories, build in-house first. The core is three things: structured reporting, swing detection, a quarantine file. One client stood it up in two weeks — shorter than a procurement cycle, and perfectly fitted to their own process.
- Cross-language, multi-repository, thousands of test cases, and no capacity to maintain infrastructure — then consider a commercial platform. Its cross-build detection works out of the box, provided you’re already using its build scans.
- Don’t buy a platform on day one. The bottleneck in governance is never the tool — it’s that nobody owns it. However good the tool, if nobody claims the quarantined cases, it still stalls.
Summary
Governing flaky tests in CI is essentially a battle to defend signal credibility. The six decisions in review:
- Define first, then act: flakiness means “outcomes swing under the same code and environment” — don’t conflate it with real failures or environment failures. Conflation is the number one cause of governance failure.
- Detect from execution history; don’t worship static detection: flakiness is a runtime property, computed from data, and static code analysis is only a hint. In-build retry, cross-build aggregation, and proactive repeated execution are three complementary layers.
- Classify by the four root causes immediately after detection: time-sensitive / resource contention / state leakage / external dependency, then assign owners by category. Enabling random ordering for tests and disabling the test cache in Go flushes out hidden order dependencies.
- Quarantine rather than delete, and set a debt ceiling: quarantined cases keep executing, enter the debt dashboard, carry an owner and an SLA, and get released automatically once the watching period passes. Freeze new admissions when the quarantine zone exceeds 5% of the total.
- Tier the gate instead of applying one blunt rule: real failures block, known flaky doesn’t block but is recorded, environment failures auto-retry. Roll out in stages and tighten only once the signal is credible.
- Metrics and organization are both indispensable: flaky rate, red-build trust, and quarantine dwell time go on the dashboard; a fixed weekly time box pays down the debt.
One closing line: the goal of governing flaky tests isn’t fewer red builds — it’s red builds that deserve to be believed again. A team has succeeded at governance when its first reaction to a red build goes back from “just rerun it” to “what broke?” Until then, all your CI gates, test coverage, and quality red lines rest on a signal that will lie to you at any moment.
References & Acknowledgments
The following resources were consulted during the writing of this article. Thanks to the original authors for their contributions:
- Flaky Tests Detection — Develocity — Official Gradle/Develocity documentation covering the design of intra-build and cross-build flaky detection, outcome control, and the Tests API quarantine mechanism
- How Far Are We from Detecting Flaky Tests? On the Limits of Code-Based Detection — arXiv paper arguing that flakiness is not a static property of test code and that code-based detectors perform poorly under stricter evaluation protocols, supporting the choice of execution history as the primary detection method
- MDFlaker: A tool for multi-factor detection and root cause analysis of flaky tests — Azeem Ahmad et al., Software Impacts (Elsevier); a multi-factor detection and root-cause analysis method built on traceback coverage, test smells, flip frequency, and case size
- Flaky tests — GitLab development docs — GitLab’s publicly documented flaky governance practice: rspec-retry automatic retries, reporting flaky examples as JSON, and raising alerts on branches
- Farewell to “Schrödinger’s Tests”: Full-Chain Flaky Test Governance in Practice — Zhihu column covering the definition of flaky tests, the four layers of harm (trust collapse / efficiency loss / quality risk / team morale), and a compilation of public data from Google and Microsoft
- The Four Root Causes of Flaky Tests and a Practical Fix Guide — CSDN, covering the root-cause distribution (time-sensitive 38.1%, resource contention 29.3%, state leakage 22.5%, external dependency 10.1%) plus a three-stage detection and five-step fix workflow
- FlakeGate: Stop “Rerunning Flaky Tests to Green” — CSDN, discussing how “rerunning to green” pollutes the CI failure signal and destroys a team’s trust in red builds