Skip to content

Make per-transaction unit-of-work state thread-safe (store on connection.info) - #391

Open
glowskir wants to merge 1 commit into
sqlalchemy-continuum:mainfrom
glowskir:fix/thread-safe-uow-390
Open

glowskir wants to merge 1 commit into
sqlalchemy-continuum:mainfrom
glowskir:fix/thread-safe-uow-390

Conversation

@glowskir

@glowskir glowskir commented Jul 9, 2026 •

Copy link
Copy Markdown

Description

VersioningManager is a process-wide singleton whose listeners are registered once at the class level (on sa.orm.Mapper, sa.orm.session.Session, sa.engine.Engine), so every session on every thread shares it. It stored per-transaction state in two global mutable dicts:

  • manager.units_of_work — Connection -> UnitOfWork
  • manager.session_connection_map — Session -> Connection

Several code paths iterate those dicts while other threads mutate them (clear, clear_connection, _uow_from_conn, track_cloned_connections all do for c in dict(self.units_of_work): ...). Under a thread pool this races and crashes, typically:

RuntimeError: dictionary changed size during iteration

or a KeyError when another thread deletes a connection entry mid-lookup.

The connection-keyed correlation is legitimate — mapper events (after_insert/update/delete) only receive a Connection, session events only receive a Session, and the connection is the common handle. What's wrong is holding that correlation in global state.

Fix

Move the state onto SQLAlchemy's own per-object scratch space:

  • connection.info[UOW_KEY] holds the UnitOfWork
  • session.info[CONN_KEY] remembers the session's bound connection, so clear() can tear down at commit time without calling session.connection() (which would begin a new transaction — the reason the old code cached the connection).

Connection.info proxies to the underlying pooled DBAPI connection, so all Connection clones that share one DBAPI connection resolve to the same .info dict (verified against SQLAlchemy 2.0.51). That makes the entire clone-matching machinery unnecessary, so this PR deletes:

  • the clone-matching loop in _uow_from_conn,
  • track_cloned_connections and its set_connection_execution_options listener,
  • the connection.closed or conn.connection is c.connection sweeps in clear/clear_connection.

Each thread uses its own connection, so no shared mutable state remains and versioning is thread-safe by construction.

connection.info persists across pool checkouts, so a pool reset listener (clear_connection_on_reset) drops any lingering UnitOfWork on return-to-pool as a safety net — connection_record.info is the same dict Connection.info exposes, so this reliably clears state however the transaction ended.

Behaviour note

Two sessions bound to two Connection objects that wrap the same DBAPI connection (i.e. the same database transaction) now share one version transaction, instead of getting two. This only surfaces with in-memory SQLite (which serves every engine.connect() from a single shared connection); on a real pool each session gets its own connection and its own transaction as before. tests/test_sessions.py::test_multiple_connections is therefore skipped on SQLite, where the "multiple connections" premise cannot hold.

