WORKINGCHAPTER 13

Flaky tests: causes, quarantine and cure

A test that fails one run in twenty is not noise: it is a measurement, and you can take it, then fix the wait, the shared state or the product

60 MINSOFTWARE TESTING AND QUALITYUPDATED 2026-11-23
PREDICT

A test submits a product to a search index, sleeps 50 ms, and asserts the product is searchable. The index applies each update after a random delay between 0 and 2 times its average lag. With an average lag of 50 ms the test fails about half the time. The code is correct. What happens to the failure rate if the index is slower, with an average lag of 200 ms?

A flaky test is one that passes and fails on the same code. That is a bad property for a check, and it is worse than it looks. A test’s whole job is to carry information: red means broken, green means safe. A flaky test sends the same signal for a broken and a working system, so it carries none. It also costs: every red build now needs a human to decide whether it counts, and the humans learn to decide quickly and wrongly.

Flaky is a rate

Start by turning the word into a number. “It’s flaky” is an opinion; “it failed 23 of 50 runs on an unchanged commit” is a measurement. With a number you can say whether a change helped, and you can compare two tests and fix the worse one first.

Measuring is a loop: run the test many times on the same code and count failures. Two cautions. First, a small count lies. A test that fails one run in twenty passes ten runs in a row about 60% of the time, so ten green runs prove almost nothing. Gruber and colleagues, who studied flaky tests in 22,352 Python projects, estimate that to be 95% confident a passing test is not flaky you need about 170 reruns. That is why the lab runs 200. Second, run it the way CI runs it: the same random order, the same parallelism, the same machine load. A test that is stable on your idle laptop and flaky on a busy runner is flaky.

Where do the failures come from? The research agrees on a short list. Luo and colleagues at Illinois (FSE 2014) classified the fixes of flaky tests in open-source Java projects and found a few causes covering most of them, led by async waits, concurrency and test-order dependence. The Python study found a different mix: order dependence was the largest cause, 59% of 7,571 flaky tests, with test infrastructure at 28%. Fowler’s older article groups them as lack of isolation, asynchronous behaviour, remote services, time and resource leaks. You will meet three in this chapter, because they are the three Ojaline’s suite can show you.

Cause The test… Typical sign Cure
A wait that guesses sleeps, then asserts on work done elsewhere fails more under load; passes when run alone wait on the condition, with a deadline
Shared state reads something another test left behind passes in file order, fails when shuffled or parallel each test builds its own state
A race in the product is correct, and exposes a bug that depends on timing fails on a rate that does not move with load fix the product; the test was right

The third row matters most. Not every flaky test is a bad test. Some are a good test reporting a real intermittent bug, and the worst response is the one that makes them go quiet.

Cause one: the wait that guesses

Ojaline’s search index is eventually consistent, like most search clusters. A new product goes onto a queue, and a worker applies it after a delay. In the lab, checkout/search_index.py models that: SearchIndex(lag_s, jitter) queues documents, a background thread applies each one after lag_s seconds, or after a random 0 to 2 times lag_s when jitter is on. The product exists, and search does not know yet.

The test in tests/test_flaky_example.py does what many first tests do:

index = SearchIndex(lag_s=0.05, jitter=True)
index.submit({"id": 7, "seller_id": "s", "name": "Shea butter", "status": "published"})
time.sleep(0.05)
assert [d["id"] for d in index.search("shea")] == [7]

The sleep is a guess that the worker needs at most 50 ms. With a delay spread over 0 to 100 ms, the guess is right about half the time. On a quiet laptop with a real lag of 20 ms it would pass for months. Then CI gets busy, the worker is slow, and the test fails one run in twenty. The code was never wrong.

