# sqlite3.OperationalError：数据库已锁定

- **ID:** `python/pytest-parallel-fixture-db-collision`
- **领域:** python
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

多个 xdist 工作进程共享同一个 SQLite 文件（或同一 fixture 创建的数据库路径）并争用写锁。

## 版本兼容性

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

## 解决方案

1. **** (95% 成功率)
   ```
   @pytest.fixture
def db(tmp_path, worker_id):
    path = tmp_path / f"test-{worker_id}.db"
    conn = sqlite3.connect(path)
    yield conn
    conn.close()
   ```
2. **** (90% 成功率)
   ```
   # docker-compose with postgres
# pytest.ini
[pytest]
addopts = -n auto
# DATABASE_URL=postgresql://user:pass@localhost/test
   ```
3. **** (88% 成功率)
   ```
   pytestmark = pytest.mark.xdist_group(name="db")
# run: pytest -n auto --dist=loadgroup
   ```

## 无效尝试

- **** — Reduces but does not eliminate lock contention under load. (70% 失败率)
- **** — Disables parallelism; CI time blows up. (60% 失败率)
- **** — Autocommit increases contention rather than reducing it. (85% 失败率)
