# AssertionError: assert 1 == 2
# 使用 -p no:xdist 时通过，使用 -n auto 时失败

- **ID:** `python/pytest-xdist-shared-state`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

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

## 解决方案

1. **** (90% 成功率)
   ```
   @pytest.fixture(autouse=True)
def reset_state():
    myapp.cache.clear()
    yield
    myapp.cache.clear()
   ```
2. **** (88% 成功率)
   ```
   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'
    ...
   ```

## 无效尝试

- **** — Masks the race condition; reruns may pass by luck and hide real bugs, and flaky plugin adds overhead. (70% 失败率)
- **** — More workers means more contention, making the race more likely, not less. (95% 失败率)
- **** — Slows tests and does not eliminate the race; still fails intermittently on slow CI machines. (85% 失败率)