▶ SIMULATION
THE TEST
waits: 100 ms, fixed
deadline: none
THE JOB (CORRECT)
machine load: x2
—
WHAT THE TEAM SEES
red builds: 0 of 0
wrong alarms: 0
last—
✓ the build is red exactly when the code is wrong
SCHEDULE
01[TEST]test: start job, sleep 100 ms, assert it finished
02[CI]run 1: start the job, wait, assert
03[CI]run 2: start the job, wait, assert
04[CI]run 3: start the job, wait, assert
05[CI]run 4: start the job, wait, assert
06[CI]run 5: start the job, wait, assert
07[CI]run 6: start the job, wait, assert
08[CI]run 7: start the job, wait, assert
09[CI]run 8: start the job, wait, assert
10[CI]run 9: start the job, wait, assert
11[CI]run 10: start the job, wait, assert
12[CI]run 11: start the job, wait, assert
13[CI]run 12: start the job, wait, assert
14[TEST]report
Start of sleep 100 ms, loaded ci scenario. 14 steps.
test('job finishes', () => {
  startJob();
  sleep(100);            // a guess about how long the job takes
  expect(job.isDone()).toBe(true);
});

In the simulation, raise the load and watch what moves. The job’s code does not change. Its latency stretches past the test’s guess, so more runs lose the race between the job and the assert. Then try the fix: the sim lets you write the wait yourself. The two things to take from it are the same two you will do in the lab. The wait must stop as soon as the condition holds, so a fast run is a fast test. And it must have a deadline, so code that never finishes becomes a red test that says what it waited for, not a hung build.

The lesson Flaky test from a race goes through the same mechanism with a thread and a job. Here the point is what the fix looks like in a Python suite: a helper that polls.

def wait_until(condition, timeout_s=2.0, interval_s=0.005, what="condition"):
    deadline = time.monotonic() + timeout_s
    while True:
        value = condition()
        if value:
            return value
        if time.monotonic() >= deadline:
            raise AssertionError(f"timed out after {timeout_s} s waiting for {what}")
        time.sleep(interval_s)

Three details carry the weight. It returns the truthy value, so the test can assert on what it found instead of checking twice. The what goes into the failure message, so a red build says “timed out after 2.0 s waiting for product 7 to appear in search” instead of assert [] == [7]. And the clock is time.monotonic(), which does not jump when someone changes the system time.

There is a second cure for this particular test: index.flush() waits for the queue to drain with no sleep and no polling. It is exact, and it only works because the test can reach into the index. A test that goes through the HTTP API, as a browser or a client would, has no flush to call. It has to wait the way a user does, by asking again until the answer appears. So learn polling: it works at every level.

A deadline is a promise about the system, so choose it from the thing you know. If the search team promises new products are searchable within 30 seconds, the test waits up to 30 seconds and fails after that, and the failure now means “the promise broke”. A deadline picked because the test happened to pass is another guess. The lesson Eventual consistency in assertions shows this with a replica; it is the same shape.

Cause two: state the tests share

The second cause does not depend on time at all. Two tests share something, and the result depends on which ran first.

Ojaline’s search suite has two tests that look harmless. One checks that a new shop has no shea butter listed. The other adds a shea butter product and finds it. Both use an index built once, at the top of the file, because building one per test felt wasteful. In file order the empty-shop test runs first and passes. Nobody ever runs them in another order, so nobody knows.

▶ SIMULATION
RUNNER
fixture: shared, module-level
ran: —
FIXTURE NOW
users: []
cache: {} · db calls: 0
WHAT THE TEAM SEES
—
last—
✓ the build is red exactly when the code is wrong (the code is right)
SCHEDULE
01[RUNNER]runner: file order, one shared fixture
02[T1]t1: register adds a user
03[T2]t2: first lookup hits the database
04[T3]t3: register is idempotent
05[T4]t4: removeAll empties the list
06[RUNNER]report
Start of file order, shared fixture scenario. 6 steps.
const fixture = { users: [], cache: new Map(), dbCalls: 0 };  // module level: every test sees it

test('register adds a user', () => {
  register(fixture, 'alice');
  expect(fixture.users).toHaveLength(1);   // true only if nothing ran before
});

Watch the order the sim runs the tests in and the state they leave behind. Each test passes alone. The failure belongs to the pair. The state could be anything that outlives a test: a module-level object, a class attribute, a cache, a row in a shared database, a temp file with a fixed name, a port. A new test added in the middle, a parallel runner like pytest-xdist giving each worker a different slice, or a shuffle, changes the order and the leftover state changes with it.

