Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .github/instructions/features.instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -396,8 +396,21 @@ AppContext switches allow runtime behavior changes without modifying connection
| `Switch.Microsoft.Data.SqlClient.UseCompatibilityProcessSni` | `false` | Uses legacy SNI processing path |
| `Switch.Microsoft.Data.SqlClient.UseConnectionPoolV2` | `false` | Enables the new `ChannelDbConnectionPool` implementation |
| `Switch.Microsoft.Data.SqlClient.UseManagedNetworkingOnWindows` | `false` | Forces managed SNI on Windows (instead of native SNI) |
| `Switch.Microsoft.Data.SqlClient.UseOverallConnectTimeoutForPoolWait` | `true` | Counts pool waits against the caller's `Connect Timeout` budget for `Open` and `OpenAsync`; set to `false` to restore separate pool-wait and login budgets |
| `Switch.Microsoft.Data.SqlClient.UseOneSecFloorInTimeoutCalculationDuringLogin` | `false` | Sets 1-second minimum in login timeout calculations |

### Pool-wait timeout budget

`UseOverallConnectTimeoutForPoolWait` defaults to `true`. `SqlConnection.Open` and
`OpenAsync` propagate the caller's remaining `Connect Timeout` budget through pool
acquisition and login, for both pool implementations. Setting the switch to `false`
restores a fresh login timeout after pool acquisition; the legacy wait-handle pool
also starts a fresh pool-wait timeout. `Connect Timeout=0` remains infinite.

