fix: use RLock to prevent deadlock in database singleton initialization#654
Merged
fix: use RLock to prevent deadlock in database singleton initialization#654
Conversation
get_engine() and get_session_factory() share the same threading.Lock(). When SessionLocal() is the first DB call (before get_engine() has been called independently), get_session_factory() acquires the lock then calls get_engine() which tries to acquire the same non-reentrant lock, causing a deadlock. This was masked in the OSS app because _verify_database() in the lifespan always calls get_engine() first. Premium (and any other consumer that calls SessionLocal() without a prior get_engine()) hits the deadlock on startup. Switching to RLock (reentrant) allows the nested acquisition to succeed. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
get_engine()andget_session_factory()inbackend/app/database.pyshare the samethreading.Lock(). WhenSessionLocal()is the first DB call (both singletons uninitialized),get_session_factory()acquires the lock then callsget_engine(), which tries to acquire the same non-reentrant lock, causing a deadlock.This was masked in the OSS app because
_verify_database()in the lifespan always pre-initializesget_engine(), but any consumer that callsSessionLocal()beforeget_engine()(e.g. clawbolt-premium) deadlocks on startup.Fix: switch
threading.Lock()tothreading.RLock()(reentrant) so nested acquisition by the same thread succeeds.Type
Checklist
uv run pytest -v)ruff check backend/ && ruff format --check backend/)AI Usage
Claude Code diagnosed the deadlock root cause through systematic middleware/request stack analysis and implemented the fix.