Skip to content

Deadlock when a cancelled OpenAsync enlists in an ambient TransactionScope (Pooling=false) #4696

Open

Description

@SimonCropp

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. SqlConnectionInternal calls CompleteLogin(!ConnectionOptions.Pooling), and CompleteLogin only auto-enlists when that enlistOK is 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. CancelAfter rides 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 on Stopwatch for 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) keeps Monitor.Enter(_semaphore) held — that is the SemaphoreSlim in the syncblk output.
  • SqlConnectionInternal.cs:2273 — CompleteLogin(!ConnectionOptions.Pooling), and inside, if (enlistOK && ConnectionOptions.Enlist && RoutingInfo == null) { ... Enlist(tx); }. This is why Pooling=false is the precondition.
  • SqlDelegatedTransaction.Initialize():97 runs the Begin round trip on the login thread — skipping the parser lock, since ThreadHasParserLockForClose is true for that thread — and does not take lock(connection). So from the moment EnlistPromotableSinglePhase registers the enlistment, another thread can take lock(connection).
  • SqlDelegatedTransaction.cs:224 — Rollback takes lock(connection), then :236 calls ExecuteTransaction, which reads ThreadHasParserLockForClose. 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.

Activity

  1. github-actions commented on Sep 16, 2026

    @github-actions

    🔍 Triage Summary

    Check Result
    Issue type Bug
    Environment All required environment details provided for investigation
    Area Area\Async
    Duplicates None found (related but distinct: #1124/#1242, #1800/#1801 already cited by reporter; also potentially related: #4534)
    Regression Not indicated — reproduces on 6.1.6, 7.0.3, and current main; long-standing lock-ordering issue, not a recent regression

    Analysis

    This is a well-documented deadlock between SqlConnectionInternal's parser lock and lock(connection) that occurs when a cancelled OpenAsync continuation races the ambient TransactionScope's rollback path (Pooling=false required, 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 both lock(connection) → InternalTransaction, whereas this one is lock(connection) → parser lock racing parser lock → lock(connection). A stress-test repro with full stack traces and syncblk output 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

    Note: This triage summary is auto-generated by an AI agent. The analysis and suggestions above have not been verified by a human maintainer. Please treat as preliminary guidance only.

    Generated by SqlClient Issue Auto-Triage for #4696 · copilot · auto · 60.3 AIC · ⌖ 13.1 AIC · ⊞ 11.9K · ◷

  2. added
    Area\Connection Pooling
    and removed
    Area\Connection Pooling
    on Sep 21, 2026
  3. moved this from To triage to Backlog in SqlClient Boardon Sep 23, 2026
  4. added
    Area\Connectivity
    on Sep 23, 2026
  5. mdaigle commented on Sep 23, 2026

    @mdaigle
    Contributor

    Thanks @SimonCropp, I've prioritized this and added it to our backlog.

  6. SimonCropp commented on Sep 24, 2026

    @SimonCropp
    ContributorAuthor

    @mdaigle thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area\Connectivity

    Type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions