python runtime_error ai_generated true

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) database is locked

ID: python/pytest-parallel-db-fixture-conflict

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2025-11-30First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active
8.x active

Root Cause

Multiple pytest-xdist workers share the same SQLite file; concurrent writes cause lock contention and OperationalError.

generic

中文

多个 pytest-xdist worker 共享同一个 SQLite 文件;并发写入导致锁竞争和 OperationalError。

Workarounds

  1. 95% success
    @pytest.fixture(scope='session')
    def db_url(tmp_path_factory, worker_id):
        if worker_id == 'master':
            path = tmp_path_factory.mktemp('db') / 'test.db'
        else:
            path = tmp_path_factory.mktemp(f'db_{worker_id}') / 'test.db'
        return f'sqlite:///{path}'
  2. 92% success
    # docker-compose.yml provides postgres
    # conftest.py
    @pytest.fixture(scope='session')
    def db_url(worker_id):
        return f'postgresql://test:test@localhost/test_{worker_id}'

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Reduces frequency but not correctness; long-running transactions still deadlock and CI slows down.

  2. 90% fail

    Defeats the purpose of parallel tests; CI time returns to serial levels.

  3. 75% fail

    WAL helps readers but writers still serialize; contention remains under heavy xdist load.