The tool that finds these is a shuffle. pytest-randomly, which the lab pins (version 4.0.1) and runs by default, shuffles modules, then classes, then functions within them, and prints the seed it used: Using --randomly-seed=1. A failure under a shuffle is reproducible only if you keep that seed. Pass it back with --randomly-seed=1 and the same order returns. It also resets Python’s random seed for every test from the base seed and the test’s id, so a test that draws random numbers draws the same ones when you replay the seed. That is how you debug an order problem: replay the seed, then run the failing test and its neighbours in a smaller set until you find the one that leaves the mess.

The cure is isolation, not a fixed order. Pinning the order, or marking tests as depending on each other, makes the suite fragile and kills parallelism. Give every test its own state. In pytest that is a function-scoped fixture that builds a fresh object, and, where a test creates something outside the process (a file, a row), cleans it up. The chapter Test data and fixtures goes deeper on how to build that state cheaply. Here the rule is the one Fowler gives: properly isolated tests can run in any sequence, and a suite that has never run in another sequence has not shown it.

Cause three: the product has the race

A test can be flaky because the thing it tests is. This is the case worth the most care, because the usual cure for flaky tests, running them again, is exactly wrong here.

The lab’s checkout code has one. orders.place_order looks up the idempotency key, then charges, then saves. Two requests with the same key that arrive together can both pass the lookup, and both save an order. The provider de-duplicates the charge, so the card is billed once, but there are two orders and the stock is taken twice. If the two requests arrive a few milliseconds apart, the first finishes before the second looks, and everything is fine. A test that sends two requests at slightly random times fails some of the time. It looks like a flaky test. It is a correct test of a product bug.

You tell the cases apart by what moves the rate. A sleep-based test gets worse as load rises and as the machine slows. A shared-state test fails or passes by order, and fixing the seed fixes the outcome. A product race fails at a rate that depends on how closely two things overlap, and no amount of waiting in the test changes it. If you cannot explain a failure by one of the first two, suspect the third before you suspect the test.

Quarantine: take it out of the way, not out of sight

You cannot fix every flaky test the day you find it. Meanwhile a flaky test in the blocking run costs the whole team a re-run on each failure. The standard answer, which Fowler describes in his article on non-determinism, is quarantine: move the test out of the run that blocks merges, keep it running somewhere else, and file a bug.

Quarantine can fail in a quiet way. The test is skipped, the bug ages, and a year later the suite has a folder of tests that nobody runs and nobody remembers. The guard is three rules.

  • The quarantined test still runs. It runs in its own CI job that is allowed to fail and reports its result. You keep seeing its rate, so you can tell when someone’s fix worked.
  • Every quarantine names an owner and an end date. A person is responsible, and the date is when the question gets asked again.
  • An expired quarantine fails something. A date nothing enforces is a wish. The lab does it with a check that reads every quarantined test at collection time and refuses to continue if the date has passed. The owner then fixes the test, deletes it, or renews the date on purpose, and a renewal is a decision someone makes in a commit.

pytest’s own documentation describes marking a flaky test xfail (without strict) as being like a manual quarantine, and calls it rather dangerous to use permanently. The longer-term remedy is to fix or remove the test. A test you will never fix is a test you should remove, because its only effect is on the people who read its failures.

Retries: the cure that hides the disease

The tempting answer to a flaky build is to retry. Plugins like pytest-rerunfailures run a failed test again, and CI services have a “re-run failed jobs” button. For a sleep-based test this lowers the red rate, because each run is another chance to be lucky. That is the problem: you changed the number the team sees and not the test.

▶ SIMULATION
CI RUNNER
policy: silent retry, up to 3
builds: 0
THE PRODUCT
checkout_stock has a real race: yes
builds deployed over a race nobody was told about: 0
THE TEAM SEES
flaky tests on the dashboard: 0
tests that actually needed a retry: 0
last—
✓ a build never goes green over a product race that nobody was told about✓ the flaky count the team sees equals the tests that needed a retry✓ a test that never fails is never flagged
SCHEDULE
01[CI]policy: retry a failed test up to 3 times; any pass is a pass; nothing is recorded
02[CI]a build runs the three tests, retrying failures
03[CI]a build runs the three tests, retrying failures
04[CI]a build runs the three tests, retrying failures
05[CI]a build runs the three tests, retrying failures
06[CI]a build runs the three tests, retrying failures
07[CI]a build runs the three tests, retrying failures
08[CI]a build runs the three tests, retrying failures
09[CI]report
Start of auto-retry, nothing recorded scenario. 9 steps.
# the runner
retry_failed_tests: 3        # any pass is a pass
# no record of the failed attempts
# the dashboard counts tests that failed all 3 times: 0
# a real race passes on attempt 2 and ships

