python
data_error
ai_generated
true
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
80%Fix Rate
87%Confidence
0Evidence
2025-07-15First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 2.0.x | active | — | — | — |
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.
generic中文
session 作用域的 SQLAlchemy Session fixture 跨测试复用;某测试抛异常后事务失败,后续测试使用同一 session 时处于待回滚状态。
Workarounds
-
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() -
90% success
@pytest.fixture def session(engine): s = Session(engine) yield s s.rollback() s.close()
Dead Ends
Common approaches that don't work:
-
70% fail
Doesn't isolate data written before the error; tests still see dirty state from previous tests.
-
85% fail
Pool size is unrelated to transaction state; the pending rollback persists on the same session object.