Repository navigation
Conversation
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]>
|
+1 |
|
@coderabbitai full review |
✅ Action performedFull review finished. |
|
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 configurationConfiguration used: defaults Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (8)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review. 📝 WalkthroughWalkthroughUnit-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. ChangesConnection-scoped state
Priority: ➖ Normal Estimated code review effort: 3 (Moderate) | ~25 minutes Change: Bug fix · Severity of issue fixed: Medium Suggested reviewers: Merge Risk: ⚪ Minimal · up to No actionable issue remains that should prevent merging after normal checks. Security Architecture ReviewSecurity architecture risk: 🟡 Moderate · up to 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
Security review detailsSecurity Blast Radius
Security Findings and Attack Paths
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Docstring CoverageExplanation 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.)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
|
| uow = connection.info.get(UOW_KEY) | ||
| if uow is None: | ||
| uow = self.uow_class(self) | ||
| connection.info[UOW_KEY] = uow |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
| # 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'") |
There was a problem hiding this comment.
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.
Description
VersioningManageris a process-wide singleton whose listeners are registered once at the class level (onsa.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 -> UnitOfWorkmanager.session_connection_map—Session -> ConnectionSeveral code paths iterate those dicts while other threads mutate them (
clear,clear_connection,_uow_from_conn,track_cloned_connectionsall dofor c in dict(self.units_of_work): ...). Under a thread pool this races and crashes, typically:or a
KeyErrorwhen another thread deletes a connection entry mid-lookup.The connection-keyed correlation is legitimate — mapper events (
after_insert/update/delete) only receive aConnection, session events only receive aSession, 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 theUnitOfWorksession.info[CONN_KEY]remembers the session's bound connection, soclear()can tear down at commit time without callingsession.connection()(which would begin a new transaction — the reason the old code cached the connection).Connection.infoproxies to the underlying pooled DBAPI connection, so allConnectionclones that share one DBAPI connection resolve to the same.infodict (verified against SQLAlchemy 2.0.51). That makes the entire clone-matching machinery unnecessary, so this PR deletes:_uow_from_conn,track_cloned_connectionsand itsset_connection_execution_optionslistener,connection.closed or conn.connection is c.connectionsweeps inclear/clear_connection.Each thread uses its own connection, so no shared mutable state remains and versioning is thread-safe by construction.
connection.infopersists across pool checkouts, so a poolresetlistener (clear_connection_on_reset) drops any lingeringUnitOfWorkon return-to-pool as a safety net —connection_record.infois the same dictConnection.infoexposes, so this reliably clears state however the transaction ended.Behaviour note
Two sessions bound to two
Connectionobjects 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 everyengine.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_connectionsis 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 onconnection.info, that no global dicts remain on the manager, that state is cleared after commit/rollback, and that the poolresetsafety 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 ontest_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__.pyteardown leak check updated to inspectconnection.info/session.info.Full suite green on SQLite (
857 passed, 19 skipped);ruff checkandruff format --checkclean.Changelog entries added to
CHANGES.rstanddocs/changelog.md.Fixes: #390
Summary by CodeRabbit