Repository navigation
Description
Discussed in #13484
Originally posted by jaxtell-patreon August 8, 2026
We hit a situation where a Session becomes permanently unusable, and I would like to understand whether this is expected behaviour and what the supported recovery is — before assuming it is a bug.
If a bulk_update_mappings() / bulk_insert_mappings() / bulk_save_objects() call is made while the Session's transaction is not active (for example after a failed flush that has not yet been rolled back), the call raises PendingRollbackError as I would expect — but the Session is left with _flushing set to True, and every subsequent flush() then raises InvalidRequestError: Session is already flushing.
What surprised us is that the usual recovery does not clear it: after Session.rollback() — which is what the PendingRollbackError message advises — and even after Session.close(), the Session still raises on the next flush(). In our case the Session is reused across units of work, so it stays broken until the object itself is discarded.
Reproduction
import sqlalchemy
from sqlalchemy import Column, Integer, String, create_engine, exc as sa_exc
from sqlalchemy.orm import Session, declarative_base
print("SQLAlchemy", sqlalchemy.__version__)
Base = declarative_base()
class Thing(Base):
__tablename__ = "thing"
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
session = Session(engine)
session.add(Thing(id=1, name="original"))
session.commit()
# 1. A failed flush leaves the transaction needing a rollback. Deliberately do not roll back yet.
session.add(Thing(id=2, name=None))
try:
session.flush()
except Exception as e:
print("1. flush failed as expected:", type(e).__name__)
print(" _flushing after failed flush:", session._flushing)
# 2. A bulk_* call on that session.
try:
session.bulk_update_mappings(Thing, [{"id": 1, "name": "updated"}])
except Exception as e:
print("2. bulk_update_mappings raised:", type(e).__name__)
print(" _flushing after bulk call: ", session._flushing)
# 3. Does the documented recovery clear it?
session.rollback()
print("3. _flushing after rollback():", session._flushing)
session.close()
print(" _flushing after close(): ", session._flushing)
# 4. State of the Session now.
try:
session.flush()
print("4. flush() succeeded")
except sa_exc.InvalidRequestError as e:
print("4. flush() raises:", e)Output, identical on 1.4.54 and 2.0.51:
- flush failed as expected: IntegrityError
_flushing after failed flush: False - bulk_update_mappings raised: PendingRollbackError
_flushing after bulk call: True - _flushing after rollback(): True
_flushing after close(): True - flush() raises: Session is already flushing
Note that step 1 shows flush() itself cleaning up correctly — it is only the bulk path where the flag persists.
Questions
- Is a Session expected to be recoverable after a bulk_* call raises on an inactive transaction, or is discarding the Session the intended response?
- If it is meant to be recoverable, is there a supported way to do so? rollback() and close() both leave _flushing set, and it is a private attribute so resetting it directly does not feel like something we should rely on.
- Reading _bulk_save_mappings, self._flushing = True and the transaction-begin are outside the try whose finally resets the flag (2.0.51 orm/session.py:4739/4741/4766; 1.4.54 has the same shape at :3877-3915), whereas flush() sets it inside its try. Is that difference deliberate?
Happy to open an issue if this turns out to be unintended rather than a usage mistake on our side.
Versions
OS: Linux
Python: 3.12.9
SQLAlchemy: reproduced on 1.4.54 and 2.0.51
Database: SQLite for the script above; originally observed on MySQL 8 / PyMySQL, where a deadlock during a bulk update is what leaves the transaction needing a rollback
DBAPI: sqlite3, pymysql
Activity
alliasgher commentedon Aug 8, 2026
Opened #13488 for this.
sqla-tester commentedon Aug 11, 2026
hamodywe has proposed a fix for this issue in the main branch:
Reset Session.flushing when a bulk call can't begin its transaction* https://gerrit.sqlalchemy.org/c/sqlalchemy/sqlalchemy/+/6882
sqla-tester commentedon Aug 11, 2026
Hamody We has proposed a fix for this issue in the rel_2_0 branch:
Reset Session.flushing when a bulk call can't begin its transaction* https://gerrit.sqlalchemy.org/c/sqlalchemy/sqlalchemy/+/6883
Reset Session._flushing when a bulk_* call can't begin its transaction
Reset Session._flushing when a bulk_* call can't begin its transaction