Fix | Fix race condition issues between SinglePhaseCommit and TransactionEnded events #1042
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.
A race condition exists between "Single Phase Commit" and "Transaction Ended" as both are triggered externally by delegated SqlTransaction. With recent changes to doom connection in "Transaction Ended" Event (#543), "Commit" started failing intermittently leading to this issue. Dooming connection is essential to prevent connection re-use that leads to security issues, so that fix is intact.
But as a consequence, "Commit"'s inconsistent locking leads to this problem. Locking is essential in this design, but in "Single Phase Commit" implementation, late and split locking causes issues between Commit and Abort event handling, leading to intermittent "Transaction Aborted Exception".
This change in lock scope fixes the issue. It wasn't easily reproducible in Microsoft.Data.SqlClient but happens very often with System.Data.SqlClient 4.8.2. Making test-case more rigorous and forcing latency while debugging aided in reproducing this issue.
Link to Repro.
Possibly also related to issue #729 (repro)
P.S. Fix tested with System.Data.SqlClient in debug session.
cc @saurabh500