python runtime_error ai_generated true

AssertionError: assert 1 == 2 # passes with -p no:xdist, fails with -n auto

ID: python/pytest-xdist-shared-state

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-10-21First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active
8.x active

Root Cause

Tests share global state (module-level caches, singletons, files) that is safe serially but races or persists across worker processes under pytest-xdist.

generic

中文

测试共享全局状态(模块级缓存、单例、文件),在串行下安全,但在 pytest-xdist 的多个 worker 进程下产生竞态或持久化。

Workarounds

  1. 90% success
    @pytest.fixture(autouse=True)
    def reset_state():
        myapp.cache.clear()
        yield
        myapp.cache.clear()
  2. 88% success
    def test_db(tmp_path, worker_id):
        if worker_id == 'master':
            db = tmp_path / 'db.sqlite'
        else:
            db = tmp_path / f'db_{worker_id}.sqlite'
        ...

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Masks the race condition; reruns may pass by luck and hide real bugs, and flaky plugin adds overhead.

  2. 95% fail

    More workers means more contention, making the race more likely, not less.

  3. 85% fail

    Slows tests and does not eliminate the race; still fails intermittently on slow CI machines.