fix: race condition in transaction #91
Merged
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.
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:
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).