In the simulation, set a retry policy and a fault in the product, and compare the pass rate with what actually failed. The sim makes two points. A product race fails some attempts and passes others, so a policy of three retries lets it through nearly every time. And the number that rises when flakiness grows is the count of tests that needed a retry. The pass rate after retries stays high. The lesson Retries hide the bug has the policy side.

The pytest documentation presents pytest-rerunfailures as a mitigation that keeps the build green, not a fix. GitHub’s engineers reported something sharper about their own retries. Before they built their flaky-test system, the retry approaches they had caught about a quarter of flaky failures. Their replacement re-ran failed tests in several ways, including with the clock shifted and on another host, to guess the cause, and kept a record of each flaky test so an issue could be opened for its likely owner. The lesson is that a retry is useful as an instrument and harmful as a verdict. Re-run to collect evidence about a failure. Never let the re-run erase it.

If you do use a retry plugin, three rules keep it honest. Report every rerun in the build output, so the count is visible. Retry only tests that are marked as known flaky, not the whole suite. And never retry the tests that exercise concurrency in your own code, because for those a failure that goes away on retry is the finding.

One more trap, which the lab shows. pytest-rerunfailures defines a marker called flaky, the same word this lab uses for its quarantined test. A bare @pytest.mark.flaky on a test tells the plugin to rerun that test once, and that count beats the --reruns 3 you gave on the command line. Two meanings of one word is a reason to name your quarantine marker something the plugin does not own. The lab uses quarantine.

What to do on Monday

Put these in order, because the order is the point.

  1. Measure before you fix. Rerun the suspect test enough times to see a rate, with the same ordering and load as CI.
  2. Name the cause from the three above, by what moves the rate: load, order, or neither.
  3. Quarantine if the fix is not today, with an owner, a date and a separate non-blocking job.
  4. Fix the cause, not the symptom: poll with a deadline, isolate the state, or fix the product.
  5. Measure again with the same number of runs, and delete the quarantine.
LAB Measure a flaky test, quarantine it, fix it, and see a retry hide a race ~60 MIN
YOU NEEDlabs/testing set up (README, 'Set up'), Python 3.9+no Docker, no servers, no network beyond pipa scratch database path: export CHECKOUT_DB=/tmp/flaky-lab.sqlite

You will measure the lab’s flaky test, see how its failure rate follows the index lag, quarantine it with a guard, fix it by polling, then watch a retry plugin hide a race in the order code and a shuffle expose shared state. Work from labs/testing with the venv from the README. You create six small files and a second virtual environment, and edit four files (pyproject.toml, tests/conftest.py, tests/test_flaky_example.py and ci/github-actions.yml). The last step of the lab puts everything back.

1. Measure the flaky test over fifty runs. Create scripts/flake_rate.sh, which runs pytest many times and counts the runs that fail:

#!/bin/sh
# usage: scripts/flake_rate.sh N [pytest args...]
# Runs pytest N times and counts the runs that fail. PYTEST picks the runner.
n=$1; shift
runner=${PYTEST:-.venv/bin/pytest}
fails=0
i=0
while [ "$i" -lt "$n" ]; do
  "$runner" -q -p no:randomly "$@" >/dev/null 2>&1 || fails=$((fails + 1))
  i=$((i + 1))
done
echo "$fails of $n runs failed"

Run this before step 2, because after step 2 -m flaky also collects the tests in tests/test_flaky_lag.py. Then run it against the quarantined test. The default run deselects it, so ask for it with -m flaky:

cd labs/testing
export CHECKOUT_DB=/tmp/flaky-lab.sqlite
chmod +x scripts/flake_rate.sh
scripts/flake_rate.sh 50 -m flaky
About a minute, then a line such as 23 of 50 runs failed. Your number will differ; between 18 and 30 is normal. The test uses a lag of 50 ms with the jitter on and sleeps 50 ms, so it loses about half the time. Run it a second time and you will not get the same count. That spread is why one run proves nothing.

2. Move the lag and watch the rate move. The test hard-codes its lag. Create tests/test_flaky_lag.py, which takes the lag and the run count from the environment and runs the same scenario many times in one pytest call:

"""The flaky test again, with the lag and the number of runs set from the environment."""

import os
import time

import pytest

from checkout.search_index import SearchIndex
from tests.helpers import wait_until

LAG_S = float(os.environ.get("LAG_MS", "50")) / 1000
RUNS = int(os.environ.get("RUNS", "1"))


@pytest.mark.flaky
@pytest.mark.parametrize("attempt", range(RUNS))
def test_sleep_then_search(attempt):
    index = SearchIndex(lag_s=LAG_S, jitter=True)
    index.submit({"id": 7, "seller_id": "s", "name": "Shea butter", "status": "published"})
    time.sleep(0.05)  # the guess
    assert [d["id"] for d in index.search("shea")] == [7]


@pytest.mark.flaky
@pytest.mark.parametrize("attempt", range(RUNS))
def test_poll_then_search(attempt):
    index = SearchIndex(lag_s=LAG_S, jitter=True)
    index.submit({"id": 7, "seller_id": "s", "name": "Shea butter", "status": "published"})
    hits = wait_until(lambda: index.search("shea"), what="product 7 to be searchable")
    assert [d["id"] for d in hits] == [7]

The second test imports tests/helpers.py, so create that file too. It holds the wait_until from the chapter, which step 4 uses again:

"""Shared test helpers."""

import time


def wait_until(condition, timeout_s=2.0, interval_s=0.005, what="condition"):
    """Poll `condition()` until it returns a truthy value; fail at the deadline.

    Returns the truthy value, so the caller can assert on it.
    """
    deadline = time.monotonic() + timeout_s
    while True:
        value = condition()
        if value:
            return value
        if time.monotonic() >= deadline:
            raise AssertionError(f"timed out after {timeout_s} s waiting for {what}")
        time.sleep(interval_s)

Now run the sleeping test two hundred times at four lags:

for lag in 25 50 200 400; do
  echo "lag $lag ms"
  LAG_MS=$lag RUNS=200 .venv/bin/pytest tests/test_flaky_lag.py -k sleep -m flaky -p no:randomly -q | tail -1
done
Each line takes about 12 seconds. Counts from 2026-11-23, 200 runs each: lag 25 ms: 1 failed, 199 passed (another run gave 8); lag 50 ms: 97 failed, 103 passed; lag 200 ms: 170 failed, 30 passed; lag 400 ms: 190 failed, 10 passed. At 25 ms the longest possible delay equals the guess, so the failures are the odd run where the thread is a little late: about one in twenty-five, close to what Ojaline’s team sees. At 50 ms it is half. Past that the guess is hopeless. The code never changed; only the speed of the thing it waits for did.

3. Quarantine it, with an owner, a date and a guard. Three edits. First, in pyproject.toml, register the marker and keep it out of the default run:

addopts = "-ra -m 'not flaky and not quarantine' -p no:schemathesis"
markers = [
  "flaky: deliberately flaky (sleep-based); quarantined from the default run, run with -m flaky",
  "quarantine(owner, until): known flaky, kept out of the blocking run; needs an owner and an ISO date",
  "e2e: browser test; skipped unless Playwright's Chromium is installed",
]

Second, in tests/conftest.py, add import datetime as dt to the imports and this hook at the end. It runs before pytest deselects anything, so it sees quarantined tests too:

@pytest.hookimpl(tryfirst=True)
def pytest_collection_modifyitems(items):
    """A quarantine names an owner and an end date, and an expired one fails the run."""
    today = dt.date.today()
    for item in items:
        mark = item.get_closest_marker("quarantine")
        if mark is None:
            continue
        owner, until = mark.kwargs.get("owner"), mark.kwargs.get("until")
        if not owner or not until:
            raise pytest.UsageError(f"{item.nodeid}: quarantine needs owner= and until=")
        if dt.date.fromisoformat(until) < today:
            raise pytest.UsageError(f"{item.nodeid}: quarantine by {owner} ended on {until}; fix or delete the test")

