Skip to content

fix(#392): handle join_txn_mode for version_session - #393

Open
skissane-medallia wants to merge 1 commit into
sqlalchemy-continuum:mainfrom
skissane-medallia:fix-issue-392
Open

skissane-medallia wants to merge 1 commit into
sqlalchemy-continuum:mainfrom
skissane-medallia:fix-issue-392

Conversation

@skissane-medallia

@skissane-medallia skissane-medallia commented Jul 10, 2026 •

Copy link
Copy Markdown

Description

Ported corridor/sqlalchemy-history#122 fix from sqlalchemy-history fork to this project

Fixes: #392

Description by fix original author (@ashish16052):

  • SQLA 2.0 introduced new session param called join_transaction_mode which changes the behaviour of how existing transactions are handled

  • When using a Connection with an existing SAVEPOINT: SQLA-1.4: the Session would propagate both commit() and rollback() calls to the underlying transaction. SQLA-2.0: use join_transaction_mode=control_fully to replicate the same behaviour.

  • When using a Connection without an existing SAVEPOINT: SQLA-1.4: the Session would propagate only rollback() calls to the underlying transaction. SQLA-2.0: use join_transaction_mode=rollback_only to replicate the same behaviour.

  • use rollback_only mode while creation of version_session, as it is using an existing connection, and we are never doing a commit() on it.

Checklist

This pull request is:

  • A documentation / typographical error fix
    • Good to go, no issue or tests are needed
  • A short code fix
    • Please include the issue number, and create an issue if none exists, which
      must include a complete example of the issue.
    • Please include: Fixes: #<issue number> in the commit message
    • Please include tests. A test that fails without the fix is strongly preferred.
  • A new feature implementation
    • Please include the issue number, and create an issue if none exists, which
      must include a complete example of how the feature would look.
    • Please include tests and documentation updates.

Summary by CodeRabbit

  • Bug Fixes
    • Improved compatibility with different SQLAlchemy versions when creating versioning sessions.
    • Avoided a SQLAlchemy warning during nested transactions while preserving version history updates.

- SQLA 2.0 introduced new session param called `join_transaction_mode`
  which changes the behaviour of how existing transactions are handled

- When using a Connection with an existing SAVEPOINT:
  `SQLA-1.4`: the Session would propagate both commit() and rollback()
  calls to the underlying transaction.
  `SQLA-2.0`: use join_transaction_mode=control_fully to replicate the
  same behaviour.

- When using a Connection without an existing SAVEPOINT:
  `SQLA-1.4`: the Session would propagate only rollback() calls to the
  underlying transaction.
  `SQLA-2.0`: use join_transaction_mode=rollback_only to replicate the
  same behaviour.

- use `rollback_only` mode while creation of version_session, as it is
  using an existing connection, and we are never doing a commit() on it.

Cherry-picked by @skissane-medallia from
corridor/sqlalchemy-history#122 by @ashish16052

Closes sqlalchemy-continuum#392
@josecsotomorales

Copy link
Copy Markdown
Collaborator

@greptileai

@josecsotomorales

Copy link
Copy Markdown
Collaborator

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
✅ Action performed

Full review finished.

@coderabbitai

coderabbitai Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: 684cb09e-929d-4c0a-8ed0-b2865118db8e

📥 Commits

Reviewing files that changed from the base of the PR and between 560369a and 66a4f5a.

📒 Files selected for processing (2)
  • sqlalchemy_continuum/unit_of_work.py
  • tests/test_revert.py

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.


📝 Walkthrough

Walkthrough

The unit of work now creates version sessions through a shared helper. The helper selects rollback-only transaction joining when supported and falls back to connection binding. A regression test checks version creation during a nested transaction while treating SAWarning as an error.

Changes

Version session handling

Layer / File(s) Summary
Version-session creation and nested-transaction test
sqlalchemy_continuum/unit_of_work.py, tests/test_revert.py
The unit of work uses a shared helper to create version sessions in its flush and transaction paths. The helper uses join_transaction_mode='rollback_only' when supported and retries with connection binding if construction raises TypeError. The test checks version creation in a nested transaction with SAWarning treated as an error.

Priority: ⬇️ Low

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Low

Suggested reviewers: josecsotomorales

Merge Risk: ⚪ Minimal · up to 66a4f

The change is focused on version-session handling during nested transactions and adds a regression check. Based on the available evidence, no concrete merge-blocking risk remains.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 66a4f

The change keeps history writes on the caller’s database connection and adds no evident new access path. Its compatibility fallback could, under an unexpected error, use different rollback behavior; failure and retry behavior remains unverified.

Retained concerns

  • Low · reliability · inferred: The new helper retries without rollback_only for any TypeError from connection acquisition or Session construction, not just an unsupported keyword. If an unrelated error permits that retry to succeed on SQLAlchemy 2.x, the intended rollback-joining contract would be bypassed. That triggering path is not established.
Security review details

Security Blast Radius

  • inferred — The repository-local effect is on history writes for sessions tracked by this library and their existing database transactions. Application tenant routing, credentials, and deployment-wide exposure are not established.

Trust Boundaries and Controls

  • inferred — The changed path introduces no evidenced attacker-controlled input or new identity transition: tracked Session events still lead to a UnitOfWork keyed by that session’s connection, which supplies the auxiliary session’s bind.

Resilience and Maintainability Implications

  • inferred — Nested history assertions provide counterevidence to ordinary commit and rollback inconsistency, but do not establish recovery after partial failure or ownership behavior for concurrent sessions sharing a connection.

Hardening Proposals

  • proposed — Limit the compatibility fallback to an unsupported join_transaction_mode argument, and verify both supported-version branches and interrupted-flush recovery before relying on uniform rollback behavior.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 55.56% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the primary change: handling transaction mode when creating the version session. It is concise and directly related to the pull request.
Linked Issues check ✅ Passed Issue [#392] requires preventing the SQLAlchemy 2.x nested-transaction warning. UnitOfWork.create_version_session passes join_transaction_mode='rollback_only' when the installed Session supports…
Out of Scope Changes check ✅ Passed The changes stay within issue [#392]. The unit_of_work.py change configures the version session transaction mode. The test change adds coverage for the reported nested-transaction warning. The `pyte…
  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 4/5

[Medium risk] Adjusts how version tracking sessions handle database transactions.

The transaction change appears safe to merge once the explicit repository style requirement is satisfied.

Findings

  1. P2 Docstring exceeds line limit ▶
  2. P2 Fallback retries unrelated errors ▶

Summary

The PR creates version sessions with SQLAlchemy 2.x’s rollback_only join mode while retaining a fallback for SQLAlchemy 1.4.

  • Updates all three version-session creation sites.
  • Adds a nested-transaction versioning test.

Reviews (1) · Last reviewed commit: "fix(#392): handle join_txn_mode for vers..."


def create_version_session(self, session):
"""
In SQLA-2.0, when using an existing connection with savepoint, Set join_transaction_mode="rollback_only"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Docstring exceeds line limit The new docstring exceeds the repository’s required 88-character line length. Please wrap it before merging.

Suggested change
In SQLA-2.0, when using an existing connection with savepoint, Set join_transaction_mode="rollback_only"
In SQLA-2.0, when using an existing connection with savepoint, Set
join_transaction_mode="rollback_only"

Context Used: CLAUDE.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment on lines +26 to +31
try:
return sa.orm.session.Session(
bind=session.connection(), join_transaction_mode='rollback_only'
)
except TypeError:
return sa.orm.session.Session(bind=session.connection())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Fallback retries unrelated errors The TypeError handler also catches errors from session.connection(), not just an unsupported SQLAlchemy 1.4 keyword. If connection acquisition raises an unrelated TypeError, the fallback calls it again and can obscure the original failure. Check compatibility before constructing the version session, and obtain the connection once.

@andrewswait

Copy link
Copy Markdown

@josecsotomorales anything blocking this being merged? We're moving a large test suite over to transactions that roll-back (using create_savepoint as you suggested in #204) and hit #392 on 1.7.0 with SqlAlchemy 2.0.51. I had more or less the same fix as a test-only UnitOfWork subclass before finding this PR. Would much rather upgrade than keep that around. Happy to test a pre-release if that helps!

@marksteward

marksteward commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

We don't support SQLAlchemy 1.4 any more, so the fallback behaviour is unnecessary (and too broad, as greptile points out). So the real question is whether our default join_transaction_mode should be rollback_only, which I think would be a breaking change.

Can you justify making this change the default, or should it be an initialisation argument?

This branch has not been deployed

No deployments
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.

SAWarning: nested transaction already deassociated from connection

5 participants