Repository navigation
Description
How this was found
This was found while investigating Linux CI failures on #4335 (Re-issue session isolation level on TransactionScope re-enlistment):
- Tests opening connections sequentially inside a
TransactionScopefailed on the secondOpen()with an unexpected DTC promotion (EnlistNonNull -> GetExportCookie), instead of reusing the transaction-bound connection. - One failing case used ReadCommitted, which skips Re-issue session isolation level on TransactionScope re-enlistment #4335's new isolation-level SQL, so that PR's change could not explain the promotion.
- Tracing the "second open gets a different physical connection" symptom led to pool pruning: a pool with
Count == 0but a physical connection still being created was retired, stranding the first connection in a dead pool. - The CI logs did not capture pruning directly. The deterministic repro below establishes the defect independently; its role in those specific CI runs is inferred.
Describe the bug
Pool-group pruning treats !pool.ErrorOccurred && pool.Count == 0 as evidence that a pool is idle. However, physical connection creation can already be in flight before the connection is published to the pool's counted inventory. Pruning can remove and shut down that pool while the admitted creation subsequently completes successfully.
Inside a TransactionScope, this can strand the first physical connection in the retired pool. A later sequential open uses a replacement pool/physical connection instead of reusing the transaction-bound connection, causing an unexpected attempt to promote the transaction to DTC.
This is not exclusive to 7.1 or pool V2. A deterministic injection reproduces it with the released 6.1.0 and 6.1.7 NuGet packages, V1 (WaitHandleDbConnectionPool), on both sync and async paths. Each uninjected control completes three opens on the same SPID without promotion. The injected runs retire the zero-count pool during the first physical creation; the first open succeeds, and the second attempts promotion.
| Driver | Pool | Sync control | Async control | Sync forced prune | Async forced prune |
|---|---|---|---|---|---|
| 6.1.0 | V1, concrete type verified | Pass, stable SPID | Pass, stable SPID | Reproduced, second-open promotion | Reproduced, second-open promotion |
| 6.1.7 | V1, concrete type verified | Pass, stable SPID | Pass, stable SPID | Reproduced, second-open promotion | Reproduced, second-open promotion |
Representative observation on both released versions:
Creation hook: pool=Microsoft.Data.SqlClient.ConnectionPool.WaitHandleDbConnectionPool; Count=0; IsRunning=True
After prune: Count=0; IsRunning=False
Open 1: SPID=54; distributed=False
SQL Server version: 16.0.1200.5
Failure on open 2: System.NotSupportedException; hook hits=1
Windows reproduction leaves implicit distributed transactions disabled to make unintended promotion observable; enabling DTC is not the proposed fix. Representative full sync exception stack (local source path removed):
System.NotSupportedException: Implicit distributed transactions have not been enabled. If you're intentionally starting a distributed transaction, set TransactionManager.ImplicitDistributedTransactions to true.
at System.Transactions.DtcProxyShim.DtcProxyShimFactory.ConnectToProxy(String nodeName, Guid resourceManagerIdentifier, Object managedIdentifier, Boolean& nodeNameMatches, Byte[]& whereabouts, ResourceManagerShim& resourceManagerShim)
at System.Transactions.Oletx.DtcTransactionManager.Initialize()
at System.Transactions.Oletx.DtcTransactionManager.get_ProxyShimFactory()
at System.Transactions.TransactionInterop.GetOletxTransactionFromTransmitterPropagationToken(Byte[] propagationToken)
at System.Transactions.TransactionStatePSPEOperation.PSPEPromote(InternalTransaction tx)
at System.Transactions.TransactionStateDelegatedBase.EnterState(InternalTransaction tx)
at System.Transactions.EnlistableStates.Promote(InternalTransaction tx)
at System.Transactions.Transaction.Promote()
at System.Transactions.TransactionInterop.ConvertToOletxTransaction(Transaction transaction)
at System.Transactions.TransactionInterop.GetExportCookie(Transaction transaction, Byte[] whereabouts)
at Microsoft.Data.SqlClient.SqlInternalConnection.GetTransactionCookie(Transaction transaction, Byte[] whereAbouts)
at Microsoft.Data.SqlClient.SqlInternalConnection.EnlistNonNull(Transaction tx)
at Microsoft.Data.SqlClient.SqlInternalConnection.Enlist(Transaction tx)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.Activate(Transaction transaction)
at Microsoft.Data.ProviderBase.DbConnectionInternal.ActivateConnection(Transaction transaction)
at Microsoft.Data.SqlClient.ConnectionPool.WaitHandleDbConnectionPool.PrepareConnection(DbConnection owningObject, DbConnectionInternal obj, Transaction transaction)
at Microsoft.Data.SqlClient.ConnectionPool.WaitHandleDbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at Microsoft.Data.SqlClient.ConnectionPool.WaitHandleDbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 taskCompletionSource, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry, SqlConnectionOverrides overrides)
at Microsoft.Data.SqlClient.SqlConnection.Open(SqlConnectionOverrides overrides)
at Microsoft.Data.SqlClient.SqlConnection.Open()
at Program.<Main>$(String[] args)
The async case reaches the same promotion chain through WaitHandleDbConnectionPool.WaitForPendingOpen.
To reproduce
This is a deterministic forced-interleaving repro, not a claim about how often the natural timer hits this window. An EventListener invokes the real factory pruning callback exactly at the physical-create trace, before the pool publishes its count. The control listens at the same boundary but does not prune. No driver binaries are modified. The harness checks the concrete pool type/output, zero-count running state, post-prune retirement, first-open success, second-open promotion stack, and callback execution. Callback errors are surfaced rather than swallowed by EventListener.
Create an isolated console project using these two files. Supply a working SQL Server connection string directly via the DOTNET_SQLCLIENT_TEST_CONNECTIONSTRING environment variable; do not put credentials in source. The local repro uses TrustServerCertificate=true only within this test process for a development certificate.
HistoricalPruning.csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<SqlClientVersion Condition="'$(SqlClientVersion)' == ''">6.1.7</SqlClientVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Data.SqlClient" Version="$(SqlClientVersion)" />
</ItemGroup>
</Project>Program.cs (complete Windows repro):
using System.Collections;
using System.Diagnostics.Tracing;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Transactions;
using Microsoft.Data.SqlClient;
if (args.Length != 2 || (args[0] != "sync" && args[0] != "async") ||
(args[1] != "control" && args[1] != "inject"))
{
Console.Error.WriteLine("Usage: HistoricalPruning <sync|async> <control|inject>");
return 2;
}
bool asynchronous = args[0] == "async";
bool inject = args[1] == "inject";
AppContext.SetSwitch("Switch.Microsoft.Data.SqlClient.UseConnectionPoolV2", false);
if (OperatingSystem.IsWindows())
TransactionManager.ImplicitDistributedTransactions = false;
var builder = new SqlConnectionStringBuilder(
Environment.GetEnvironmentVariable("DOTNET_SQLCLIENT_TEST_CONNECTIONSTRING")
?? throw new InvalidOperationException("Set DOTNET_SQLCLIENT_TEST_CONNECTIONSTRING directly in the environment."))
{
Pooling = true,
MinPoolSize = 0,
MaxPoolSize = 1,
Enlist = true,
ConnectTimeout = 15,
// Only this standalone process trusts the local SQL development certificate.
TrustServerCertificate = true,
ApplicationName = "HistoricalPruning-" + Guid.NewGuid().ToString("N")
};
Console.WriteLine($"Driver: {typeof(SqlConnection).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion}");
Console.WriteLine($"Runtime: {RuntimeInformation.FrameworkDescription}; OS: {RuntimeInformation.OSDescription}");
Console.WriteLine($"Mode: {args[0]}/{args[1]}; V2=false; implicit DTC=false");
using var listener = new PruningListener(inject);
int attempt = 0;
int? sessionId = null;
try
{
using var scope = new TransactionScope(TransactionScopeOption.RequiresNew,
new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted },
TransactionScopeAsyncFlowOption.Enabled);
listener.Arm();
for (attempt = 1; attempt <= 3; attempt++)
{
using var connection = new SqlConnection(builder.ConnectionString);
if (asynchronous)
await connection.OpenAsync();
else
connection.Open();
listener.ThrowIfFailed();
using var command = new SqlCommand("SELECT CAST(@@SPID AS int)", connection);
int current = Convert.ToInt32(asynchronous ? await command.ExecuteScalarAsync() : command.ExecuteScalar());
Console.WriteLine($"Open {attempt}: SPID={current}; distributed={Transaction.Current!.TransactionInformation.DistributedIdentifier != Guid.Empty}");
sessionId ??= current;
if (current != sessionId || Transaction.Current!.TransactionInformation.DistributedIdentifier != Guid.Empty)
throw new InvalidOperationException("Session reuse or transaction affinity changed.");
if (attempt == 1)
{
command.CommandText = "SELECT CAST(SERVERPROPERTY('ProductVersion') AS varchar(50))";
Console.WriteLine($"SQL Server version: {command.ExecuteScalar()}");
}
}
scope.Complete();
if (listener.Hits != 1)
throw new InvalidOperationException($"Expected one creation hook, got {listener.Hits}.");
Console.WriteLine(inject ? "NOT REPRODUCED: injected case retained the session." : "CONTROL PASS: all three opens reused the session.");
return inject ? 3 : 0;
}
catch (Exception exception)
{
listener.ThrowIfFailed();
bool promotion = exception is NotSupportedException &&
exception.Message.Contains("Implicit distributed transactions") &&
exception.StackTrace?.Contains("GetExportCookie") == true;
Console.WriteLine($"Failure on open {attempt}: {exception.GetType().FullName}; hook hits={listener.Hits}");
// Do not print arbitrary SQL/network exception messages or event payloads.
if (promotion)
Console.WriteLine(exception.Message);
Console.WriteLine(exception.StackTrace);
if (inject && attempt == 2 && listener.Hits == 1 && listener.Retired && promotion)
{
Console.WriteLine("REPRODUCED: active zero-count V1 pool retired; second open attempted DTC promotion.");
return 0;
}
Console.WriteLine("UNEXPECTED FAILURE: not accepted as reproduction evidence.");
return 1;
}
sealed class PruningListener(bool inject) : EventListener
{
private int _armed;
private Exception? _failure;
internal int Hits { get; private set; }
internal bool Retired { get; private set; }
internal void Arm() => Volatile.Write(ref _armed, 1);
internal void ThrowIfFailed()
{
if (_failure is not null)
throw new InvalidOperationException("Pruning injection failed.", _failure);
}
protected override void OnEventSourceCreated(EventSource source)
{
if (source.Name == "Microsoft.Data.SqlClient.EventSource")
EnableEvents(source, EventLevel.Verbose, EventKeywords.All);
}
protected override void OnEventWritten(EventWrittenEventArgs data)
{
if (Volatile.Read(ref _armed) == 0 || data.Payload is null ||
!data.Payload.OfType<string>().Any(value =>
value.Contains("<prov.DbConnectionFactory.CreatePooledConnection|") ||
value.Contains("<prov.SqlConnectionFactory.CreatePooledConnection|")) ||
Interlocked.Exchange(ref _armed, 0) == 0)
return;
try
{
Hits++;
Type type = typeof(SqlConnection).Assembly.GetType("Microsoft.Data.SqlClient.SqlConnectionFactory", true)!;
object factory = type.GetField("SingletonInstance", BindingFlags.Public | BindingFlags.Static)?.GetValue(null)
?? type.GetProperty("Instance", BindingFlags.NonPublic | BindingFlags.Static)?.GetValue(null)
?? throw new MissingMemberException(type.FullName, "SingletonInstance/Instance");
var groups = (IEnumerable)FindField(type, "_connectionPoolGroups").GetValue(factory)!;
var pools = new List<object>();
foreach (object entry in groups)
{
object group = entry.GetType().GetProperty("Value")!.GetValue(entry)!;
var collection = (IEnumerable)FindField(group.GetType(), "_poolCollection").GetValue(group)!;
foreach (object poolEntry in collection)
pools.Add(poolEntry.GetType().GetProperty("Value")!.GetValue(poolEntry)!);
}
if (pools.Count != 1)
throw new InvalidOperationException($"Expected one pool, got {pools.Count}.");
object pool = pools[0];
Type poolType = pool.GetType();
object? Read(string name) => poolType.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)!.GetValue(pool);
Console.WriteLine($"Creation hook: pool={poolType.FullName}; Count={Read("Count")}; IsRunning={Read("IsRunning")}");
if (Convert.ToInt32(Read("Count")) != 0 || !Convert.ToBoolean(Read("IsRunning")))
throw new InvalidOperationException("Did not reach the active zero-count window.");
if (inject)
{
MethodInfo? prune = null;
for (Type? current = type; current is not null && prune is null; current = current.BaseType)
prune = current.GetMethod("RunPruningPass", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
?? current.GetMethod("PruneConnectionPoolGroups", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
if (prune is null)
throw new MissingMethodException("No factory pruning callback found.");
prune.Invoke(factory, prune.GetParameters().Length == 0 ? null : new object?[] { null });
Retired = !Convert.ToBoolean(Read("IsRunning"));
Console.WriteLine($"After prune: Count={Read("Count")}; IsRunning={Read("IsRunning")}");
}
}
catch (Exception exception)
{
_failure = exception;
}
}
private static FieldInfo FindField(Type type, string name)
{
for (Type? current = type; current is not null; current = current.BaseType)
if (current.GetField(name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly) is { } field)
return field;
throw new MissingFieldException(type.FullName, name);
}
}Run from the isolated project directory, with the connection-string environment variable already set:
dotnet build -p:SqlClientVersion=6.1.0
dotnet .\bin\Debug\net8.0\HistoricalPruning.dll sync control
dotnet .\bin\Debug\net8.0\HistoricalPruning.dll sync inject
dotnet .\bin\Debug\net8.0\HistoricalPruning.dll async control
dotnet .\bin\Debug\net8.0\HistoricalPruning.dll async inject
# Repeat all four commands after:
dotnet build -p:SqlClientVersion=6.1.7Exit zero means the requested control passed or the injected defect was positively reproduced; inspect CONTROL PASS versus REPRODUCED in the output. It does not mean the injected driver behavior is correct. Other failures are rejected as reproduction evidence.
Expected behavior
Pruning must distinguish a genuinely idle empty pool from one with admitted acquisition/creation work and atomically exclude new admission during retirement. Repeated sequential opens in this transaction should preserve physical-session reuse rather than promote because cleanup retired an active pool. Explicit user-requested ClearPool/ClearAllPools is a separate lifecycle case.
Further technical details
- Microsoft.Data.SqlClient released packages: 6.1.0 (
1af7327454f9cafbf3aaaa8b3d615489aad480ab) and 6.1.7 (efca28cabb8d13fe0b0afd277bf6ff66eb8231e5). These are loaded assembly informational versions, not source rebuilds. - .NET target:
net8.0; runtime.NET 8.0.31. - SQL Server: SQL Server 2022,
16.0.1200.5. - OS: Windows,
10.0.26200. - Pool: V1 explicitly selected; runtime type confirmed as
Microsoft.Data.SqlClient.ConnectionPool.WaitHandleDbConnectionPool. - Transaction: ReadCommitted, async flow enabled, three sequential opens;
Max Pool Size=1,Min Pool Size=0, unique application name. - No SQL service/settings changes. Credentials are environment-only and not logged; no trace payloads are stored.
Additional context
- Proposed standalone fix: Fix active connection pools being retired during creation #4754. On unchanged
main(d189eeb7), four deterministic unit cases also reproduce retirement across both V1/V2 and sync/async. With the fix, pool/factory suites pass 435 tests on each of net462/net8/net9/net10; SQL regression tests pass four cases each on net8/net10 with stable SPID and no DTC promotion. - How this was found: see How this was found at the top (Re-issue session isolation level on TransactionScope re-enlistment #4335 Linux CI investigation; link to those runs is inferred, not observed).
- Related but distinct from [7.1] 7.1.0 regression: in-flight OpenAsync fails instantly with pool "Timeout expired" when ClearAllPools()/ClearPool() runs #4737: that report demonstrates a 7.1-specific async timeout after explicit ClearAllPools/Shutdown. This report demonstrates automatic-pruning eligibility retiring active creation and losing transaction affinity, already present in 6.1.0. The older-version evidence does not downgrade or disprove [7.1] 7.1.0 regression: in-flight OpenAsync fails instantly with pool "Timeout expired" when ClearAllPools()/ClearPool() runs #4737's separate regression.
- Earliest affected release and natural-timer frequency have not been established; 6.1.0 and 6.1.7 are confirmed affected.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
github-actions commentedon Sep 25, 2026
🔍 Triage Summary
Area\Connection PoolingWaitHandleDbConnectionPool), and states it is not exclusive to 7.1 or pool V2Analysis
This report describes a race between pool-group pruning and physical connection creation: pruning treats
!pool.ErrorOccurred && pool.Count == 0as sufficient evidence of an idle pool, but an admitted connection creation can be in flight before it is published to the pool's counted inventory. If pruning retires the pool during that window, aTransactionScope-enlisted connection can be stranded, causing a subsequent sequential open to use a different pool/physical connection and unexpectedly attempt DTC promotion (NotSupportedException: Implicit distributed transactions have not been enabled). The report includes a deterministic, instrumented reproduction (EventListener-based injection) affectingMicrosoft.Data.SqlClient.ConnectionPool.WaitHandleDbConnectionPool(V1) on both sync and async paths, and states the same defect reproduces on V2. A fix is already proposed in linked PR #4754, with reported passing pool/factory suites (435 tests) across net462/net8/net9/net10 and passing SQL regression tests. Given this affects transaction correctness/session affinity under pooling+TransactionScope and has a documented fix, this is a P1 — correctness bug with real-world impact on distributed-transaction promotion, well-diagnosed and already has a proposed remediation.Next Steps
WaitHandleDbConnectionPool(V1) and the channel-based V2 pool) and to confirm the added regression tests cover both sync and async paths as described.ClearAllPools/Shutdown) and references Re-issue session isolation level on TransactionScope re-enlistment #4335 (Linux CI failures under investigation). These should be reviewed together for shared root cause in pruning/pool-lifecycle code, but treated as separate defects per the reporter's own analysis.