Third, in tests/test_flaky_example.py, replace @pytest.mark.flaky with a quarantine that ends two weeks from today (the date below is two weeks from 2026-11-23; use your own):

@pytest.mark.quarantine(owner="search team", until="2026-12-07")

Check three things: the default run, the quarantined run and the expired quarantine.

.venv/bin/pytest -q | tail -1
.venv/bin/pytest -m quarantine tests/test_flaky_example.py -p no:randomly -q | tail -1
sed -i.bak 's/2026-12-07/2026-11-01/' tests/test_flaky_example.py
.venv/bin/pytest --collect-only -q | head -2; echo "exit code: $?"
mv tests/test_flaky_example.py.bak tests/test_flaky_example.py
The default run shows 23 passed, 1 skipped, 3 deselected; the quarantined test and the two tests in test_flaky_lag.py are the deselected ones. The quarantined run passes or fails with the rate you measured. With the date moved into the past the collection stops with ERROR: tests/test_flaky_example.py::test_new_product_is_searchable_after_a_short_wait: quarantine by search team ended on 2026-11-01; fix or delete the test. The echo prints the exit code of head, which is 0; pytest itself exits 4 when you run the command without the pipe. The last command restores your two-week date.

To run quarantined tests in CI without blocking, open ci/github-actions.yml and make two additions. In the lint job, after the ruff step, add a step that reads every test file, so an expired date fails a blocking job. Then add a job of its own, placed before the mutation job:

      - run: pytest --collect-only -q   # in the lint job: an expired quarantine fails here

  quarantine:
    runs-on: ubuntu-latest
    continue-on-error: true   # reported on every push, never blocking
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with: {python-version: "3.9"}
      - run: pip install -r requirements.txt
      - run: pytest -m quarantine -p no:randomly -q

The continue-on-error key at job level lets the workflow pass when this job fails; GitHub’s workflow syntax reference documents it. Check the file still parses:

.venv/bin/python -c "import yaml; print(list(yaml.safe_load(open('ci/github-actions.yml'))['jobs']))"
['lint', 'unit', 'integration', 'quarantine', 'mutation']. The file is an example, not active, so nothing runs on GitHub; the job is there for you to copy.

4. Fix it by polling, then measure again. Rewrite tests/test_flaky_example.py so it waits on the condition. It has no marker now, so it joins the default run:

"""A product reaches search after the index lag. The test waits for that, not for a guess."""

from checkout.search_index import SearchIndex
from tests.helpers import wait_until


def test_new_product_is_searchable_after_a_short_wait():
    index = SearchIndex(lag_s=0.05, jitter=True)  # each update waits 0 to 0.1 s
    index.submit({"id": 7, "seller_id": "s", "name": "Shea butter", "status": "published"})
    hits = wait_until(lambda: index.search("shea"), what="product 7 to appear in search")
    assert [d["id"] for d in hits] == [7]

Test the helper’s deadline too, in tests/test_wait_until.py, so its failure message is itself under test:

import pytest

from tests.helpers import wait_until


def test_wait_until_fails_at_the_deadline_and_says_what_it_waited_for():
    with pytest.raises(AssertionError, match="timed out after 0.05 s waiting for the moon"):
        wait_until(lambda: False, timeout_s=0.05, what="the moon")
.venv/bin/pytest tests/test_wait_until.py -q | tail -1
scripts/flake_rate.sh 50 tests/test_flaky_example.py
for lag in 50 200; do
  LAG_MS=$lag RUNS=200 .venv/bin/pytest tests/test_flaky_lag.py -k poll -m flaky -p no:randomly -q | tail -1
done
1 passed; then 0 of 50 runs failed; then 200 passed, 200 deselected in 11.7s at lag 50 ms and 200 passed, 200 deselected in 42.3s at 200 ms. Zero in 250 runs, at lags where the sleeping test failed from half to nearly all of the time. The time is the price: the poll waits for the real lag, which averages 200 ms per run here, so 200 runs take about 40 seconds. The sleeping test was fast at that lag because it gave up too early.

5. Watch a retry hide a race. The retry plugin must not go into the lab’s pinned .venv, so make a second venv for it and pin the plugin. On 2026-11-23 the newest pytest-rerunfailures, 16.0.1, installed on Python 3.9.6 with the lab’s pytest.

