Our test suite had a flake we couldn't pin down. A test would pass alone, pass in its own file, then fail when the full suite ran. Re-run it and it passed again. Classic state leak.

The culprit turned out to be the thing we thought was protecting us: pytest-xdist.

The Problem

xdist spreads tests across persistent worker processes. Those workers stay alive and pick up file after file. That is great for spawn overhead and terrible for isolation. Any module-level dict, any ContextVar, any singleton that one test file mutates rides along into the next file that lands on the same worker.

We had ~17k tests across ~850 files. The state that leaked was almost always module-level: a registry populated at import time, a cache that never got reset, an env-var read once and memoized. None of it was the test author's bug. It was the worker being reused.