DEV Community

Emery Lin
Emery Lin

Posted on

Flaky Tests: Quarantine With an Expiry, Not a Retry

Automatic retries buy silence. Quarantine buys a name, an owner, and a deadline. If your CI red-flags a different test every week and someone re-runs the job until it goes green, you already have a flake problem — what you don't have is a record of it.

This post is about the smaller, more durable fix: move flaky tests into a quarantine manifest that CI validates on every pull request, run them without letting them block, and fail the build when an entry outlives its expiry date. This proposed procedure still needs review against the team’s CI setup.

Who this is for, and what you need first

You have a suite that mostly passes. A handful of tests fail intermittently for reasons nobody has time to chase — timing, shared state, network, or a model-backed check with nondeterministic output. Your merge gate is a single required job that either goes green or doesn't.

Prerequisites worth confirming before you start:

  • Your test runner can emit per-test results in a parseable form (JUnit XML or JSON). Without that, you cannot tell a quarantined test from a broken suite.
  • Test IDs are stable strings under your control, not line numbers. tests/billing/test_invoice.py::test_proration_rounding works; test #14 does not.
  • The manifest lives in the repository and changes through normal review. A quarantine list editable outside code review is a mute button.
  • Your CI can run one job as non-blocking while another job stays required. Most providers support this; check yours rather than assuming.

The decision: retry, quarantine, or delete

Option What it hides Ongoing cost Reasonable when
Auto-retry (N times) Earlier failures if attempts are not retained A final green status can hide a repeatable pattern You need a stopgap for hours, not weeks
Quarantine with owner + expiry The failure's blocking power, visibly A dated entry someone must clear You need the suite trustworthy while you investigate
Delete the test The coverage gap Silent loss of a check The test asserts nothing you still care about

Retries and quarantine answer different questions. Retries say "ignore this." Quarantine says "we know, here is who owns it, and here is when it dies." Pick quarantine when you want the second sentence written down.

Steps

1. Make per-test results machine-readable

Have the runner write results to a file, and keep that file as a CI artifact even when the job fails. Everything downstream depends on this one output. If a failing job discards its results, your quarantine logic has nothing to read.

2. Put the manifest in the repo

A minimal entry needs four fields: the test ID, an owner, the date it was quarantined, and the date it expires. The reason is optional but pays for itself during review.

# Illustrative manifest sketch — not a validated schema, not executed
entries:
  - test_id: "tests/billing/test_invoice.py::test_proration_rounding"
    owner: "@team-billing"
    quarantined_on: "2026-11-18"
    expires_on: "2026-12-16"
    reason: "rounding assertion depends on clock; needs injected time source"
    link: "<issue-tracker-id>"
Enter fullscreen mode Exit fullscreen mode

Keep expiry windows short by policy. A thirty-day default forces a decision; an open-ended entry is a deletion with extra steps.

3. Split the run: blocking vs. reported

Run the full suite once, then classify results against the manifest. Quarantined failures do not fail the pipeline. They must still run, still be reported, and still be counted.

# Illustrative pseudocode — not executed
results   = parse_results(artifact)
manifest  = load("ci/quarantine.yaml")
quarantined = {e.test_id for e in manifest.entries}
reject_if_collection_crashed_or_report_incomplete(results)
blocking  = [r for r in results if r.test_id not in quarantined]
failing   = [r for r in blocking if is_blocking_outcome(r, skip_policy)]

report.count("quarantine_failures", n_failed(results, quarantined))
report.count("quarantine_total", len(quarantined))
fail_build(failing)
Enter fullscreen mode Exit fullscreen mode

Two properties matter here. Quarantined tests keep running, so you learn when they stop failing and can promote them back. And the quarantine size is a published number, not a feeling.

4. Validate the manifest with a cheap, fast check

This is the part that keeps quarantine from becoming permanent. Run it on every pull request; it needs no test execution, only the manifest and the collected test list.

# Illustrative pseudocode — not executed
manifest = load("ci/quarantine.yaml")
today    = utc_date()
problems = []

