# sqlalchemy.exc.PendingRollbackError: This Session's transaction has been rolled back due to a previous exception during flush

- **ID:** `python/pytest-sqlalchemy-session-scope-leak`
- **Domain:** python
- **Category:** data_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

A session-scoped SQLAlchemy Session fixture reused across tests leaves a failed transaction after one test raises. Subsequent tests hit the same session in a pending-rollback state.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 2.0.x | active | — | — |

## Workarounds

1. **** (94% success)
   ```
   @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% success)
   ```
   @pytest.fixture
def session(engine):
    s = Session(engine)
    yield s
    s.rollback()
    s.close()
   ```

## Dead Ends

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