Fix deadlock when command is being cancelled from two threads #1131
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.
Hi there,
A couple of days ago we encountered a deadlock inside mysql connector which lead our system to downtime.
What happened?
Our monitoring detected that there are no new writes are happened to database in about 10 minutes. We dumped process memory and started looking for a problem. It turned out that deadlock happened in TimerQueue and connection Session.
The problem
The problem is that timer callback is being called under TimerQueue lock. Since callback can be almost any user code no one restricts it from acquiring other locks inside which exactly happened in our case.
ServerSession.TryStartCancel
andServerSession.DoCancel
already uses a lock inside to protect internal session state and when it's called from TimerQueue it also implicitly acquires the lock on TimerQueue.I attached screenshots which clearly illustrates the problem.
Reproduction
I was able to create a pretty stable repro. All you need is to make cancellation happenned simultaneously both from external cancellation source (CancellationTokenSource with timeout/HttpContext.RequestAborted etc.) and command timeout watchdog.
You can examine the code here https://github.com/ahydrax/StableMysqlConnectorDeadlockRepro
The solution
From my perspective solution should be pretty simple: timer queue calls pending callbacks outside of TimerQueue internal lock.
Closing notes
After fixing deadlock I've encountered a small bug inside
Session.TryStartCancel
which didn't respect all command states inside during state verifying.