Skip to content

ExecuteReaderAsync can remain pending after Azure SQL 10928 with Always Encrypted and Attestation Protocol=None #4735

Closed as duplicate

Description

@get-flat

Sorry for AI generated report but this is a real issue we hit so we can provide more details if needed.
I udnerstand that we hit the limit but it should not hang. Repro is for Basic tier limits but it hangs for higher tiers DTU tiers as well.

ExecuteReaderAsync can remain pending after Azure SQL 10928 with Always Encrypted and Attestation Protocol=None

Describe the bug

SqlCommand.ExecuteReaderAsync can leave its returned task pending after Azure SQL rejects a request with error 10928 (worker limit reached), when the connection has both:

Column Encryption Setting=Enabled;Attestation Protocol=None;

This was reproduced against an empty Azure SQL Basic database with VBS enclaves enabled, using 64 independent connections and the following parameterized command:

WAITFOR DELAY @delay; SELECT @@SPID;

@delay is varchar(8) with value 00:00:15, and CommandTimeout is 60 seconds. In the observed failing run, 26 returned tasks were still pending in ExecuteReaderAsync at 120 seconds. An independent watchdog ended the process; the driver did not complete those calls before that deadline.

No encrypted columns, column keys, key-store providers, tables, stored procedures, transactions or ORM are required for this reproduction. The connection's AE/enclave settings are sufficient to enter the affected client-side error path.

The database refusing excess work is expected. The problem is that some rejected operations never report an error through the task returned to the caller.

Expected behavior

Every operation should eventually complete successfully or complete with a failure/cancellation outcome. When the connection closes during error handling, the exception should still be propagated to the returned task. An internal continuation must not fault while leaving that task pending.

This is consistent with the documented ExecuteReaderAsync contract that execution exceptions are reported through the returned task. API documentation

Environment

Component Tested configuration
Microsoft.Data.SqlClient NuGet 7.0.2; assembly version 7.0.0.0
SNI runtime dependency Microsoft.Data.SqlClient.SNI.runtime 6.0.2; Windows native path
.NET Runtime 10.0.11, target framework net10.0
Client platform Windows x64
Database Azure SQL Database, Basic, 5 DTUs
Database enclave setting VBS
Authentication Microsoft Entra SQL access token assigned to SqlConnection.AccessToken
Connection settings Encryption enabled, certificate validation enabled, pooling enabled, max pool size 100, MARS disabled, connect retry count 0
Command Parameterized text command; 60-second timeout
Command cancellation No cancellation requested in the failing 64-command reproduction

No custom driver build or command retry provider was used. This report establishes behavior on 7.0.2; other driver versions, runtimes, transport implementations and database tiers have not been verified for this exact reproduction.

Reproduction procedure

  1. Use an empty disposable Azure SQL Basic database that you control. Basic has a documented limit of 30 concurrent workers; its connection/session limit is different. Azure SQL limits
  2. Enable VBS enclaves on that database. Attestation Protocol=None is an explicit enclave configuration; it does not mean enclave handling is disabled. A database without enclave support rejects this connection configuration during login, which is a different result.
  3. Ensure the test identity can connect and read the service-objective view used by the setup check. No application schema or column-encryption keys need to be created.
  4. Build the console project below and provide the target and access token through environment variables. Do not include either real value in the issue or its attachments.
  5. Run the default mode. The program pre-opens 64 independent connections sequentially, then releases a gate to start their commands together. This separates SQL request-worker pressure from concurrent login limits. Each command uses its own connection; no connection or command instance is used concurrently by multiple operations.
  6. Repeat using --without-enclave on the same VBS-enabled database. AE remains enabled; only the explicit enclave connection option is removed.

Example PowerShell setup, using placeholders:

$env:SQL_CONNECTION_STRING = 'Server=tcp:<server>.database.windows.net,1433;Database=<disposable-basic-database>;'
$env:SQL_ACCESS_TOKEN = az account get-access-token --tenant '<tenant-id>' --resource https://database.windows.net/ --query accessToken -o tsv
dotnet build repro/Repro.csproj --configuration Debug

