python data_error ai_generated true

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

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

其他格式: JSON · Markdown 中文 · English
80%修复率
87%置信度
0证据数
2025-07-15首次发现

版本兼容性

版本状态引入弃用备注
2.0.x active — — —

根因分析

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

English

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

解决方案

  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()

无效尝试

常见但无效的做法:

  1. 70% 失败

    Doesn't isolate data written before the error; tests still see dirty state from previous tests.

  2. 85% 失败

    Pool size is unrelated to transaction state; the pending rollback persists on the same session object.