Flaky test triage
Never "fix" a flaky test by adding a retry or a longer sleep without finding the cause. Process: reproduce → measure → classify → isolate → fix → prove.
1. Collect evidence first
- Exact test ID, failure message, and stack from CI (for GitHub Actions:
gh run view <run-id> --log-failed; see ci-failure-debugger). - History: how often, since when?
gh run list --workflow <wf> --limit 50 --json conclusion,headSha,createdAtand correlate withgit logaround the first failure. - Environment differences CI vs local: CPU count, OS, TZ, locale, parallelism flags, DB/service versions, test order/sharding, network access.
2. Reproduce and measure
python <skill-dir>/scripts/rerun.py -n 30 -- pytest "tests/test_orders.py::test_ship" -q -p no:randomly
python <skill-dir>/scripts/rerun.py -n 40 -j 4 -- go test ./orders -run TestShip -count=1
python <skill-dir>/scripts/rerun.py -n 30 --shell -- npx jest src/cart.test.ts -t "coupon" # --shell for npx on Windows
python <skill-dir>/scripts/rerun.py -n 20 --env TZ=Asia/Tokyo --env LANG=de_DE.UTF-8 -- <cmd>
The report gives pass rate, failure signatures (normalized, grouped), pass vs fail duration, and timeouts. Exit code 1 if any run failed. --save-dir flaky-logs keeps every failing log.
If it never fails in isolation, escalate pressure in this order: run the whole file, then the whole suite (order dependence), then -j 4 (shared state/races), then CPU stress (stress-ng --cpu 0 or run alongside a build), then the CI container image locally (docker run the same image).
Order dependence tools: pytest -p randomly / --randomly-seed=<seed> and pytest --lf; Jest --runInBand vs default, --randomize --seed=<n>; Go -shuffle=on (prints the seed), -count=1 disables cache; RSpec --order rand:<seed> + --bisect; JUnit 5 @TestMethodOrder(Random).
3. Classify (match symptoms → cause)
| Symptom | Likely cause | Fix |
|---|---|---|
| Fails only with other tests / specific order | Shared mutable state: globals, singletons, env vars, DB rows, files, caches, mocked modules not restored | Isolate per test (transactions/rollback, unique temp dirs, reset singletons, restore mocks in teardown) |
| Fails only in parallel | Port/file/DB name collisions, race conditions | Ephemeral ports (:0), unique names per worker, proper locking/awaiting |
| Failing runs much slower / timeouts | Fixed sleep, waiting on async work, slow CI | Wait on a condition (poll with deadline), fake timers, raise timeout only for genuinely slow ops |
| Around midnight, month end, DST, specific TZ | Real clock / local timezone | Inject clock / freeze time (freezegun, jest.useFakeTimers().setSystemTime), use UTC |
| Different values each run | Unseeded randomness, unordered collections (set/dict/map iteration, SQL without ORDER BY) | Seed RNG, sort before asserting, ORDER BY |
| Float assert mismatch | Floating point accumulation order | Approx compare (pytest.approx, toBeCloseTo) |
| Network errors / 429 | Real external calls | Mock at the HTTP boundary, or recorded fixtures |
| UI test: element not found / detached | Asserting before render; animations | Auto-waiting locators (await expect(locator).toBeVisible()), disable animations |
| Async test passes but logs errors later | Un-awaited promise/goroutine leaks into next test | Await everything; leak detectors (--detectOpenHandles, goleak) |
| Only on CI OS | Path separators, case-sensitive FS, line endings, locale | pathlib/path.join, normalize EOL, explicit locale |
4. Isolate the cause
- Add temporary diagnostics around the failing assertion (actual values, timestamps, thread/worker id) and re-run with
rerun.py --save-dir. - For order dependence, bisect the preceding tests: run
[first half of preceding tests] + target, halve until one polluter remains. git bisectif it started failing at a known point (usererun.py -n 20as the bisect predicate; exit code 1 = bad).
5. Fix and prove
- Fix the root cause in the test or the code (flaky tests often expose real race conditions in production code — check that first).
- Prove it:
rerun.pywith at least 3× the runs that previously showed a failure (e.g. failed 3/30 → require 0/100), under the same pressure (parallel/order) that reproduced it. - If you can't fix now: quarantine with an explicit marker + linked issue (
@pytest.mark.skip(reason="flaky: #123"),test.skipwith issue link), and tell the user. Never silently delete or retry-wrap.
6. Report template
## Flaky test: tests/test_orders.py::test_ship
- Before: 27/30 pass (90%), signature `a1b2c3d4`: AssertionError: expected 'shipped' got 'pending'
- Root cause: test asserts before the background job completes; job runs on a thread pool, slower under CI load.
- Fix: wait on job completion event with 5s deadline instead of `sleep(0.1)` (tests/test_orders.py:44).
- After: 100/100 pass, -j 4 (rerun.py).
- Production impact: none / <describe if the race exists in prod code>