From 988320711f632e5a61457a6ee591500f4b4042bf Mon Sep 17 00:00:00 2001
From: Rocco Panunzio <222559735+RoccoPanunzio@users.noreply.github.com>
Date: Sat, 14 Nov 2026 09:17:08 +0100
Subject: [PATCH 1/2] Don't wait in SniTcpHandle.CheckConnection
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
The liveness check polled the socket with a 100 µs timeout. On a healthy,
idle connection the poll waits the whole timeout, and Windows rounds it up
to the system timer tick (15.6 ms by default), so every open from the pool
over TCP with the managed network layer cost about 15 ms once the
connection had been idle longer than CheckConnectionWindow.
A connection closed by the peer is already readable, so a zero timeout
detects it just the same; SelectRead and the Available check stay as they
were for Linux.
---
.../ManagedSni/SniTcpHandle.netcore.cs | 6 +-
.../SqlClient/ManagedSni/SniTcpHandleTests.cs | 122 ++++++++++++++++++
2 files changed, 127 insertions(+), 1 deletion(-)
create mode 100644 src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandleTests.cs
diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs
index ef8e10256a..73e6b3a19c 100644
--- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs
+++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs
@@ -1089,7 +1089,11 @@ public override uint CheckConnection()
// Since _socket.Connected alone doesn't guarantee if the connection is still active, we use it in
// combination with _socket.Poll method and _socket.Available == 0 check. When both of them
// return true we can safely determine that the connection is no longer active.
- if (!_socket.Connected || (_socket.Poll(100, SelectMode.SelectRead) && _socket.Available == 0))
+ //
+ // The poll does not wait: a closed connection is already readable, so waiting adds nothing.
+ // Any positive timeout is rounded up to the system timer tick on Windows (15.6 ms by default),
+ // which this check would cost on every connection taken from the pool.
+ if (!_socket.Connected || (_socket.Poll(0, SelectMode.SelectRead) && _socket.Available == 0))
{
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, Socket not usable.", args0: _connectionId);
return TdsEnums.SNI_ERROR;
diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandleTests.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandleTests.cs
new file mode 100644
index 0000000000..5c2232f194
--- /dev/null
+++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandleTests.cs
@@ -0,0 +1,122 @@
+// 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.
+
+#if NET
+
+using System;
+using System.Diagnostics;
+using System.Net;
+using System.Net.Sockets;
+using System.Threading;
+using Microsoft.Data.ProviderBase;
+using Microsoft.Data.SqlClient.ManagedSni;
+using Microsoft.Data.SqlClient.Parser;
+using Xunit;
+
+namespace Microsoft.Data.SqlClient.UnitTests.ManagedSni
+{
+ ///
+ /// Covers the liveness check of a managed TCP handle, run on every connection taken from the pool.
+ ///
+ public sealed class SniTcpHandleTests
+ {
+ ///
+ /// The check on an open, idle connection succeeds without waiting. A positive poll timeout is
+ /// rounded up to the timer tick on Windows (15.6 ms by default), so twenty checks that waited
+ /// would take about 300 ms instead of well under the bound.
+ ///
+ [Fact]
+ public void CheckConnection_IdleOpenConnection_ReturnsSuccessWithoutWaiting()
+ {
+ // Arrange
+ using LocalConnection connection = new();
+ const int Checks = 20;
+ uint[] results = new uint[Checks];
+
+ // Act
+ Stopwatch stopwatch = Stopwatch.StartNew();
+ for (int i = 0; i < Checks; i++)
+ {
+ results[i] = connection.Handle.CheckConnection();
+ }
+ stopwatch.Stop();
+
+ // Assert
+ Assert.All(results, result => Assert.Equal(TdsEnums.SNI_SUCCESS, result));
+ Assert.True(
+ stopwatch.ElapsedMilliseconds < 100,
+ $"{Checks} checks took {stopwatch.ElapsedMilliseconds} ms.");
+ }
+
+ ///
+ /// The check reports a connection the peer has closed, so the pool discards it instead of
+ /// handing it out. The peer's close reaches the client asynchronously, so the check is repeated
+ /// until it fails or a deadline passes.
+ ///
+ [Fact]
+ public void CheckConnection_PeerClosed_ReturnsError()
+ {
+ // Arrange
+ using LocalConnection connection = new();
+ connection.Peer.Close();
+
+ // Act
+ uint result = TdsEnums.SNI_SUCCESS;
+ Stopwatch deadline = Stopwatch.StartNew();
+ while (result == TdsEnums.SNI_SUCCESS && deadline.Elapsed < TimeSpan.FromSeconds(5))
+ {
+ result = connection.Handle.CheckConnection();
+ if (result == TdsEnums.SNI_SUCCESS)
+ {
+ Thread.Sleep(10);
+ }
+ }
+
+ // Assert
+ Assert.Equal(TdsEnums.SNI_ERROR, result);
+ }
+
+ ///
+ /// Opens a managed TCP handle to a local listener and owns both ends.
+ ///
+ private sealed class LocalConnection : IDisposable
+ {
+ public SniTcpHandle Handle { get; }
+
+ public Socket Peer { get; }
+
+ public LocalConnection()
+ {
+ using TcpListener listener = new(IPAddress.Loopback, 0);
+ listener.Start();
+ SQLDNSInfo? pendingDnsInfo = null;
+ Handle = new SniTcpHandle(
+ IPAddress.Loopback.ToString(),
+ ((IPEndPoint)listener.LocalEndpoint).Port,
+ TimeoutTimer.StartNew(TimeSpan.FromSeconds(5)),
+ parallel: false,
+ SqlConnectionIPAddressPreference.IPv4First,
+ cachedFQDN: nameof(SniTcpHandleTests),
+ ref pendingDnsInfo,
+ tlsFirst: false,
+ hostNameInCertificate: null,
+ serverCertificateFilename: null);
+ using CancellationTokenSource timeout = new(TimeSpan.FromSeconds(5));
+ Peer = listener.AcceptSocketAsync(timeout.Token).AsTask().GetAwaiter().GetResult();
+ Assert.Equal(TdsEnums.SNI_SUCCESS, Handle.Status);
+ }
+
+ ///
+ /// Closes the client handle and the accepted socket.
+ ///
+ public void Dispose()
+ {
+ Handle.Dispose();
+ Peer.Dispose();
+ }
+ }
+ }
+}
+
+#endif
From 51098c5655ffbb7a4283249cd55a49bcfe3fe4d7 Mon Sep 17 00:00:00 2001
From: Rocco Panunzio <222559735+RoccoPanunzio@users.noreply.github.com>
Date: Mon, 16 Nov 2026 20:25:46 +0100
Subject: [PATCH 2/2] Measure an idle pooled checkout as a benchmark instead of
a unit test
The liveness probe runs only on a connection that has been idle for more
than 5 ms, and a successful probe restarts that window, so the churn
runner probes at most one checkout in every 5 ms and averages its cost
away. ConnectionPoolIdleCheckoutRunner leaves a one-connection pool idle
for 10 ms outside the measurement, then times a single open, sync and
async, so every measured checkout pays for the probe. With managed SNI on
Windows it reads about 13.5 ms per checkout with Poll(100) and about
0.2 ms with Poll(0).
The timing assertion leaves the unit tests, which keep the peer-closed case.
---
.../ConnectionPoolIdleCheckoutRunner.cs | 91 +++++++++++++++++++
.../tests/PerformanceTests/Config/Config.cs | 1 +
.../tests/PerformanceTests/Program.cs | 1 +
.../runnerconfig.default.jsonc | 10 ++
.../SqlClient/ManagedSni/SniTcpHandleTests.cs | 28 ------
5 files changed, 103 insertions(+), 28 deletions(-)
create mode 100644 src/Microsoft.Data.SqlClient/tests/PerformanceTests/BenchmarkRunners/ConnectionPoolIdleCheckoutRunner.cs
diff --git a/src/Microsoft.Data.SqlClient/tests/PerformanceTests/BenchmarkRunners/ConnectionPoolIdleCheckoutRunner.cs b/src/Microsoft.Data.SqlClient/tests/PerformanceTests/BenchmarkRunners/ConnectionPoolIdleCheckoutRunner.cs
new file mode 100644
index 0000000000..637cc8d061
--- /dev/null
+++ b/src/Microsoft.Data.SqlClient/tests/PerformanceTests/BenchmarkRunners/ConnectionPoolIdleCheckoutRunner.cs
@@ -0,0 +1,91 @@
+// 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.Threading;
+using System.Threading.Tasks;
+using BenchmarkDotNet.Attributes;
+
+namespace Microsoft.Data.SqlClient.PerformanceTests
+{
+ ///
+ /// Measures one checkout of a connection that has sat idle in the pool long enough to be
+ /// probed for liveness before it is handed out.
+ ///
+ /// The pool skips the liveness probe for a connection that did I/O or passed a probe within
+ /// the last 5 ms (TdsParserStateObject.CheckConnectionWindow). In the rapid open/close
+ /// loop of at most one checkout in every 5 ms is
+ /// probed, and its cost is averaged over the rest. Here every iteration waits past that window
+ /// outside the measurement, then times a single open, so every measured checkout pays for the
+ /// probe. Under managed SNI the probe is
+ /// SniTcpHandle.CheckConnection, whose socket poll must not wait: Windows rounds any
+ /// positive poll timeout up to the timer tick, about 15 ms by default.
+ ///
+ /// The pool holds a single connection, so every iteration probes the same idle socket. Set
+ /// UseManagedSniOnWindows to measure the managed probe on Windows; on other operating
+ /// systems the managed implementation is the only one.
+ ///
+ /// Related issue: #5070
+ ///
+ public class ConnectionPoolIdleCheckoutRunner : BaseRunner
+ {
+ ///
+ /// How long the connection sits idle before each measured checkout: twice the 5 ms window,
+ /// so clock granularity cannot leave it inside the window.
+ ///
+ private static readonly TimeSpan s_idleTime = TimeSpan.FromMilliseconds(10);
+
+ private string _connectionString;
+
+ [GlobalSetup]
+ public void Setup()
+ {
+ var builder = new SqlConnectionStringBuilder(s_config.ConnectionString)
+ {
+ Pooling = true,
+ // One connection, kept open, so each checkout probes the same idle socket rather
+ // than opening a new physical connection.
+ MinPoolSize = 1,
+ MaxPoolSize = 1
+ };
+ _connectionString = builder.ConnectionString;
+
+ // Opened and released before measurement, so no measured open is a physical connect.
+ using var conn = new SqlConnection(_connectionString);
+ conn.Open();
+ }
+
+ ///
+ /// Leaves the pooled connection idle past the liveness window, outside the measurement.
+ ///
+ [IterationSetup]
+ public void IterationSetup()
+ {
+ Thread.Sleep(s_idleTime);
+ }
+
+ [GlobalCleanup]
+ public void Cleanup()
+ {
+ using var conn = new SqlConnection(_connectionString);
+ SqlConnection.ClearPool(conn);
+ }
+
+ [Benchmark]
+ public void OpenIdlePooledConnection()
+ {
+ using var conn = new SqlConnection(_connectionString);
+ conn.Open();
+ // Dispose returns the connection to the pool.
+ }
+
+ [Benchmark]
+ public async Task OpenIdlePooledConnectionAsync()
+ {
+ await using var conn = new SqlConnection(_connectionString);
+ await conn.OpenAsync();
+ // Dispose returns the connection to the pool.
+ }
+ }
+}
diff --git a/src/Microsoft.Data.SqlClient/tests/PerformanceTests/Config/Config.cs b/src/Microsoft.Data.SqlClient/tests/PerformanceTests/Config/Config.cs
index 6bf99f9f0f..1a2f41f967 100644
--- a/src/Microsoft.Data.SqlClient/tests/PerformanceTests/Config/Config.cs
+++ b/src/Microsoft.Data.SqlClient/tests/PerformanceTests/Config/Config.cs
@@ -74,6 +74,7 @@ public class Benchmarks
public RunnerJob ConnectionPoolStressRunnerConfig;
public RunnerJob ConnectionPoolContentionRunnerConfig;
public RunnerJob ConnectionPoolChurnRunnerConfig;
+ public RunnerJob ConnectionPoolIdleCheckoutRunnerConfig;
public RunnerJob ConnectionPoolRampRunnerConfig;
public RunnerJob ConnectionPoolThreadPoolPressureRunnerConfig;
}
diff --git a/src/Microsoft.Data.SqlClient/tests/PerformanceTests/Program.cs b/src/Microsoft.Data.SqlClient/tests/PerformanceTests/Program.cs
index 53533374a7..3ab019fc85 100644
--- a/src/Microsoft.Data.SqlClient/tests/PerformanceTests/Program.cs
+++ b/src/Microsoft.Data.SqlClient/tests/PerformanceTests/Program.cs
@@ -60,6 +60,7 @@ public BenchmarkUnit(string name, Func selector, Type run
new BenchmarkUnit("ConnectionPoolStress", b => b.ConnectionPoolStressRunnerConfig, typeof(ConnectionPoolStressRunner)),
new BenchmarkUnit("ConnectionPoolContention", b => b.ConnectionPoolContentionRunnerConfig, typeof(ConnectionPoolContentionRunner)),
new BenchmarkUnit("ConnectionPoolChurn", b => b.ConnectionPoolChurnRunnerConfig, typeof(ConnectionPoolChurnRunner)),
+ new BenchmarkUnit("ConnectionPoolIdleCheckout", b => b.ConnectionPoolIdleCheckoutRunnerConfig, typeof(ConnectionPoolIdleCheckoutRunner)),
new BenchmarkUnit("ConnectionPoolRamp", b => b.ConnectionPoolRampRunnerConfig, typeof(ConnectionPoolRampRunner)),
new BenchmarkUnit("ConnectionPoolThreadPoolPressure", b => b.ConnectionPoolThreadPoolPressureRunnerConfig, typeof(ConnectionPoolThreadPoolPressureRunner)),
};
diff --git a/src/Microsoft.Data.SqlClient/tests/PerformanceTests/runnerconfig.default.jsonc b/src/Microsoft.Data.SqlClient/tests/PerformanceTests/runnerconfig.default.jsonc
index d7bb3cf5a0..8ddb244a8a 100644
--- a/src/Microsoft.Data.SqlClient/tests/PerformanceTests/runnerconfig.default.jsonc
+++ b/src/Microsoft.Data.SqlClient/tests/PerformanceTests/runnerconfig.default.jsonc
@@ -181,6 +181,16 @@
"WarmupCount": 1,
"RowCount": 0
},
+ // Each iteration times a single checkout, so it needs more iterations than the others
+ // for a stable median.
+ "ConnectionPoolIdleCheckoutRunnerConfig": {
+ "Enabled": true,
+ "LaunchCount": 1,
+ "IterationCount": 50,
+ "InvocationCount": 1,
+ "WarmupCount": 1,
+ "RowCount": 0
+ },
"ConnectionPoolRampRunnerConfig": {
"Enabled": true,
"LaunchCount": 1,
diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandleTests.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandleTests.cs
index 5c2232f194..22f4d2f54b 100644
--- a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandleTests.cs
+++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandleTests.cs
@@ -21,34 +21,6 @@ namespace Microsoft.Data.SqlClient.UnitTests.ManagedSni
///
public sealed class SniTcpHandleTests
{
- ///
- /// The check on an open, idle connection succeeds without waiting. A positive poll timeout is
- /// rounded up to the timer tick on Windows (15.6 ms by default), so twenty checks that waited
- /// would take about 300 ms instead of well under the bound.
- ///
- [Fact]
- public void CheckConnection_IdleOpenConnection_ReturnsSuccessWithoutWaiting()
- {
- // Arrange
- using LocalConnection connection = new();
- const int Checks = 20;
- uint[] results = new uint[Checks];
-
- // Act
- Stopwatch stopwatch = Stopwatch.StartNew();
- for (int i = 0; i < Checks; i++)
- {
- results[i] = connection.Handle.CheckConnection();
- }
- stopwatch.Stop();
-
- // Assert
- Assert.All(results, result => Assert.Equal(TdsEnums.SNI_SUCCESS, result));
- Assert.True(
- stopwatch.ElapsedMilliseconds < 100,
- $"{Checks} checks took {stopwatch.ElapsedMilliseconds} ms.");
- }
-
///
/// The check reports a connection the peer has closed, so the pool discards it instead of
/// handing it out. The peer's close reaches the client asynchronously, so the check is repeated