# sqlalchemy.exc.PendingRollbackError: 由于之前 flush 时发生异常，此 Session 的事务已被回滚

- **ID:** `python/pytest-sqlalchemy-session-scope-leak`
- **领域:** python
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

session 作用域的 SQLAlchemy Session fixture 跨测试复用；某测试抛异常后事务失败，后续测试使用同一 session 时处于待回滚状态。

## 版本兼容性

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

## 解决方案

1. **** (94% 成功率)
   ```
   @pytest.fixture
def db_session(engine):
    conn = engine.connect()
    trans = conn.begin()
    session = Session(bind=conn, join_transaction_mode='create_savepoint')
    yield session
    session.close()
    trans.rollback()
    conn.close()
   ```
2. **** (90% 成功率)
   ```
   @pytest.fixture
def session(engine):
    s = Session(engine)
    yield s
    s.rollback()
    s.close()
   ```

## 无效尝试

- **** — Doesn't isolate data written before the error; tests still see dirty state from previous tests. (70% 失败率)
- **** — Pool size is unrelated to transaction state; the pending rollback persists on the same session object. (85% 失败率)
