# sqlite3.OperationalError: 数据库已锁定

- **ID:** `python/pytest-xdist-fixture-not-thread-safe`
- **领域:** python
- **类别:** system_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.5.x | active | — | — |
| 3.6.x | active | — | — |

## 解决方案

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()
   ```

## 无效尝试

- **** — WAL allows concurrent readers but still serializes writers; parallel tests writing cause 'database is locked' to persist. (65% 失败率)
- **** — Masks flakiness and slows the suite; long transactions still hold locks and eventually exhaust retries. (60% 失败率)