Set the switch before using SqlClient because its value is cached on first use.
See [Migrating connection networking defaults](../../doc/networking-defaults.md#pool-wait-timeout-budget)
for the compatibility opt-out example.

### Authentication configuration in app.config

The `SqlClientAuthenticationProviders` (modern) and `SqlAuthenticationProviders`
Expand Down
24 changes: 24 additions & 0 deletions doc/networking-defaults.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,27 @@ On modern .NET, TNIR remains unsupported.

See [SqlClient high availability and disaster recovery](https://learn.microsoft.com/sql/connect/ado-net/sql/sqlclient-support-high-availability-disaster-recovery)
for the supported connection strategies and their limitations.

## Pool-wait timeout budget

`Switch.Microsoft.Data.SqlClient.UseOverallConnectTimeoutForPoolWait` now defaults
to `true` on .NET Framework and modern .NET. `SqlConnection.Open` and `OpenAsync`
carry the caller's remaining `Connect Timeout` budget through pool acquisition and
login, for both pool implementations. Time spent waiting for the pool is deducted
from the budget available for physical connection creation instead of granting
login another full timeout. Applications that previously relied on those separate
budgets may now time out sooner under pool contention. `Connect Timeout=0` remains
infinite.

To restore the previous behavior, set the existing switch to `false` before using
SqlClient, because its value is cached on first use:

```csharp
AppContext.SetSwitch(
"Switch.Microsoft.Data.SqlClient.UseOverallConnectTimeoutForPoolWait", false);
```

With this compatibility opt-out, login starts a fresh `Connect Timeout` after pool
acquisition. The legacy wait-handle pool also uses its configured pool-wait timeout
rather than the caller's remaining budget; the channel pool continues to use the
caller's remaining budget for its internal waits.
Original file line number Diff line number Diff line change
Expand Up @@ -701,17 +701,17 @@ public static bool UseCompatibilityAsyncBehaviour
ref s_useLegacyIdleTimeoutBehavior);

/// <summary>
/// When set to true, pool operations count against the
/// When set to true (the default), pool operations count against the
/// caller's ConnectTimeout budget. This includes waits and async operations.
/// When false, pool operations receive a full ConnectTimeout and
/// network calls receive a further full ConnectTimeout.
/// When false, login receives a fresh ConnectTimeout after pool acquisition.
/// The legacy pool also starts a fresh pool-wait timeout.
///
/// The default value of this switch is false.
/// The default value of this switch is true.
/// </summary>
public static bool UseOverallConnectTimeoutForPoolWait =>
AcquireAndReturn(
UseOverallConnectTimeoutForPoolWaitString,
defaultValue: false,
defaultValue: true,
ref s_useOverallConnectTimeoutForPoolWait);

#if NET
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2563,30 +2563,71 @@ public async Task ConcurrentCallers_ShouldTimeoutIndependently()
/// <see cref="FakeTimeProvider"/> so the test does not depend on real
/// wall-clock waits or thread sleeps.
/// </remarks>
[Fact]
public void GetConnection_TimeoutTimerReflectsPoolWaitTime()
[Theory]
[InlineData(null)]
[InlineData(true)]
[InlineData(false)]
public void TryGetConnection_ConsumedBudget_ForwardsRemainingTime(bool? switchEnabled)
{
// Arrange: a capturing factory and a fake-time-backed timer with a
// 30-second budget anchored at virtual time t = 0.
// Arrange
using LocalAppContextSwitchesHelper switches = new()
{
UseOverallConnectTimeoutForPoolWait = switchEnabled,
};
var factory = new SuccessfulSqlConnectionFactory();
var pool = ConstructPool(factory);
var owner = new SqlConnection("Timeout=30");
using var owner = new SqlConnection("Timeout=30");
var fakeTime = new FakeTimeProvider();
TimeoutTimer timer = TimeoutTimer.StartNew(TimeSpan.FromSeconds(30), fakeTime);

// Act: advance virtual time by 5 seconds before invoking the pool,
// simulating budget that was consumed elsewhere (e.g., waiting on a
// pool slot) before the factory was called.
fakeTime.Advance(TimeSpan.FromSeconds(5));
pool.TryGetConnection(owner, taskCompletionSource: null, timer, out DbConnectionInternal? connection);

// Assert: factory received the same timer, and it reports the
// reduced 25-second remaining budget.
// Act
bool completed = pool.TryGetConnection(
owner, taskCompletionSource: null, timer, out DbConnectionInternal? connection);

// Assert
Assert.True(completed);
Assert.NotNull(connection);
Assert.Same(timer, factory.CapturedTimeout);
Assert.Equal(25_000, factory.CapturedTimeout!.MillisecondsRemainingInt);
}

/// <summary>
/// Ensures asynchronous acquisition forwards the remaining budget to physical creation
/// regardless of whether login will honor it or use the compatibility opt-out.
/// </summary>
[Theory]
[InlineData(null)]
[InlineData(true)]
[InlineData(false)]
public async Task TryGetConnectionAsync_ConsumedBudget_ForwardsRemainingTime(
bool? switchEnabled)
{
// Arrange
using LocalAppContextSwitchesHelper switches = new()
{
UseOverallConnectTimeoutForPoolWait = switchEnabled,
};
var factory = new SuccessfulSqlConnectionFactory();
var pool = ConstructPool(factory);
using var owner = new SqlConnection("Timeout=30");
var fakeTime = new FakeTimeProvider();
TimeoutTimer timer = TimeoutTimer.StartNew(TimeSpan.FromSeconds(30), fakeTime);
fakeTime.Advance(TimeSpan.FromSeconds(5));
var completion = new TaskCompletionSource<DbConnectionInternal>();

// Act
bool completed = pool.TryGetConnection(owner, completion, timer, out _);
Task winner = await Task.WhenAny(completion.Task, Task.Delay(TimeSpan.FromSeconds(30)));

// Assert
Assert.False(completed);
Assert.Same(completion.Task, winner);
Assert.NotNull(await completion.Task);
Assert.Same(timer, factory.CapturedTimeout);
Assert.Equal(25_000, factory.CapturedTimeout!.MillisecondsRemainingInt);
}

#endregion
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -68,58 +68,145 @@ private WaitHandleDbConnectionPool CreatePool(
}

/// <summary>
/// Verifies that the <see cref="TimeoutTimer"/> the pool hands to the
/// connection factory reports a reduced remaining-time budget when the
/// timer's clock has advanced before the pool was entered. Both the
/// synchronous (<c>taskCompletionSource == null</c>) and asynchronous
/// paths must forward the caller's already-advanced timer rather than
/// constructing a fresh one from <c>CreationTimeout</c>. Mirrors
/// <c>ChannelDbConnectionPoolTest.GetConnection_TimeoutTimerReflectsPoolWaitTime</c>.
/// Ensures synchronous acquisition forwards the remaining budget to physical creation,
/// independently of whether login will later honor it or use the compatibility opt-out.
/// </summary>
[Theory]
[InlineData(false)] // sync
[InlineData(true)] // async
public async Task GetConnection_TimeoutTimerReflectsTimeAlreadyConsumed(bool async)
[InlineData(null)]
[InlineData(true)]
[InlineData(false)]
public void TryGetConnection_ConsumedBudget_ForwardsRemainingTime(bool? switchEnabled)
{
// Arrange: capturing factory and a fake-time-backed timer with a
// 30-second budget anchored at virtual time t = 0.
// Arrange
using LocalAppContextSwitchesHelper switches = new()
{
UseOverallConnectTimeoutForPoolWait = switchEnabled,
};
var factory = new MockSqlConnectionFactory();
var pool = CreatePool(factory);
var owner = new SqlConnection("Timeout=30");
using var owner = new SqlConnection("Timeout=30");
var fakeTime = new FakeTimeProvider();
TimeoutTimer timer = TimeoutTimer.StartNew(TimeSpan.FromSeconds(30), fakeTime);
TaskCompletionSource<DbConnectionInternal>? tcs =
async ? new TaskCompletionSource<DbConnectionInternal>() : null;

// Act: simulate 5s of budget consumed elsewhere (e.g., higher-level
// Open() work) before the pool is entered, then request a connection.
fakeTime.Advance(TimeSpan.FromSeconds(5));

// Act
bool completed = pool.TryGetConnection(
owner,
tcs,
taskCompletionSource: null,
timer,
out DbConnectionInternal? connection);

if (async)
{
// Bound the await so a regression in the pool can't hang the suite.
Task winner = await Task.WhenAny(tcs!.Task, Task.Delay(TimeSpan.FromSeconds(30)));
Assert.Same(tcs.Task, winner);
connection = await tcs.Task;
}
else
// Assert
Assert.True(completed);
Assert.NotNull(connection);
Assert.Same(timer, factory.CapturedTimeout);
Assert.Equal(25_000, factory.CapturedTimeout!.MillisecondsRemainingInt);
}

/// <summary>
/// Ensures asynchronous acquisition forwards the already-consumed budget to physical
/// creation for the default, enabled, and compatibility settings.
/// </summary>
[Theory]
[InlineData(null)]
[InlineData(true)]
[InlineData(false)]
public async Task TryGetConnectionAsync_ConsumedBudget_ForwardsRemainingTime(bool? switchEnabled)
{
// Arrange
using LocalAppContextSwitchesHelper switches = new()
{
Assert.True(completed);
}
UseOverallConnectTimeoutForPoolWait = switchEnabled,
};
var factory = new MockSqlConnectionFactory();
var pool = CreatePool(factory);
using var owner = new SqlConnection("Timeout=30");
var fakeTime = new FakeTimeProvider();
TimeoutTimer timer = TimeoutTimer.StartNew(TimeSpan.FromSeconds(30), fakeTime);
fakeTime.Advance(TimeSpan.FromSeconds(5));
var completion = new TaskCompletionSource<DbConnectionInternal>();

// Assert: factory received the same timer, and it reports the reduced
// 25-second remaining budget rather than the original 30s or the
// pool's static 15s CreationTimeout.
Assert.NotNull(connection);
// Act
bool completed = pool.TryGetConnection(owner, completion, timer, out _);
Task winner = await Task.WhenAny(completion.Task, Task.Delay(TimeSpan.FromSeconds(30)));

// Assert
Assert.False(completed);
Assert.Same(completion.Task, winner);
Assert.NotNull(await completion.Task);
Assert.Same(timer, factory.CapturedTimeout);
Assert.Equal(25_000, factory.CapturedTimeout!.MillisecondsRemainingInt);
}

/// <summary>
/// Ensures an expired overall budget also expires a queued asynchronous pool wait,
/// rather than starting a fresh CreationTimeout by default.
/// </summary>
[Theory]
[InlineData(null)]
[InlineData(true)]
public async Task TryGetConnectionAsync_ExpiredOverallBudget_TimesOut(bool? switchEnabled)
{
// Arrange
using LocalAppContextSwitchesHelper switches = new()
{
UseOverallConnectTimeoutForPoolWait = switchEnabled,
};
var pool = CreatePool(new MockSqlConnectionFactory(), maxPoolSize: 1);
using var firstOwner = new SqlConnection();
pool.TryGetConnection(
firstOwner, taskCompletionSource: null,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(30)), out DbConnectionInternal? held);
using var waitingOwner = new SqlConnection();
var completion = new TaskCompletionSource<DbConnectionInternal>();

// Act
bool completed = pool.TryGetConnection(
waitingOwner, completion, TimeoutTimer.StartExpired(), out _);
Task winner = await Task.WhenAny(completion.Task, Task.Delay(TimeSpan.FromSeconds(5)));

// Assert
Assert.NotNull(held);
Assert.False(completed);
Assert.Same(completion.Task, winner);
InvalidOperationException exception =
await Assert.ThrowsAsync<InvalidOperationException>(() => completion.Task);
Assert.Contains("prior to obtaining a connection from the pool", exception.Message);
Assert.Equal(1, pool.Count);
}

