Skip to content

A failed bulk_* call leaves Session in flushing state #13485

Closed

Description

@CaselIT

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:

  1. flush failed as expected: IntegrityError
    _flushing after failed flush: False
  2. bulk_update_mappings raised: PendingRollbackError
    _flushing after bulk call: True
  3. _flushing after rollback(): True
    _flushing after close(): True
  4. 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

  1. Is a Session expected to be recoverable after a bulk_* call raises on an inactive transaction, or is discarding the Session the intended response?
  2. 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.
  3. 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

  1. added this to the 2.0.x milestone on Aug 8, 2026
  2. added
    bug
    great mcve
    on Aug 8, 2026
  3. alliasgher commented on Aug 8, 2026

    @alliasgher

    Opened #13488 for this.

  4. added
    code review in progress
    on Aug 11, 2026
  5. sqla-tester commented on Aug 11, 2026

    @sqla-tester
    Collaborator

    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

  6. sqla-tester commented on Aug 11, 2026

    @sqla-tester
    Collaborator

    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

  7. added a commit that references this issue on Aug 11, 2026
    4c42358
  8. added a commit that references this issue on Aug 11, 2026
    4914050
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugcode review in progressgreat mcveorm

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions