fix: flush table-update notifications while holding the write mutex#1
Merged
Merged
Conversation
There was a problem hiding this comment.
Pull request overview
This PR fixes a concurrency bug in MDSQLiteAdapter.WriteLock where writeConnection.FlushUpdates() could enumerate MDSQLiteConnection’s updateBuffer concurrently with the SQLite update hook appending to it, causing InvalidOperationException and potentially mis-batching or losing table-update notifications.
Changes:
- Move
writeConnection.FlushUpdates()to execute while holdingwriteMutexin bothWriteLockoverloads. - Ensure update notifications are flushed/cleared deterministically within the single-writer critical section, preventing concurrent mutation during enumeration.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
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.
Problem
MDSQLiteAdapter.WriteLock(both overloads) callswriteConnection.FlushUpdates()after releasingwriteMutex.FlushUpdates()enumerates the connection'supdateBuffer(a plainList<>), which the SQLite update hook appends to from whichever thread is executing a write. With two overlappingWriteLockcalls, the second caller's hook fires while the first is still enumerating:The late flush also misattributes updates: a concurrent writer's entries can land in another caller's
TablesUpdatedEventbatch or be lost to itsClear(), soWatchqueries can silently miss changes.Fix
Move
FlushUpdates()inside the mutex. The update hook only fires during writes, which only happen under the mutex, so the buffer becomes single-threaded by construction. No deadlock risk:EventStream.Emitis a non-blockingChannel.Writer.TryWriteand subscribers consume on their own tasks.