# sqlalchemy.exc.StatementError: (sqlalchemy.exc.InvalidRequestError) Can't reconnect until invalid transaction is rolled back

- **ID:** `python/pytest-sqlalchemy-connection-closed`
- **Domain:** python
- **Category:** data_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

A previous database operation failed, leaving the transaction in an invalid state. Subsequent queries fail until the transaction is explicitly rolled back.

## Version Compatibility

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

## Workarounds

1. **** (98% success)
   ```
   try:
    session.execute(...)
except Exception:
    session.rollback()
    raise
   ```
2. **** (95% success)
   ```
   @pytest.fixture
def db_session():
    session = Session()
    yield session
    session.rollback()
    session.close()
   ```
3. **** (90% success)
   ```
   with session.begin():
    session.execute(...)
# automatically rolls back on exception
   ```

## Dead Ends

- **** — This is disruptive and does not address the application-level transaction handling issue. (90% fail)
- **** — The issue is not about pool size but about transaction state. (85% fail)
- **** — Retrying without rollback will keep failing. (95% fail)