for e in manifest.entries:
    if e.owner is empty:            problems.append("no owner: " + e.test_id)
    if e.expires_on < today:        problems.append("expired: " + e.test_id)
    if e.expires_on < e.quarantined_on or e.expires_on > e.quarantined_on + 30d:
        problems.append("invalid quarantine interval: " + e.test_id)
    if e.test_id not in collected:  problems.append("stale entry: " + e.test_id)

fail_build(problems)
Enter fullscreen mode Exit fullscreen mode

In this example the expiry date is the final allowed UTC date. Record all retries in the report and decide explicitly which skips are expected. A crash before a full report must fail the gate. A test that was renamed or deleted leaves an orphan entry that quietly inflates your count forever. That means collection must run before validation, or you validate against the IDs your runner reports from a discovery-only pass.

5. Ratchet the merge contract

State the rule in one sentence and make CI enforce exactly that: a merge requires all non-quarantined tests green on the merge result, the manifest valid, and the quarantine count no higher than the recorded baseline unless this PR raises the baseline explicitly.

The ratchet matters more than any single check. It converts "we'll clean it up" into "adding a second flaky entry needs a second approval." Raising the baseline is allowed — it should just be visible in the diff.

Test: does the gate do what you think?

You can check the validator without touching real tests, using throwaway manifests as inputs. This is a verification plan, not a run I performed; record what you actually observe.

  1. Expired entry. Point the validator at a copy of the manifest with one expires_on in the past. Expected observation: exit code non-zero, one error naming that test ID.
  2. Owner removed. Delete the owner field from one entry. Expected observation: a distinct error, not a crash on a missing key.
  3. Orphan entry. Add an entry whose test_id matches nothing the runner reports. Expected observation: a stale-entry error.
  4. Happy path. Restore the real manifest. Expected observation: exit code zero and no output beyond a count.
  5. Count ratchet, separately. Open a throwaway PR that adds one valid entry without changing the baseline. Expected observation: the ratchet job fails while the validator passes. Two checks, two signals — if both fail identically, they are one check wearing two names.

If any of these produces no observable difference, the gate is decorative. Fix that before trusting it with blocking authority.

Failure modes to watch

  • Quarantine creep. The count rises faster than it clears. The ratchet is your only brake; if the count is not printed on every PR, nobody will notice.
  • Permanent renewal. The same entry gets a new expiry date every month. Consider refusing a renewal without a changed reason field.
  • Non-blocking job that nobody reads. Zero visibility means the test is deleted, not quarantined. Publish the failure count somewhere a human sees weekly.
  • Single-red quarantine. One failure is not evidence of flakiness. Look for both passing and failing results on the same revision under comparable conditions. Repeated failures alone are also consistent with a deterministic defect. pytest on flaky tests
  • Mixed signals. If the quarantined job is also required, you are back to retries with a more complicated config.

Tradeoffs and where this does not fit

Quarantine trades blocking power for visibility. You accept a real coverage gap for a bounded time, and you pay for it with a manifest, a validator, and weekly attention. On a small suite with no flakes, that overhead is pure cost — skip it.

This approach also does not fit contexts where every test must block by policy, or where a required check cannot be split into blocking and non-blocking jobs. And it does nothing for a flake caused by nondeterministic infrastructure rather than a test: if your runners are starved of CPU, quarantine hides the symptom while the root cause stays.

Before adopting: confirm your runner's result format, decide who may raise the baseline, and agree on the default expiry window. Those three decisions determine whether the mechanism holds.

This article was created with AI assistance.

Top comments (1)

Collapse
 
hritik_chaudhary_5db0056f profile image
Hritik Chaudhary •

The expiry is what makes this work. Two things that keep a quarantine from rotting: keep running the quarantined tests in the non-blocking job and write their pass rate over the last N runs next to each manifest entry, so the owner sees whether it is still flaky or has quietly healed (a test that passes 30 runs in a row is a candidate to leave quarantine, not to wait out its date). And make the expiry failure message name the owner and link the manifest line, otherwise the build that fails on day 30 belongs to whoever happened to push that day. For finding the cause, rerunning a single quarantined test with the same seed and order, then with the order shuffled, separates timing flakes from shared-state ones quickly.