# Reproduction:
dotnet repro/bin/Debug/net10.0/Repro.dll

# Control; run after the first process has ended:
dotnet repro/bin/Debug/net10.0/Repro.dll --without-enclave

Remove-Item Env:SQL_ACCESS_TOKEN

The 120-second watchdog is outside SqlClient and exits 124 when calls remain pending. It does not cancel commands, simulate a driver timeout, or count the operation as successfully cancelled. The five-minute process watchdog also bounds setup and disposal. A normally terminating run can contain expected SQL failures; it does not mean every command succeeded.

WAITFOR is used to sustain overlapping requests, not to consume CPU. SQL Server can end waits under thread pressure, so exact counts may depend on timing. Reaching the worker limit should be confirmed from errors and/or sys.dm_db_resource_stats.max_worker_percent rather than assumed from the number of connections.

Observed results

These are counts from individual controlled runs, not a measured failure rate across repeated runs.

Connection configuration Database enclave setting Outcome
AE disabled, attestation unspecified Default 30 successful; 34 SQL 10928 errors; all 64 settled
AE enabled, attestation unspecified Default 30 successful; 34 closed-connection exceptions; all 64 settled
AE enabled, Attestation Protocol=None VBS 30 successful; 8 SQL 10928 errors; 26 calls still pending at 120 seconds
AE enabled, attestation unspecified Same VBS database as failing run 30 successful; 34 closed-connection exceptions; all 64 settled in approximately 15 seconds

The post-failure control on the same VBS database recorded 100% worker utilization, so it also exercised worker exhaustion. Enabling AE alone changed some reported exceptions but did not reproduce the unfinished-task symptom in these controls. The failing combination included explicit enclave handling.

Exception evidence

The failing process contained this exception inside the driver's internal continuation. Below are the relevant frames, with memory addresses, local paths and runtime offsets removed:

System.InvalidOperationException: Invalid operation. The connection is closed.
  at Microsoft.Data.SqlClient.SqlConnection.GetOpenTdsConnection()
  at Microsoft.Data.SqlClient.SqlConnection.get_Parser()
  at Microsoft.Data.SqlClient.SqlCommand.get_IsColumnEncryptionEnabled()
  at Microsoft.Data.SqlClient.SqlCommand.get_ShouldUseEnclaveBasedWorkflow()
  at Microsoft.Data.SqlClient.SqlCommand.<>c__DisplayClass188_0.<CreateLocalCompletionTask>b__0(Task<object>)
  at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(...)
  at System.Threading.Tasks.Task.ExecuteWithThreadLocal(...)

SQL 10928 was also observed in that run, identifying the worker-limit rejection. The affected caller tasks remained awaiting ExecuteReaderAsync instead of receiving the failure. The stack above is from the isolated reproduction; it is not an exception successfully caught by the corresponding caller.

Source analysis

The 7.0.2 NuGet package identifies source commit 8c70cec98444338ddb0b97be94c34fde93970241.

The observed stack and inspected source point to this path:

  1. TriggerInternalEndAndRetryIfNecessary selects internal completion processing when the enclave workflow is enabled.
  2. In CreateLocalCompletionTask, the internal end-reader call raises a SQL error after the connection has closed.
  3. The catch block checks whether the error is eligible for an encryption/enclave retry. Its condition evaluates ShouldUseEnclaveBasedWorkflow before the isEnclaveSessionError boolean.
  4. With explicit enclave configuration, that property evaluates IsColumnEncryptionEnabled, which accesses SqlConnection.Parser and then GetOpenTdsConnection. The closed connection causes a second InvalidOperationException.
  5. This second exception escapes from the catch block before the later code can fault globalCompletion. The internal continuation faults, while the separate task returned to the caller remains pending.

The nested try/catch around a later GetOpenTdsConnection().DecrementAsyncCount() does not protect the earlier enclave-property evaluation.

Pinned source references:

This appears related in failure mechanism to #3067, but the exception here originates in the enclave-property check earlier in the error handler. The prior issue's closure does not establish that this specific path is covered. No claim is made that the same original defect was reintroduced.

