{
  "id": "python/pytest-sqlalchemy-session-scope-leak",
  "signature": "sqlalchemy.exc.PendingRollbackError: This Session's transaction has been rolled back due to a previous exception during flush",
  "signature_zh": "sqlalchemy.exc.PendingRollbackError: 由于之前 flush 时发生异常，此 Session 的事务已被回滚",
  "regex": "sqlalchemy\\.exc\\.PendingRollbackError:\\ This\\ Session's\\ transaction\\ has\\ been\\ rolled\\ back\\ due\\ to\\ a\\ previous\\ exception\\ during\\ flush",
  "domain": "python",
  "category": "data_error",
  "subcategory": null,
  "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.",
  "root_cause_type": "generic",
  "root_cause_zh": "session 作用域的 SQLAlchemy Session fixture 跨测试复用；某测试抛异常后事务失败，后续测试使用同一 session 时处于待回滚状态。",
  "versions": [
    {
      "version": "2.0.x",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    }
  ],
  "os_specific": {},
  "dead_ends": [
    {
      "action": "",
      "why_fails": "Doesn't isolate data written before the error; tests still see dirty state from previous tests.",
      "fail_rate": 0.7,
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "why_fails": "Pool size is unrelated to transaction state; the pending rollback persists on the same session object.",
      "fail_rate": 0.85,
      "condition": "",
      "sources": []
    }
  ],
  "workarounds": [
    {
      "action": "",
      "success_rate": 0.94,
      "how": "@pytest.fixture\ndef db_session(engine):\n    conn = engine.connect()\n    trans = conn.begin()\n    session = Session(bind=conn, join_transaction_mode='create_savepoint')\n    yield session\n    session.close()\n    trans.rollback()\n    conn.close()",
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "success_rate": 0.9,
      "how": "@pytest.fixture\ndef session(engine):\n    s = Session(engine)\n    yield s\n    s.rollback()\n    s.close()",
      "condition": "",
      "sources": []
    }
  ],
  "workarounds_zh": [],
  "transition_graph": {
    "leads_to": [],
    "preceded_by": [],
    "frequently_confused_with": []
  },
  "official_doc_url": null,
  "official_doc_section": null,
  "error_code": null,
  "verification_tier": "ai_generated",
  "confidence": 0.87,
  "fix_success_rate": 0.8,
  "resolvable": "true",
  "first_seen": "2025-07-15",
  "last_confirmed": "2025-01-01",
  "last_updated": "2025-01-01",
  "evidence_count": 0,
  "tags": [],
  "locale": "en",
  "aliases": []
}