Tests

  • tests/test_thread_safe_uow_storage.py — deterministic, runs on every backend: asserts the UoW lives on connection.info, that no global dicts remain on the manager, that state is cleared after commit/rollback, and that the pool reset safety net clears a lingering UoW before the next checkout.
  • tests/test_thread_safe_uow_multithreaded.py — concurrency stress test (8 threads sharing one engine pool, insert+update+commit cycles) modelled on test_validity_strategy_multithreaded.py; this is the test that races/crashes on the pre-fix code. Skipped on SQLite (single shared connection can't exercise real concurrency); runs on postgres/mysql in CI.
  • tests/__init__.py teardown leak check updated to inspect connection.info/session.info.

Full suite green on SQLite (857 passed, 19 skipped); ruff check and ruff format --check clean.

Changelog entries added to CHANGES.rst and docs/changelog.md.

Fixes: #390

Summary by CodeRabbit

  • Bug Fixes
    • Improved reliability when multiple sessions use a shared connection pool, preventing transaction state from interfering across concurrent operations.
    • Fixed crashes that could occur while processing transactions concurrently.
    • Ensured transaction state is cleared after commit, rollback, and connection reuse.

The VersioningManager is a process-wide singleton whose listeners are
registered once at the class level, so every session on every thread shares
it. It kept per-transaction state in two global mutable dicts
(units_of_work, session_connection_map) that were iterated and mutated from
multiple threads (clear, clear_connection, _uow_from_conn,
track_cloned_connections), racing and crashing under a thread pool with
"RuntimeError: dictionary changed size during iteration" / KeyError.

Move that state onto SQLAlchemy's own per-object scratch space:
connection.info holds the UnitOfWork and session.info remembers the bound
connection for commit-time cleanup. connection.info proxies to the underlying
pooled DBAPI connection, so all Connection clones sharing it resolve to the
same UnitOfWork -- which lets us delete the entire clone-matching dance
(_uow_from_conn's loop, track_cloned_connections, and the closed/fairy
sweeps). Each thread uses its own connection, so there is no shared mutable
state left and versioning is thread-safe by construction.

connection.info persists across pool checkouts, so a pool "reset" listener
drops any lingering UnitOfWork on return-to-pool as a safety net.

Tests: add a deterministic mechanism test (runs on SQLite) and a threaded
stress test modelled on test_validity_strategy_multithreaded (postgres/mysql);
update the harness leak check to inspect connection.info/session.info.
test_multiple_connections is skipped on SQLite, whose in-memory database
serves every connection from one shared DBAPI connection and so cannot
exercise the multiple-connections path.

Fixes: sqlalchemy-continuum#390

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@dPeS

dPeS commented Jul 9, 2026

Copy link
Copy Markdown

+1

@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: a92e957c-804a-4039-97a0-dbaf2b160d8a

📥 Commits

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

📒 Files selected for processing (8)
  • CHANGES.rst
  • docs/changelog.md
  • sqlalchemy_continuum/__init__.py
  • sqlalchemy_continuum/manager.py
  • tests/__init__.py
  • tests/test_sessions.py
  • tests/test_thread_safe_uow_multithreaded.py
  • tests/test_thread_safe_uow_storage.py

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


📝 Walkthrough

Walkthrough

Unit-of-work state now resides in connection and session info rather than manager-level dictionaries. Transaction and pool-reset cleanup remove that state. Regression tests cover cleanup, pool reuse, and concurrent sessions.

Changes

Connection-scoped state

Layer / File(s) Summary
Unit-of-work storage and lookup
sqlalchemy_continuum/manager.py, CHANGES.rst, docs/changelog.md
unit_of_work() stores the session connection in session.info and retrieves or creates the unit of work through connection.info. The changelog entries describe this storage change.
Transaction and pool cleanup, and regression coverage
sqlalchemy_continuum/manager.py, sqlalchemy_continuum/__init__.py, tests/__init__.py, tests/test_thread_safe_uow_storage.py, tests/test_thread_safe_uow_multithreaded.py, tests/test_sessions.py
Transaction cleanup removes connection and session state. An Engine reset listener clears remaining connection state. Tests cover state cleanup, pool reuse, and concurrent sessions; the multiple-connection tests skip SQLite.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: josecsotomorales

Merge Risk: ⚪ Minimal · up to a62fe

No actionable issue remains that should prevent merging after normal checks.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to a62fe

Moving audit state off the shared manager improves isolation for separate pooled connections. Sessions that share one underlying database connection may now share audit state, however, which could attribute changes to the wrong user. Cleanup after an interrupted connection lifecycle also remains unverified.

Retained concerns

  • Medium · security · inferred: Distinct sessions using wrappers over one DBAPI connection can share a UOW and its first-created audit transaction. Later version records can therefore inherit the earlier session's transaction identity and user metadata.
Security review details

Security Blast Radius

  • inferred — The identified attribution risk is bounded to sessions sharing an underlying DBAPI connection; distinct pooled connections have separate info state. The available concurrency coverage does not establish behavior for shared-connection sessions.

Security Findings and Attack Paths

  • inferred — If separate application sessions with different user contexts use wrappers over one DBAPI connection, the second session can reuse the first session's audit transaction. This depends on application connection sharing, not on an established ability for an unauthenticated caller to select a connection.

Trust Boundaries and Controls

  • observed — Audit state now resides in the mutable info dictionaries exposed by SQLAlchemy session and connection objects. Repository production paths shown here use reserved keys for lookup and cleanup; no downstream mutation of those keys is established.

Resilience and Maintainability Implications

  • inferred — Interrupted cleanup remains uncertain: session cleanup accesses the remembered connection.info directly after removing the session key, and the available regression tests do not exercise a connection closed or invalidated before that callback. Pool reset provides a separate control against state surviving ordinary reuse.

Hardening Proposals

  • proposed — Define whether audit identity belongs to a database transaction or to an application session, and verify attribution for two differently identified sessions sharing a DBAPI connection.
  • proposed — Verify cleanup ordering for connection invalidation or early close, including whether session and pool cleanup still leave no reusable audit state.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.74% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 27 functions across 6 files. (2 skipped: … 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 and concisely describes the main change: moving per-transaction unit-of-work state to connection.info to improve thread safety.
Linked Issues check ✅ Passed The PR addresses issue #390. It removes the manager-owned per-connection and session maps. It stores the UnitOfWork in connection.info and the bound connection in session.info. Commit, rollback,…
Out of Scope Changes check ✅ Passed The changes stay within issue #390. The listener migration, cleanup changes, regression tests, SQLite test skip, teardown updates, and changelog entries support the connection-scoped state and thread-…
Full details: Docstring Coverage

Explanation

Docstring coverage is 40.74% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 27 functions across 6 files. (2 skipped: 2 unsupported.)

  • 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: 3/5

[High risk] Refactors how versioning state is stored and cleaned up.

The PR is not ready to merge because connection-scoped state can be reused by the wrong manager or after manager reconfiguration.

Findings

  1. P1 Managers share one unit of work ▶
  2. P1 Reset leaves old transaction state ▶
  3. P2 Skip ignores database override ▶

Summary

The PR moves unit-of-work state from manager dictionaries into connection and session info, adds pool-reset cleanup, and introduces storage and concurrency tests.

  • Connection-scoped keys need to preserve isolation between managers and across manager reconfiguration.
  • Test skips should reflect the database actually selected by the harness.
Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
  S[Session flush] --> C[Session connection]
  C --> I[Connection info]
  I --> U[UnitOfWork]
  S --> SI[Session info: connection]
  SI --> X[Commit or rollback cleanup]
  X --> I
  P[Pool reset] --> I
Loading

Reviews (1) · Last reviewed commit: "Store unit-of-work state on connection.i..."

Comment on lines +332 to +335
uow = connection.info.get(UOW_KEY)
if uow is None:
uow = self.uow_class(self)
connection.info[UOW_KEY] = uow

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Managers share one unit of work

If two VersioningManager instances use sessions on the same database connection, both look up the fixed UOW_KEY. The second manager gets the first manager’s unit of work, so its flush can use the wrong transaction model, plugins, and versioning settings. make_versioned(manager=...) allows callers to supply a different manager, but the connection and session keys do not keep their state separate.


self.session_connection_map = {}

self.metadata = None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Reset leaves old transaction state

If versioning is removed and configured again while a connection remains open, manager.reset() no longer discards the unit of work stored on that connection. The next lookup reuses its old transaction, version session, and operations, which can write incorrect audit history under the new configuration.

Comment thread tests/test_sessions.py
# DBAPI connection, so the two sessions below actually share one database
# connection (hence one transaction) and cannot exercise the
# multiple-connections path. Runs on backends with a real connection pool.
@pytest.mark.skipif("os.environ.get('DB', 'sqlite') == 'sqlite'")

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 Skip ignores database override

The test harness lets DATABASE_URL override DB, but this skip checks only DB. If DB is unset and DATABASE_URL points to PostgreSQL, this test skips despite having separate connections. The new concurrency test uses the same condition, so that setup also loses its main regression coverage. Base both skips on the database or pool actually selected.

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.

VersioningManager singleton stores per-connection state in global dicts — not thread-safe (crashes under connection pools / thread pools)

3 participants