Requested fix and regression coverage

Please ensure that exceptions anywhere in this internal completion/error-processing path are propagated to the caller's task, including exceptions while evaluating enclave state after a connection closes.

Suggested regression cases:

  • AE enabled, explicit enclave handling enabled, and a connection-closing SQL error during asynchronous completion.
  • A non-enclave error such as 10928 that should not enter enclave retry handling.
  • An exception thrown while determining whether an enclave retry is applicable.
  • Every returned task must settle within a bounded test deadline; an internal continuation fault must not leave its caller pending.

Reordering the boolean operands may avoid this particular 10928 path, but the general completion guarantee should also cover failures while processing genuine enclave-related errors. A permanent loss of task completion is distinct from the expected transient SQL rejection.

Minimal reproduction source

The following is a sanitized standalone extraction of the tested command/concurrency pattern. Its build is checked separately; the observation table records the instrumented experimental runs described above.

Repro.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Data.SqlClient" Version="7.0.2" />
  </ItemGroup>
</Project>

Program.cs

using System.Collections.Concurrent;
using System.Data;
using System.Diagnostics;
using Microsoft.Data.SqlClient;

// Use an empty, disposable Azure SQL Basic database with VBS enclaves enabled.
// Neither input is printed. Supply a SQL access token for the target tenant.
var input = Environment.GetEnvironmentVariable("SQL_CONNECTION_STRING")
    ?? throw new InvalidOperationException("Set SQL_CONNECTION_STRING.");
var token = Environment.GetEnvironmentVariable("SQL_ACCESS_TOKEN")
    ?? throw new InvalidOperationException("Set SQL_ACCESS_TOKEN.");
bool enclave = !args.Contains("--without-enclave");
var builder = new SqlConnectionStringBuilder(input)
{
    Encrypt = true,
    TrustServerCertificate = false,
    Pooling = true,
    MaxPoolSize = 100,
    ConnectTimeout = 30,
    ConnectRetryCount = 0,
    MultipleActiveResultSets = false,
    ColumnEncryptionSetting = SqlConnectionColumnEncryptionSetting.Enabled,
    AttestationProtocol = enclave
        ? SqlConnectionAttestationProtocol.None
        : SqlConnectionAttestationProtocol.NotSpecified,
    EnclaveAttestationUrl = "",
    ApplicationName = "SqlClientRepro"
};
SqlConnection NewConnection() => new(builder.ConnectionString) { AccessToken = token };

var pending = new ConcurrentDictionary<int, string>();
// Final process bound also covers setup/disposal. It does not cancel SQL commands.
using var watchdog = new Timer(_ =>
{
    Console.WriteLine($"PROCESS WATCHDOG: {pending.Count} calls still pending.");
    Console.Out.Flush();
    Environment.Exit(124);
}, null, TimeSpan.FromMinutes(5), Timeout.InfiniteTimeSpan);

await using var observer = NewConnection();
await observer.OpenAsync();
using (var guard = observer.CreateCommand())
{
    guard.CommandText = """
        SELECT CONVERT(int, SERVERPROPERTY('EngineEdition')), edition, service_objective
        FROM sys.database_service_objectives WHERE database_id = DB_ID();
        """;
    await using var reader = await guard.ExecuteReaderAsync();
    if (!await reader.ReadAsync() || reader.GetInt32(0) != 5 ||
        reader.GetString(1) != "Basic" || reader.GetString(2) != "Basic")
        throw new InvalidOperationException("This reproducer requires Azure SQL Basic.");
}

