Skip to content

Reset _flushing when a bulk_* call fails before it can begin - #13488

Closed
alliasgher wants to merge 1 commit into
sqlalchemy:mainfrom
alliasgher:fix-bulk-flushing-flag
Closed

alliasgher wants to merge 1 commit into
sqlalchemy:mainfrom
alliasgher:fix-bulk-flushing-flag

Conversation

@alliasgher

Copy link
Copy Markdown

Fixes #13485

Description

Session._bulk_save_mappings sets the flushing flag and begins the transaction above its try::

mapper = _class_to_mapper(mapper)
self._flushing = True

transaction = self._autobegin_t()._begin()
try:
    ...
finally:
    self._flushing = False

_begin() carries @_StateChange.declare_states((SessionTransactionState.ACTIVE,), NO_CHANGE), so on a Session whose transaction is not active it raises PendingRollbackError — before the try: is entered. The finally: never runs and _flushing stays True.

The Session is then unrecoverable: grep -n "_flushing" shows the flag is only ever set back to False in __init__, in flush(), and in that finally:. Neither rollback() nor close() touches it, so the recovery the PendingRollbackError message advises does not work, and every subsequent flush() raises InvalidRequestError: Session is already flushing.

flush() itself is fine — it sets the flag inside its try: (session.py:4504-4513), which is why the reporter's step 1 self-heals and only the bulk path sticks.

Reproduced on current main (2.1.0b4, 5995834) with the reporter's script; output matches their 1.4.54 / 2.0.51 results exactly.

Fix

The obvious-looking fix — move self._flushing = True below _begin() and into the try: — would be wrong, and I want to flag that explicitly since it is the first thing a reviewer will reach for.

_begin() constructs a SessionTransaction with origin SUBTRANSACTION, and SessionTransaction.__init__ does:

if not is_begin and not self.session._flushing:
    self.session.flush()

So the flag being set before _begin() is load-bearing — it suppresses a recursive autoflush on the bulk path. I kept the assignment where it is and wrapped _begin() plus the existing try/except in the try: instead, which is a pure indentation change to the existing body.

Tests

Added to SessionTransactionTest in test/orm/test_transaction.py rather than test/orm/dml/test_bulk.py, because that class already has _inactive_flushed_session_fixture(), which produces exactly the deactivated-transaction state this needs, and its FixtureTest base handles table lifecycle for a session that is deliberately left mid-failure. (I tried it in test_bulk.py first; BulkTest.run_define_tables = "each" plus sqlite:///:memory: meant a deliberately un-rolled-back session took the schema with it between tests.)

The test parameterises over bulk_update_mappings and bulk_insert_mappings, asserts _flushing is False after the PendingRollbackError, and then asserts the documented recovery works — rollback(), add, commit() — since silently losing the Session is the actual user-visible symptom.

Verified non-vacuous: with lib/sqlalchemy/orm/session.py reverted both parameterisations fail; with the fix both pass.

test/orm/ in full: 10880 passed, 142 skipped. black --check clean on both changed files; flake8 reports the same 21 pre-existing I100 import-order notes on session.py before and after.

Changelog

doc/build/changelog/unreleased_20/13485.rst, since the issue is milestoned 2.0.x.

_bulk_save_mappings set self._flushing = True and called
self._autobegin_t()._begin() above its try:, so the finally: that resets the
flag never ran if _begin() raised. On a Session whose transaction is not
active, _begin() raises PendingRollbackError through its
@_StateChange.declare_states guard.

The Session was then stuck: _flushing is only ever cleared in __init__,
flush() and here, so neither rollback() nor close() recovers it and every
later flush() raises 'Session is already flushing'.

The assignment stays above _begin(): SessionTransaction.__init__ autoflushes
when the flag is not set, so moving it below would recurse. Wrap _begin()
and the existing try/except in the try instead.

Fixes: sqlalchemy#13485
@CaselIT

CaselIT commented Aug 9, 2026

Copy link
Copy Markdown
Member

hi, thanks but there is already #13487 open

@CaselIT CaselIT closed this Aug 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A failed bulk_* call leaves Session in flushing state

2 participants