/// <summary>
/// Ensures the compatibility opt-out allows an asynchronous pool wait to succeed after
/// the caller's overall budget has expired.
/// </summary>
[Fact]
public async Task TryGetConnectionAsync_OverallBudgetDisabled_UsesLegacyPoolWait()
{
// Arrange
using LocalAppContextSwitchesHelper switches = new()
{
UseOverallConnectTimeoutForPoolWait = false,
};
var pool = CreatePool(new MockSqlConnectionFactory(), maxPoolSize: 1);
using var firstOwner = new SqlConnection();
pool.TryGetConnection(
firstOwner, taskCompletionSource: null,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(30)), out DbConnectionInternal? held);
using var waitingOwner = new SqlConnection();
var completion = new TaskCompletionSource<DbConnectionInternal>();

// Act
bool completed = pool.TryGetConnection(
waitingOwner, completion, TimeoutTimer.StartExpired(), out _);
pool.ReturnInternalConnection(held!, firstOwner);
Task winner = await Task.WhenAny(completion.Task, Task.Delay(TimeSpan.FromSeconds(5)));

// Assert
Assert.False(completed);
Assert.Same(completion.Task, winner);
Assert.Same(held, await completion.Task);
}

/// <summary>
/// Identifies which kind of caller-supplied <see cref="TimeoutTimer"/> a
/// parameterized test should construct. Used because
Expand All @@ -133,23 +220,18 @@ public enum TimerKind
}

/// <summary>
/// Verifies the resolution matrix for the synchronous
/// <c>WaitHandle.WaitAny</c> timeout:
/// <list type="bullet">
/// <item>switch ON → use the caller timer's remaining budget
/// (expired → 0, infinite → <see cref="Timeout.Infinite"/>);</item>
/// <item>switch OFF → ignore the caller timer and use
/// <c>CreationTimeout</c>, treating <c>0</c> as
/// <see cref="Timeout.Infinite"/> per legacy behavior.</item>
/// </list>
/// Ensures synchronous waits use the remaining caller budget by default and when enabled,
/// while the compatibility opt-out uses CreationTimeout. Infinite waits remain infinite.
/// </summary>
[Theory]
[InlineData(null, TimerKind.Expired, 5_000, 0u)]
[InlineData(null, TimerKind.Infinite, 5_000, unchecked((uint)Timeout.Infinite))]
[InlineData(true, TimerKind.Expired, 5_000, 0u)]
[InlineData(true, TimerKind.Infinite, 5_000, unchecked((uint)Timeout.Infinite))]
[InlineData(false, TimerKind.Expired, 1_500, 1_500u)]
[InlineData(false, TimerKind.Expired, 0, unchecked((uint)Timeout.Infinite))]
public void ResolvePoolWaitTimeoutMs_ReturnsExpected(
bool switchEnabled,
public void ResolvePoolWaitTimeoutMs_SwitchAndBudget_ReturnsExpectedTimeout(
bool? switchEnabled,
TimerKind timerKind,
int creationTimeoutMs,
uint expected)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public class LocalAppContextSwitchesTest
[Fact]
public void TestDefaultAppContextSwitchValues()
{
// Arrange
// LocalAppContextSwitches caches each switch value on first access for
// the lifetime of the process. Other tests running in parallel may
// already have triggered caching, or may use LocalAppContextSwitchesHelper
Expand Down Expand Up @@ -59,6 +60,10 @@ public void TestDefaultAppContextSwitchValues()
switchesHelper.DisableTnirByDefault = null;
#endif

// Act
bool overallConnectTimeout = switchesHelper.UseOverallConnectTimeoutForPoolWait == true;

// Assert
Assert.False(switchesHelper.LegacyRowVersionNullBehavior);
Assert.False(switchesHelper.SuppressInsecureTlsWarning);
Assert.False(switchesHelper.MakeReadAsyncBlocking);
Expand All @@ -68,7 +73,7 @@ public void TestDefaultAppContextSwitchValues()
Assert.True(switchesHelper.UseCompatibilityAsyncBehaviour);
Assert.True(switchesHelper.UseLegacyIdleTimeoutBehavior);
Assert.False(switchesHelper.UseConnectionPoolV2);
Assert.False(switchesHelper.UseOverallConnectTimeoutForPoolWait);
Assert.True(overallConnectTimeout);
Assert.False(switchesHelper.TruncateScaledDecimal);
Assert.False(switchesHelper.IgnoreServerProvidedFailoverPartner);
Assert.False(switchesHelper.UseLegacyFailoverAlternationOnLoginSqlErrors);
Expand Down
Loading
Loading