Repository navigation
Description
Describe the bug
Cancelling a SqlConnection.OpenAsync(token) that is auto-enlisting in an ambient TransactionScope deadlocks the connection against that scope's own rollback. Two threads take the connection monitor and the parser lock in opposite orders and neither can proceed. There is no exception — the process just stops.
Pooling=false is required (see below for why).
thread A — the open the caller already cancelled and stopped waiting on
SqlConnectionFactory.CreateReplaceConnectionContinuation
→ SqlConnectionInternal..ctor → OpenLoginEnlist → LoginNoFailover → CompleteLogin
→ SqlConnectionInternal.EnlistNonNull
→ Transaction.add_TransactionCompleted
→ DbConnectionInternal.TransactionCompletedEvent
→ DbConnectionInternal.CleanupConnectionOnTransactionCompletion
→ DbConnectionInternal.DetachTransaction → set_EnlistedTransaction
→ Monitor.Enter_Slowpath [BLOCKED: wants lock(connection), held by B]
owns: connection's parser lock semaphore, System.Transactions.InternalTransaction
thread B — the caller unwinding from the cancellation
TransactionScope.Dispose → Transaction.Rollback
→ TransactionStateAborted.EnterState → DurableEnlistmentAborting.EnterState
→ SqlDelegatedTransaction.Rollback [owns lock(connection)]
→ SqlConnectionInternal.ExecuteTransaction → ExecuteTransaction2005
→ SyncAsyncLock.Wait
→ Monitor.Enter_Slowpath [BLOCKED: wants the parser lock, held by A]
syncblk from a dump of the failing test below, one pair per deadlocked worker:
Index MonitorHeld Owning Thread SyncBlock Owner
25 3 151d4 Microsoft.Data.SqlClient.Connection.SqlConnectionInternal
26 3 9fcc System.Threading.SemaphoreSlim
75 3 14894 Microsoft.Data.SqlClient.Connection.SqlConnectionInternal
76 3 23698 System.Threading.SemaphoreSlim
125 1 1ca8c System.Transactions.InternalTransaction
126 3 1ca8c System.Threading.SemaphoreSlim
127 3 1d170 Microsoft.Data.SqlClient.Connection.SqlConnectionInternal
This looks like the same family as #1124 (fixed by #1242) and #1800 (fixed by #1801), but it is a different pair of locks. Both of those were lock(connection) → InternalTransaction, and both fixes moved the enlistment callback out of lock(connection). This one is lock(connection) → parser lock, racing parser lock → lock(connection), so those fixes do not cover it.
To reproduce
A stress test in the repo's own conventions. It drops into src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/ and needs nothing but a connection string — no table, no test data, nothing to clean up. It fails, typically within 30 seconds:
Failed TransactionCancelledOpenTest.CancellingOpenAsyncInsideTransactionScopeDoesNotDeadlock [21 s]
Deadlocked after 1227 cancelled opens: worker 0 has made no progress for 21s.
Standard Output: Open takes ~2.21 ms. Cancelling at 0.55..1.25x that.
Two details matter for reproducing it, and both are in the test:
Pooling=false.SqlConnectionInternalcallsCompleteLogin(!ConnectionOptions.Pooling), andCompleteLoginonly auto-enlists when thatenlistOKis true. So the enlistment only runs inside the login, while the ctor holds the parser lock, when pooling is off. With pooling on this path is not taken.- Cancelling inside the login.
CancelAfterrides the OS timer (~15.6ms), which is an order of magnitude coarser than a login, so every timer-based cancellation lands after the open has already finished. The test starts the open, spins onStopwatchfor a fraction of a continuously re-measured open duration, then cancels.
TransactionCancelledOpenTest.cs
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.Data.SqlClient.ManualTesting.Tests
{
/// <summary>
/// Cancelling an OpenAsync that is auto enlisting in an ambient TransactionScope deadlocks the
/// connection against the scope's own rollback.
///
/// Thread A, the open the caller has already cancelled and stopped waiting on. The connection
/// ctor holds _parserLock for the whole login (SyncAsyncLock.Wait(canReleaseFromAnyThread:
/// false) keeps Monitor.Enter(_semaphore)). CompleteLogin -> Enlist -> EnlistNonNull registers
/// the promotable single phase enlistment and then assigns EnlistedTransaction. The transaction
/// has aborted by then, so add_TransactionCompleted invokes the handler inline and
/// DetachTransaction blocks on lock(connection).
///
/// Thread B, the caller unwinding from the cancellation. TransactionScope.Dispose rolls the
/// transaction back, SqlDelegatedTransaction.Rollback takes lock(connection) and then calls
/// ExecuteTransaction. ThreadHasParserLockForClose is scoped to the thread that owns the lock,
/// so thread B does not see thread A's claim and waits on _parserLock.
///
/// Neither side can proceed. The window is the whole Begin round trip inside
/// SqlDelegatedTransaction.Initialize, so this reproduces in seconds rather than being a rare
/// race.
///
/// Pooling=false is required: CompleteLogin is called as CompleteLogin(!Pooling), so the
/// auto enlistment only runs inside the login, while the parser lock is held, when pooling is
/// off.
///
/// Related but distinct from the two deadlocks already fixed in this area, both of which were
/// lock(connection) -> InternalTransaction: GH#1124 (SinglePhaseEnlistment.Aborted, fixed in
/// GH#1242) and GH#1800 (SinglePhaseCommit with MSDTC, fixed in GH#1801). This one is
/// lock(connection) -> parser lock against parser lock -> lock(connection).
///
/// This is a stress test. It runs for up to <see cref="RunFor"/> and, when it reproduces, it
/// leaves the deadlocked threads and a wedged connection behind, so the test process should be
/// considered poisoned afterwards.
/// </summary>
[Trait("Set", "3")]
public class TransactionCancelledOpenTest
{
public TransactionCancelledOpenTest(ITestOutputHelper output)
{
_output = output;
}
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))]
public async Task CancellingOpenAsyncInsideTransactionScopeDoesNotDeadlock()
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TCPConnectionString);
builder.Pooling = false;
string connectionString = builder.ConnectionString;
double openMilliseconds = await MeasureOpen(connectionString);
_output.WriteLine($"Open takes ~{openMilliseconds:F2} ms. Cancelling at 0.55..1.25x that.");
State state = new State(
deadline: Stopwatch.GetTimestamp() + (long)(RunFor.TotalSeconds * Stopwatch.Frequency),
workers: Workers,
openMilliseconds: openMilliseconds);
for (int i = 0; i < Workers; i++)
{
int worker = i;
// Not tracked on purpose. When the deadlock happens these never complete, and
// awaiting them would turn a failing test into a hanging one.
_ = Task.Run(() => Worker(worker, connectionString, state));
}
while (true)
{
await Task.Delay(TimeSpan.FromSeconds(1));
long now = Stopwatch.GetTimestamp();
int stalled = -1;
double worstStall = 0;
long total = 0;
for (int i = 0; i < Workers; i++)
{
total += Volatile.Read(ref state.Iterations[i]);
double stall = Elapsed(Volatile.Read(ref state.Progress[i]), now) / 1000d;
if (stall > worstStall)
{
worstStall = stall;
if (stall > StallTimeout.TotalSeconds)
{
stalled = i;
}
}
}
if (stalled >= 0)
{
Assert.Fail(
$"Deadlocked after {total} cancelled opens: worker {stalled} has made no progress for " +
$"{worstStall:F0}s. In a dump, syncblk shows one thread owning the connection's monitor " +
"in SqlDelegatedTransaction.Rollback and waiting on the parser lock, and another owning " +
"the parser lock's semaphore in CleanupConnectionOnTransactionCompletion and waiting on " +
"the connection's monitor.");
}
if (now > state.Deadline)
{
_output.WriteLine($"{total} cancelled opens without a deadlock.");
return;
}
}
}
private static async Task Worker(int worker, string connectionString, State state)
{
Random random = new Random(worker * 7919);
while (Stopwatch.GetTimestamp() < state.Deadline)
{
if (Volatile.Read(ref state.Iterations[worker]) % 8 == 7)
{
// Re-measure, so the cancellation stays aimed at the login whatever the server
// and machine are doing.
state.RecordOpen(await MeasureOpenOnce(connectionString));
}
else
{
using (CancellationTokenSource source = new CancellationTokenSource())
{
try
{
using (TransactionScope scope = NewScope())
{
SqlConnection connection = new SqlConnection(connectionString);
try
{
// OpenAsync returns a pending task once the login is in flight,
// and the ambient transaction has already been captured.
Task open = connection.OpenAsync(source.Token);
// CancelAfter rides the OS timer, which is an order of magnitude
// coarser than a login. Spinning is the only way to land inside
// the enlistment.
SpinFor(state.OpenMilliseconds * (0.55 + (random.NextDouble() * 0.7)));
source.Cancel();
await open.ConfigureAwait(false);
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "SELECT 1";
await command.ExecuteScalarAsync(source.Token).ConfigureAwait(false);
}
scope.Complete();
}
finally
{
connection.Dispose();
}
}
}
catch (Exception)
{
// Cancelling the open is the point of the test.
}
}
}
Volatile.Write(ref state.Progress[worker], Stopwatch.GetTimestamp());
Interlocked.Increment(ref state.Iterations[worker]);
}
}
private static TransactionScope NewScope()
{
return new TransactionScope(
TransactionScopeOption.RequiresNew,
new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted },
TransactionScopeAsyncFlowOption.Enabled);
}
private static async Task<double> MeasureOpen(string connectionString)
{
List<double> samples = new List<double>();
for (int i = 0; i < 10; i++)
{
samples.Add(await MeasureOpenOnce(connectionString));
}
samples.Sort();
return samples[samples.Count / 2];
}
/// <summary>
/// Timed inside a scope on purpose. The window this test aims at is the promotable single
/// phase enlistment, which is a round trip at the very end of the login.
/// </summary>
private static async Task<double> MeasureOpenOnce(string connectionString)
{
long start = Stopwatch.GetTimestamp();
using (TransactionScope scope = NewScope())
using (SqlConnection connection = new SqlConnection(connectionString))
{
await connection.OpenAsync().ConfigureAwait(false);
scope.Complete();
}
return Elapsed(start, Stopwatch.GetTimestamp());
}
private static double Elapsed(long start, long end)
{
return (end - start) * 1000d / Stopwatch.Frequency;
}
private static void SpinFor(double milliseconds)
{
long deadline = Stopwatch.GetTimestamp() + (long)(milliseconds * Stopwatch.Frequency / 1000d);
while (Stopwatch.GetTimestamp() < deadline)
{
Thread.SpinWait(40);
}
}
private sealed class State
{
public State(long deadline, int workers, double openMilliseconds)
{
Deadline = deadline;
Progress = new long[workers];
Iterations = new long[workers];
_openMilliseconds = openMilliseconds;
long now = Stopwatch.GetTimestamp();
for (int i = 0; i < workers; i++)
{
Progress[i] = now;
}
}
public long Deadline { get; }
public long[] Progress { get; }
public long[] Iterations { get; }
public double OpenMilliseconds
{
get { return Volatile.Read(ref _openMilliseconds); }
}
public void RecordOpen(double sample)
{
Volatile.Write(ref _openMilliseconds, (Volatile.Read(ref _openMilliseconds) * 0.9) + (sample * 0.1));
}
private double _openMilliseconds;
}
private readonly ITestOutputHelper _output;
private const int Workers = 8;
private static readonly TimeSpan RunFor = TimeSpan.FromMinutes(2);
private static readonly TimeSpan StallTimeout = TimeSpan.FromSeconds(20);
}
}Run it with:
dotnet test src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTests.csproj -c Release -f net10.0 --filter "FullyQualifiedName~TransactionCancelledOpenTest"
A caveat if you want to take the test as-is: it is not CI-safe. It burns up to two minutes when it passes, and when it reproduces it leaves the deadlocked threads and wedged connections behind, so the test host is poisoned afterwards. It probably wants [ActiveIssue] or a trait that keeps it out of the normal run.
Expected behavior
Cancelling OpenAsync should not be able to deadlock the connection. Either the continuation for an open the caller has already abandoned should not enlist in the ambient transaction, or the enlistment and rollback paths should agree on a lock order.
Further technical details
Microsoft.Data.SqlClient version: reproduced on 6.1.6, 7.0.3, and current main (92f22095, v7.1.0-preview3-43). The test output above is from a source build of main.
.NET target: .NET 10.0 (the test also compiles for net462; I have not run it there)
SQL Server version: SQL Server 2022 (RTM-CU26-GDR) 16.0.4275.2, local, over TCP. Also reproduced against LocalDB 17.0.4025.3.
Operating system: Windows 11
Additional context
Relevant source on main:
SqlConnectionInternal.cs:421— the ctor takes_parserLock.Wait(canReleaseFromAnyThread: false)and holds it for the whole login (released at:471). With that flag,SyncAsyncLock.Wait(:4302) keepsMonitor.Enter(_semaphore)held — that is theSemaphoreSlimin thesyncblkoutput.SqlConnectionInternal.cs:2273—CompleteLogin(!ConnectionOptions.Pooling), and inside,if (enlistOK && ConnectionOptions.Enlist && RoutingInfo == null) { ... Enlist(tx); }. This is whyPooling=falseis the precondition.SqlDelegatedTransaction.Initialize():97runs theBeginround trip on the login thread — skipping the parser lock, sinceThreadHasParserLockForCloseis true for that thread — and does not takelock(connection). So from the momentEnlistPromotableSinglePhaseregisters the enlistment, another thread can takelock(connection).SqlDelegatedTransaction.cs:224—Rollbacktakeslock(connection), then:236callsExecuteTransaction, which readsThreadHasParserLockForClose. That property is scoped to the owning thread (_threadIdOwningParserLock == Thread.CurrentThread.ManagedThreadId,SqlConnectionInternal.cs:719), so the rolling-back thread does not see the login thread's claim and waits on the parser lock.
The window is therefore the whole Begin round trip inside Initialize, not a few instructions, which is why this reproduces in seconds rather than being a rare race.
I could not find a test in the repo that combines a cancellation token with an ambient transaction — TransactionTest.cs, TransactionEnlistmentTest.cs and DistributedTransactionTest.cs all cover pooled and non-pooled, local and distributed, but none of them cancels an open.
How this was found. The NServiceBus SQL Server transport polls its queue in QueuePeeker.Peek, which opens a connection with the receive cancellation token inside a TransactionScope. MessageReceiver.StopReceive cancels that token, so every endpoint shutdown cancels an in-flight open. Against non-pooled connection strings (which LocalDb-style test helpers hand out), endpoint shutdown intermittently never returns — the peek loop is deadlocked, so the host waits on it forever. That surfaced as CI builds hanging until the job timeout roughly once a week.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsBacklog
Activity
github-actions commentedon Sep 16, 2026
🔍 Triage Summary
Area\Asyncmain; long-standing lock-ordering issue, not a recent regressionAnalysis
This is a well-documented deadlock between
SqlConnectionInternal's parser lock andlock(connection)that occurs when a cancelledOpenAsynccontinuation races the ambientTransactionScope's rollback path (Pooling=falserequired, since auto-enlistment only runs inside the login on that path). The reporter distinguishes this from two previously fixed deadlocks (#1124/#1242 and #1800/#1801), which were bothlock(connection)→InternalTransaction, whereas this one islock(connection)→ parser lock racing parser lock →lock(connection). A stress-test repro with full stack traces andsyncblkoutput is included. Given this is a hard deadlock (process hang, no exception) affecting the login/enlistment path under a realistic and previously-observed production scenario (NServiceBus SQL transport), this warrants a P1 severity assessment.Next Steps
SqlConnectionInternal.EnlistNonNull/DbConnectionInternal.CleanupConnectionOnTransactionCompletion(parser-lock-held path) versusSqlDelegatedTransaction.Rollback/ExecuteTransaction2005(lock(connection)-held path), and align the lock acquisition order between the two — likely by moving theTransactionCompletedhandler invocation (or itsDetachTransactioncallback) outside the parser lock, consistent with how Fix | Fix deadlock in transaction (.NET Framework) #1242 and Release connection lock before signaling SinglePhaseCommit completion #1801 resolved the analogousInternalTransactiondeadlocks.TransactionCancelledOpenTeststress test is not CI-safe (up to 2 minutes runtime, poisons the test host on failure) — if incorporated, it should be marked with[ActiveIssue]or an equivalent trait to keep it out of normal CI runs, per the reporter's own caveat.OpenAsync/state-change deadlock pattern to confirm it is unrelated before starting the fix.mdaigle commentedon Sep 23, 2026
Thanks @SimonCropp, I've prioritized this and added it to our backlog.
SimonCropp commentedon Sep 24, 2026
@mdaigle thanks