Skip to content

Conversation

DominicGBauer
Copy link
Contributor

Problem

We were sporadically encountering IllegalStateException with the message "Transaction objects must be used only within the transaction lambda scope." This typically indicates a race condition where transaction objects are being accessed across different threads or coroutine contexts. I initially thought it was because of a transaction in BucketStorageImpl was using the wrong context (which was addressed in this PR #89) but this was not the case as the issue persisted.

Root Cause

Database operations were not consistently running on the same dispatcher, which could lead to transaction objects being accessed from different threads. SQLDelight requires transaction operations to maintain thread confinement for safety.

Solution

Added a dedicated IO dispatcher for all database operations by modifying the database driver creation:

val dbDispatcher = Dispatchers.IO
val dbScope = CoroutineScope(scope.coroutineContext + dbDispatcher)

This will also improve DB operation performance as the operations are now always running on the correct dispatcher.

Testing

Testing in the Swift demo no longer produces this error (although it's tough to say that this is definitively resolved since the error was sporadic).

mugikhan
mugikhan previously approved these changes Dec 19, 2024
@DominicGBauer DominicGBauer merged commit 1ad5a8b into main Dec 19, 2024
3 checks passed
@DominicGBauer DominicGBauer deleted the fix/race-condition-in-transaction branch December 19, 2024 09:39
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.

2 participants