python system_error ai_generated true

sqlite3.OperationalError: 数据库已锁定

sqlite3.OperationalError: database is locked

ID: python/pytest-xdist-fixture-not-thread-safe

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
0证据数
2024-11-18首次发现

版本兼容性

版本状态引入弃用备注
3.5.x active — — —
3.6.x active — — —

根因分析

pytest-xdist 在并行 worker 中运行测试,共享单个 SQLite 文件或 session 作用域资源。SQLite 的文件锁在跨进程时冲突。

English

pytest-xdist runs tests in parallel workers sharing a single SQLite file or session-scoped resource. SQLite's file lock conflicts across processes.

generic

解决方案

  1. 94% 成功率
    @pytest.fixture(scope='session')
    def db_path(worker_id):
        return f'/tmp/testdb_{worker_id}.sqlite'
    
    # run: pytest -n auto
  2. 92% 成功率
    @pytest.fixture(scope='session')
    def db(tmp_path_factory, worker_id):
        p = tmp_path_factory.mktemp(worker_id) / 'db.sqlite'
        conn = sqlite3.connect(p)
        init_schema(conn)
        yield conn
        conn.close()

无效尝试

常见但无效的做法:

  1. 65% 失败

    WAL allows concurrent readers but still serializes writers; parallel tests writing cause 'database is locked' to persist.

  2. 60% 失败

    Masks flakiness and slows the suite; long transactions still hold locks and eventually exhaust retries.