A test passes locally 10/10 but fails in CI 3/20. Why?
Question
This TTL cache test module passes 10/10 runs on your laptop yet fails 3/20 runs in CI.
- Spot all three causes of flakiness in the starter.
- Explain why raising
time.sleepor adding CI retries hides the real problem. - Refactor the cache and tests so every check is fast, isolated, and deterministic.
import time CACHE = {} def put(key, ttl): CACHE[key] = time.time() + ttl def live_keys(): now = time.time() return list({k for k, exp in CACHE.items() if exp > now}) def test_expiry(): put("a", ttl=0.05) time.sleep(0.02) assert live_keys() == ["a"] time.sleep(0.04) assert live_keys() == [] def test_two_keys(): put("a", ttl=1.0) put("b", ttl=1.0) assert live_keys() == ["a", "b"]
Show hints (3)
- "REVERSE TEST ORDER"
What sits inside global
CACHEif CI runstest_two_keysbeforetest_expiry? - "CHECK REAL CLOCK"
time.sleep(0.02)sleeps at least 20 ms. What happens on a busy CI runner if an extra 45 ms OS pause stretches it to 65 ms (past the 50 ms TTL)? - "CHECK LIST ORDER"
list({...})turns a set into a list whose order depends onPYTHONHASHSEED. Compare sets, inject a fake clock, and instantiate fresh cache state per test.
Show checked explanation
Three flake sources sit in this module: shared global CACHE state (order-dependent failure) and real time.time() plus time.sleep() (CI CPU stalls). It also compares a set converted to a list, which flips across PYTHONHASHSEED. Give each test a fresh Cache with an injected fake clock and assert on sets.
class Cache: def __init__(self, clock): self._clock, self._data = clock, {} def put(self, key, ttl): self._data[key] = self._clock() + ttl def live_keys(self): now = self._clock() return {k for k, exp in self._data.items() if exp > now} t = [0.0] c1, c2 = Cache(lambda: t[0]), Cache(lambda: t[0]) c1.put("a", 0.05) c2.put("b", 1.0) t[0] = 0.02 assert c1.live_keys() == {"a"} t[0] = 0.06 assert c1.live_keys() == set() assert c2.live_keys() == {"b"} print("isolated and deterministic")
isolated and deterministic
Reproduced all three flakes (reversed test order, simulated extra 45 ms CI sleep pause totaling 65 ms > 50 ms TTL, and PYTHONHASHSEED set-order flip) on the starter and checked the deterministic Cache solution on CPython 3.12.10. Checked by an editor other than the author.
Walkthrough
Flaky tests rarely fail by magic. They depend on an uncontrolled input: test order, wall-clock scheduling, or hash randomization.
| Flake source in starter | Why CI hits it | Deterministic fix |
|---|---|---|
Module global CACHE = {} | Running test_two_keys before test_expiry leaks "b" | Fresh Cache(...) instance (or pytest fixture) per test |
time.time() + time.sleep(0.02) | Extra 45 ms CI pause (65 ms > 50 ms TTL) expires "a" early | Inject a fake clock (t[0] = 0.02, then 0.06) |
list({k for ...}) == ["a", "b"] | Each CI process picks a fresh PYTHONHASHSEED | Return or compare a set, or sort explicitly |
Look at how fast you can triage a CI-only failure without guessing:
- Test for order dependence: run the failing test alone, then run the suite in reverse or shuffled order (
pytest-randomly). If it only fails after another test, look for shared globals, temp files, env vars, or database rows. - Test for hash or sort dependence: rerun with different
PYTHONHASHSEEDvalues (for examplePYTHONHASHSEED=1vs2) or unordered SQL queries missingORDER BY. - Test for clock races: check every
sleep, timeout, ortime.time()call. Wall clocks can even step backward during NTP sync. Production TTL code should default totime.monotonic, while tests inject a controllable fake clock.
Raising sleep(0.02) to sleep(5) slows every build and still flakes under heavy CI load. Blind retries hide real race bugs in production code and burn CI minutes until the team stops trusting red builds.
Common mistakes
- Fixing the CI failure by adding
--reruns 3. Retries mask genuine concurrency and state-leak bugs until they reach production. - Replacing
time.sleep(0.02)withtime.sleep(2)instead of injecting a clock. The suite turns slow and still breaks under a longer pause. - Using
time.time()for TTL expiration in production. Wall clocks jump on NTP adjustments; default totime.monotonicand inject a fake clock in tests. - Sorting
live_keys()inside the test when callers actually rely on deterministic order, or keeping alistcomparison when order is not part of the spec.
Follow-up questions
- "How do you diagnose a flake that fails once in 200 CI runs and never locally?" Reproduce the CI environment first: log the random test seed and
PYTHONHASHSEED, run under CPU throttling or parallel workers (pytest -n auto), and run the suspect test 100 times in a loop. Capture timestamps, fixture state, and network logs on failure. - "When is quarantining a flaky test acceptable?" Only as a short, tracked step with an owner and expiry date when one broken test blocks unrelated merges. Keep the quarantined test running in a non-blocking job so you can confirm the real fix before restoring it.
- "Why does
monkeypatchhelp when you cannot change a function's signature right away?" Inpytest,monkeypatch.setattrreplaces a module's clock or global for one test and restores it on teardown. That prevents state leaks into later tests while you plan a cleaner dependency-injection refactor.
What a strong answer covers
Spots all three flake causes (shared CACHE, wall-clock sleep, hash-seed list(set)) and gives a clear reproduction workflow. Replaces sleeps and globals with fresh instances plus an injected clock, and rejects blind retries.
Open in interactive practice deck →