download

A test passes locally 10/10 but fails in CI 3/20. Why?

Testing~9 minReviewed 2 Dec 2026Free · No sign-in

Question

This TTL cache test module passes 10/10 runs on your laptop yet fails 3/20 runs in CI.

  1. Spot all three causes of flakiness in the starter.
  2. Explain why raising time.sleep or adding CI retries hides the real problem.
  3. Refactor the cache and tests so every check is fast, isolated, and deterministic.
"CODE · PYTHON"
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)
  1. "REVERSE TEST ORDER"

    What sits inside global CACHE if CI runs test_two_keys before test_expiry?

  2. "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)?

  3. "CHECK LIST ORDER"

    list({...}) turns a set into a list whose order depends on PYTHONHASHSEED. 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.

"SOLUTION · PYTHON"
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")
"OUTPUT"
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 starterWhy CI hits itDeterministic 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" earlyInject a fake clock (t[0] = 0.02, then 0.06)
list({k for ...}) == ["a", "b"]Each CI process picks a fresh PYTHONHASHSEEDReturn or compare a set, or sort explicitly

Look at how fast you can triage a CI-only failure without guessing:

  1. 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.
  2. Test for hash or sort dependence: rerun with different PYTHONHASHSEED values (for example PYTHONHASHSEED=1 vs 2) or unordered SQL queries missing ORDER BY.
  3. Test for clock races: check every sleep, timeout, or time.time() call. Wall clocks can even step backward during NTP sync. Production TTL code should default to time.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) with time.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 to time.monotonic and inject a fake clock in tests.
  • Sorting live_keys() inside the test when callers actually rely on deterministic order, or keeping a list comparison 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 monkeypatch help when you cannot change a function's signature right away?" In pytest, monkeypatch.setattr replaces 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 →

Original OfferVibe question. pytest fixtures · pytest monkeypatch · Python time.monotonic.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.