python3 -m venv .venv-retry
.venv-retry/bin/pip install -q pytest==8.4.2 pytest-randomly==4.0.1 httpx==0.28.1 pytest-rerunfailures==16.0.1

Create tests/race_demo.py. The file name does not start with test_, so the default run never collects it; you name it on the command line. It sends two requests with the same idempotency key, a few milliseconds apart, as a client retrying after a timeout would:

"""Two requests with one idempotency key, arriving together. Is there one order?"""

import random
import threading
import time

from checkout.orders import place_order


def test_retry_with_same_key_makes_one_order(db, clock, payments):
    def request():
        time.sleep(random.uniform(0, 0.01))  # the two requests arrive up to 10 ms apart
        place_order(db, payments, clock, [{"product_id": 2, "qty": 1}], "same-key")

    threads = [threading.Thread(target=request) for _ in range(2)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    assert db.count_orders() == 1
scripts/flake_rate.sh 50 tests/race_demo.py
PYTEST=.venv-retry/bin/pytest scripts/flake_rate.sh 50 tests/race_demo.py --reruns 3
.venv-retry/bin/pytest tests/race_demo.py -p no:randomly --reruns 3 -rR | tail -4
The first line is a rate between a quarter and a half, for example 14 of 50 runs failed (12 and 18 came up on other runs). The second, with up to three reruns, is nearly zero: 2 of 50 runs failed. The third shows a run that went green on a rerun: RERUN tests/race_demo.py::test_retry_with_same_key_makes_one_order and 1 passed, 1 rerun. If the test passes first time, run it again until you see a RERUN line. The bug did not go anywhere: it is the check-then-act race in place_order, and for a day the dashboard would have shown a green build while real customers placed duplicate orders. A later chapter on concurrency in tests builds the fix for the product. Here the lesson is the output: the retry made 28% red into 4% red and the reruns went unnoticed unless you asked for -rR.

Make the rerun count visible in a pipeline, so a green run that needed a retry is not silent:

.venv-retry/bin/pytest tests/race_demo.py -p no:randomly --reruns 3 -rR | tee run.log
grep -c '^RERUN' run.log
The count of reruns, 0 on a clean run and 1 or more when the plugin had to try again. Count that per week. A pass rate stays high while retries are climbing; the retry count is what moves. Delete run.log afterwards.

6. Shuffle the order and find the shared state. Create tests/test_search_shared.py with the pair that shares an index, built once at the top of the file:

"""Two search tests that share one index. Green in file order, red in some others."""

from checkout.search_index import SearchIndex

INDEX = SearchIndex()  # built once, when the module loads, and shared by every test below


def test_a_new_shop_has_no_shea_butter_listed():
    assert INDEX.search("shea") == []


def test_published_product_is_found():
    INDEX.add_now({"id": 7, "seller_id": "s", "name": "Shea butter", "status": "published"})
    assert [d["id"] for d in INDEX.search("shea")] == [7]
.venv/bin/pytest tests/test_search_shared.py -p no:randomly -q | tail -1
.venv/bin/pytest tests/test_search_shared.py -p randomly --randomly-seed=1 | grep -E "seed|FAILED|passed|failed"
.venv/bin/pytest tests/test_search_shared.py -p randomly --randomly-seed=2 -q | tail -1
File order: 2 passed. Seed 1 prints Using --randomly-seed=1, then FAILED tests/test_search_shared.py::test_a_new_shop_has_no_shea_butter_listed, then 1 failed, 1 passed: the shuffle ran the adding test first and left a product behind. Seed 2 happens to keep the file order and passes: 2 passed. Seeds 1 and 5 fail on this file; the others you try (2, 3, 4 and 6 were checked) pass. A suite with only the default shuffle would fail intermittently with a seed you did not write down, which is why the plugin prints it.

Now fix it: replace the file’s contents with one index per test.

"""Two search tests, each with its own index. Green in any order."""

import pytest

from checkout.search_index import SearchIndex


@pytest.fixture
def index():
    return SearchIndex()  # a fresh index for every test


def test_a_new_shop_has_no_shea_butter_listed(index):
    assert index.search("shea") == []


def test_published_product_is_found(index):
    index.add_now({"id": 7, "seller_id": "s", "name": "Shea butter", "status": "published"})
    assert [d["id"] for d in index.search("shea")] == [7]
for s in 1 5; do .venv/bin/pytest tests/test_search_shared.py -p randomly --randomly-seed=$s -q | tail -1; done
.venv/bin/pytest tests/test_search_shared.py -n 2 -q | tail -1
Seeds 1 and 5, the two that failed, now report 2 passed, and so does the parallel run with two workers. The order no longer matters, which is the whole point. Keep the file: it is a good regression test for any later change to the index.
Take the fix out of tests/test_flaky_example.py: put back time.sleep(0.05) in place of the poll, and run scripts/flake_rate.sh 50 tests/test_flaky_example.py, then again with PYTEST=.venv-retry/bin/pytest and –reruns 3 added. On 2026-11-23 that gave 32 of 50 red and then 2 of 50: the retry made the flake look cured. Now change the index to lag_s=0.4 and repeat both: 46 of 50 red, and 39 of 50 with the retries. A retry hides a flake that fails some of the time and cannot hide one that fails nearly always, and in neither case did the test get any better. Restore the polling version, and delete .venv-retry, run.log and tests/race_demo.py.

Put the lab back. Run git checkout pyproject.toml tests/conftest.py tests/test_flaky_example.py ci/github-actions.yml, then delete scripts/flake_rate.sh, tests/helpers.py, tests/test_flaky_lag.py, tests/test_wait_until.py, tests/test_search_shared.py, tests/race_demo.py, run.log, the folder .venv-retry and /tmp/flaky-lab.sqlite. The next chapters count from 23 passed, 1 skipped, 1 deselected.

DECIDE

Ojaline's order-search test fails about one CI run in twenty. It sleeps 200 ms after publishing a product and then searches. Wangari has looked at it twice and cannot see a bug in the code under test. The release is on Thursday, and the team has already started pressing re-run. Kiplagat asks what the team should do today.

READING
  1. POST
    Eradicating Non-Determinism in Tests Martin Fowler, 2011

    The short, clear account of why non-deterministic tests are corrosive and how to quarantine them. Read Quarantine, Lack of Isolation and Asynchronous Behavior; skim Remote Services, Time and Resource Leaks, which later chapters return to.

  2. PAPER
    An Empirical Study of Flaky Tests in Python Gruber, Lukasczyk, Kroiß and Fraser, 2021

    The numbers behind this chapter: order dependence as the biggest cause in Python (59% of 7,571 flaky tests) and about 170 reruns to be 95% sure a passing test is not flaky. Skip the sections on the tooling pipeline on a first read. Read: the abstract, the causes section and the section on how many reruns detection needs.

  3. PAPER
    An Empirical Analysis of Flaky Tests Luo, Hariri, Eloussi and Marinov, 2014

    The first large classification of why tests are flaky, from open-source Java projects, and the fixes that worked. The publisher blocks automated fetches, so the title, authors and venue were checked through Crossref; read the root-cause tables and skip the tool-support discussion. Read: the sections on root causes and on how developers fixed them.

  4. PAPER
    A Survey of Flaky Tests Parry, Kapfhammer, Hilton and McMinn, 2021

    A map of everything researchers know: causes, how to detect flakiness, how to repair or manage it. Use it as a reference when you meet a flaky test that fits none of this chapter's three causes. The publisher blocks automated fetches, so the metadata was checked through Crossref. Read: the sections on causes, detection and mitigation.

  5. POST
    Reducing flaky builds by 18x Jordan Raine, GitHub, 2020

    A real system for managing flakiness at scale: rerunning in different ways to guess the cause, keeping the build green while tracking the test, and opening an issue for the right owner. Read it for the numbers (9% of commits red from flaky tests, under 0.5% six weeks later) and for how retries alone caught about a quarter of flaky failures.

  6. DOC
    Flaky tests

    pytest's own page: root causes, how pytest-xdist and pytest-randomly expose shared state, marking a flaky test xfail without strict as something like a manual quarantine that is rather dangerous to use permanently, and rerun plugins presented as a mitigation. Short; read all of it. Read 2026-11-23.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Coverage and mutation testing: measuring the tests →