var connections = new List<SqlConnection>();
try
{
    // Separate request-worker exhaustion from simultaneous login pressure.
    for (int i = 0; i < 64; i++)
    {
        var connection = NewConnection();
        connections.Add(connection);
        await connection.OpenAsync();
    }

    Console.WriteLine($"Starting 64 commands; Always Encrypted enabled; enclave={enclave}.");
    var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
    var tasks = connections.Select(async (connection, index) =>
    {
        await gate.Task;
        var clock = Stopwatch.StartNew();
        pending[index] = "ExecuteReaderAsync";
        try
        {
            using var command = connection.CreateCommand();
            command.CommandTimeout = 60;
            command.CommandText = "WAITFOR DELAY @delay; SELECT @@SPID;";
            command.Parameters.Add("@delay", SqlDbType.VarChar, 8).Value = "00:00:15";
            await using var reader = await command.ExecuteReaderAsync(CancellationToken.None);
            pending[index] = "ReadAsync";
            if (!await reader.ReadAsync()) throw new InvalidOperationException("Missing row.");
            Console.WriteLine($"{index}: success after {clock.ElapsedMilliseconds} ms");
        }
        catch (SqlException ex)
        {
            string numbers = string.Join(",", ex.Errors.Cast<SqlError>().Select(e => e.Number));
            Console.WriteLine($"{index}: SQL [{numbers}] after {clock.ElapsedMilliseconds} ms; state={connection.State}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"{index}: {ex.GetType().Name} after {clock.ElapsedMilliseconds} ms; state={connection.State}");
        }
        finally { pending.TryRemove(index, out _); }
    }).ToArray();

    gate.SetResult();
    Task all = Task.WhenAll(tasks);
    if (await Task.WhenAny(all, Task.Delay(TimeSpan.FromSeconds(120))) != all)
    {
        Console.WriteLine($"HANG: {pending.Count} calls remain pending after 120 seconds; CommandTimeout=60.");
        foreach (var call in pending.OrderBy(p => p.Key))
            Console.WriteLine($"{call.Key}: {call.Value}");
        // Terminate the isolated process rather than treating a watchdog as SQL cancellation.
        Console.Out.Flush();
        Environment.Exit(124);
    }
    await all;
    Console.WriteLine("All 64 calls settled. Inspect outcomes to confirm worker-limit pressure.");
}
finally
{
    foreach (var connection in connections) await connection.DisposeAsync();
}

Activity

  1. github-actions commented on Sep 23, 2026

    @github-actions

    🔍 Triage Summary

    Check Result
    Issue type Bug
    Environment All required environment details provided for investigation
    Area Area\Async
    Duplicates Potentially related: #1762, #4199
    Regression Not indicated (no prior-working-version claim)

    Analysis

    ExecuteReaderAsync's returned task can remain pending forever when the server rejects a request with error 10928 (worker limit reached) on a connection configured with Column Encryption Setting=Enabled and Attestation Protocol=None. The included stack trace shows an internal continuation (SqlCommand's enclave-workflow check, invoked from the async completion callback) throwing InvalidOperationException: The connection is closed while accessing SqlConnection.Parser/IsColumnEncryptionEnabled/ShouldUseEnclaveBasedWorkflow after the connection was already torn down by error handling — and that exception is not propagated to the caller's task, leaving it faulted internally but pending externally. This closely matches the older issue #1762 (same 10928 error, same "connection is closed" hang, Column Encryption enabled) and is plausibly the AE/enclave-specific manifestation discussed in #4199. Given this can cause indefinite hangs in production under normal Azure SQL throttling (no cancellation needed to trigger it), this warrants a P1 severity.

    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 #4735 · copilot · auto · 40.1 AIC · ⌖ 12.5 AIC · ⊞ 13K · ◷

  2. get-flat commented on Sep 23, 2026

    @get-flat
    Author

    BTW Is this project still maintain becasue it seems the same issue (with repro steps was reported 2022) and you did nothing about it? Or there are official alternatives which should be used with azure DBs?

  3. mdaigle commented on Sep 23, 2026

    @mdaigle
    Contributor

    Hey @get-flat, thank you for the report. Sorry you're facing this issue.
    If you don't mind, I'm going to close this as a duplicate of #1762. That issue is prioritized as a P2 at the moment. Please chime in there and let us know that it's important to you as we do prioritized partly based on community interest. Thanks!

  4. moved this from To triage to Done in SqlClient Boardon Sep 23, 2026
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

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions