Skip to content

Managed SNI: attention timeout publishes the failure before breaking the connection, so cleanup throws "another read operation is pending" #5022

Open

Description

@a11smiles

Describe the bug

On managed SNI with TLS, a command timeout whose attention isn't acknowledged in time can fail with:

System.NotSupportedException: This method may not be called when another read operation is pending.
   at System.Net.Security.SslStream.ReadAsyncInternal[TIOAdapter](Memory`1 buffer, CancellationToken cancellationToken)
   at System.Net.Security.SslStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   at Microsoft.Data.SqlClient.ManagedSni.SniPacket.ReadFromStream(Stream stream)
   at Microsoft.Data.SqlClient.ManagedSni.SniTcpHandle.Receive(SniPacket& packet, Int32 timeoutInMilliseconds)
   at Microsoft.Data.SqlClient.ManagedSni.TdsParserStateObjectManaged.ReadSyncOverAsync(Int32 timeoutRemaining, UInt32& error)
   at Microsoft.Data.SqlClient.TdsParserStateObject.ReadSniSyncOverAsync()
   at Microsoft.Data.SqlClient.TdsParserStateObject.TryReadNetworkPacket()
   at Microsoft.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer()
   at Microsoft.Data.SqlClient.TdsParserStateObject.TryReadByte(Byte& value)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(...)
   at Microsoft.Data.SqlClient.TdsParser.Run(...)
   at Microsoft.Data.SqlClient.TdsParser.ProcessAttention(TdsParserStateObject stateObj)
   at Microsoft.Data.SqlClient.TdsParser.ProcessPendingAck(TdsParserStateObject stateObj)
   at Microsoft.Data.SqlClient.TdsParserStateObject.ResetCancelAndProcessAttention()
   at Microsoft.Data.SqlClient.TdsParserStateObject.CloseSession()
   at Microsoft.Data.SqlClient.SqlCommand.PutStateObject()
   at Microsoft.Data.SqlClient.SqlCommand.ReliablePutStateObject()
   at Microsoft.Data.SqlClient.SqlCommand.EndExecuteNonQueryAsync(IAsyncResult asyncResult)

The exception surfaces from the awaited command that timed out, in place of the timeout SqlException. No second command is issued and the connection isn't used concurrently, so it isn't application overlap.

Cause

In TdsParserStateObject.OnTimeoutCore (v6.1.3, TdsParserStateObject.cs around lines 2880-2915), the attention-timeout continuation completes the pending packet task with the timeout (source.TrySetException(ex)) before it sets _parser.State = TdsParserState.Broken and calls _parser.Connection.BreakConnection().

Completing that task runs the command's completion path, EndExecuteNonQueryAsync → PutStateObject → CloseSession → ResetCancelAndProcessAttention → ProcessPendingAck → ProcessAttention. If that path runs before the break, the parser still looks usable, so ProcessAttention starts a synchronous transport read (SniTcpHandle.Receive → SniPacket.ReadFromStream → SslStream.Read). Meanwhile the original asynchronous SslStream.ReadAsync (SniPacket.netcore.cs, ReadAsync(..., CancellationToken.None)) is still pending, and SslStream rejects the overlapping read.

This looks like the same publish-before-break ordering behind #4971, where SqlTransaction dispose races the background close. Here the race is between the command's own cleanup and the break.

To reproduce

All synthetic: one database, a one-row table, local SQL Server 2022 (16.0.4305.5) in Docker, TLS on, MARS off.

  1. Connect through a local TCP proxy that forwards TLS unchanged, but withholds all server replies on the one connection under test for about 6.5 s. Other connections are forwarded normally.
  2. Run one awaited command with CommandTimeout = 1: await connection.ExecuteAsync("WAITFOR DELAY '00:00:08'; SELECT 42;") (Dapper 2.1.35), or the equivalent SqlCommand.ExecuteNonQueryAsync.
  3. The command times out, sends attention, and waits for the acknowledgment, which the proxy withholds.

The window is narrow, so to make it deterministic our harness attaches an ExecuteSynchronously continuation to the pending _networkPacketTaskSource task, read by reflection. When that task faults or is cancelled, the continuation pauses 200 ms. It writes no driver fields and issues no SQL. It only holds the timeout publisher after TrySetException while the command's completion path runs.

With that pause: 6 of 6 runs fail with the exception above on 6.1.3 (the NuGet package and a source build of tag v6.1.3) and on 6.1.7. It also fails with Pooling=false. A new pooled connection afterwards succeeds on a different physical connection, so it isn't pool poisoning. SqlConnection.ClearPool after the failure doesn't help, since the exception is thrown inside the failing await.

Without the pause it reproduces intermittently. We first saw it in a CI-style test suite against a SQL Server that stopped responding for several minutes.

Expected behavior

The command fails with the original timeout SqlException. Cleanup doesn't start another read on a transport whose read is still pending.

Possible fix (verified only in a scratch build)

Mark the parser broken and break the connection before publishing the failure:

                                             catch (Exception ex)
                                             {
+                                                _parser.State = TdsParserState.Broken;
+                                                Interlocked.CompareExchange(ref _networkPacketTaskSource, null, source);
+                                                _parser.Connection.BreakConnection();
                                                 if (source.TrySetException(ex))

With only this change and the same fault and pause, the exception no longer reproduces, and the caller gets the original timeout. This was a causal check, not a reviewed fix. MARS, native SNI and concurrent close or cancel paths weren't tested.

Further technical details

Activity

  1. github-actions commented on Nov 9, 2026

    @github-actions

    🔍 Triage Summary

    Check Result
    Issue type Bug
    Environment All required environment details provided for investigation
    Area Area\Managed SNI
    Duplicates Potentially related: #4971, #4374, #4969 (none an exact duplicate)
    Regression Inconclusive (reproduced on 6.1.3 and 6.1.7; no earlier good version identified)

    Analysis

    On managed SNI with TLS, the command-timeout attention path in TdsParserStateObject.OnTimeoutCore completes the pending packet task with the timeout before it marks the parser broken. The command's cleanup (ProcessAttention) can then start a synchronous SslStream.Read while the original async read is still pending, which throws NotSupportedException in place of the timeout SqlException. The report includes a deterministic repro and a candidate fix. Suggested severity: P2. Behavior is incorrect and the exception is misleading, but it only occurs when the attention acknowledgment is delayed.

    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 #5022 · copilot · auto · 23.6 AIC · ⌖ 11.3 AIC · ⊞ 7.8K · ◷

  2. added
    Area\Managed SNI
    on Nov 12, 2026
  3. lorocash commented on Nov 17, 2026

    @lorocash

    Describe the bug

    On managed SNI with TLS, a command timeout whose attention isn't acknowledged in time can fail with:

    System.NotSupportedException: This method may not be called when another read operation is pending.
       at System.Net.Security.SslStream.ReadAsyncInternal[TIOAdapter](Memory`1 buffer, CancellationToken cancellationToken)
       at System.Net.Security.SslStream.Read(Byte[] buffer, Int32 offset, Int32 count)
       at Microsoft.Data.SqlClient.ManagedSni.SniPacket.ReadFromStream(Stream stream)
       at Microsoft.Data.SqlClient.ManagedSni.SniTcpHandle.Receive(SniPacket& packet, Int32 timeoutInMilliseconds)
       at Microsoft.Data.SqlClient.ManagedSni.TdsParserStateObjectManaged.ReadSyncOverAsync(Int32 timeoutRemaining, UInt32& error)
       at Microsoft.Data.SqlClient.TdsParserStateObject.ReadSniSyncOverAsync()
       at Microsoft.Data.SqlClient.TdsParserStateObject.TryReadNetworkPacket()
       at Microsoft.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer()
       at Microsoft.Data.SqlClient.TdsParserStateObject.TryReadByte(Byte& value)
       at Microsoft.Data.SqlClient.TdsParser.TryRun(...)
       at Microsoft.Data.SqlClient.TdsParser.Run(...)
       at Microsoft.Data.SqlClient.TdsParser.ProcessAttention(TdsParserStateObject stateObj)
       at Microsoft.Data.SqlClient.TdsParser.ProcessPendingAck(TdsParserStateObject stateObj)
       at Microsoft.Data.SqlClient.TdsParserStateObject.ResetCancelAndProcessAttention()
       at Microsoft.Data.SqlClient.TdsParserStateObject.CloseSession()
       at Microsoft.Data.SqlClient.SqlCommand.PutStateObject()
       at Microsoft.Data.SqlClient.SqlCommand.ReliablePutStateObject()
       at Microsoft.Data.SqlClient.SqlCommand.EndExecuteNonQueryAsync(IAsyncResult asyncResult)
    

    The exception surfaces from the awaited command that timed out, in place of the timeout SqlException. No second command is issued and the connection isn't used concurrently, so it isn't application overlap.

    Cause

    In TdsParserStateObject.OnTimeoutCore (v6.1.3, TdsParserStateObject.cs around lines 2880-2915), the attention-timeout continuation completes the pending packet task with the timeout (source.TrySetException(ex)) before it sets _parser.State = TdsParserState.Broken and calls _parser.Connection.BreakConnection().

    Completing that task runs the command's completion path, EndExecuteNonQueryAsync → PutStateObject → CloseSession → ResetCancelAndProcessAttention → ProcessPendingAck → ProcessAttention. If that path runs before the break, the parser still looks usable, so ProcessAttention starts a synchronous transport read (SniTcpHandle.Receive → SniPacket.ReadFromStream → SslStream.Read). Meanwhile the original asynchronous SslStream.ReadAsync (SniPacket.netcore.cs, ReadAsync(..., CancellationToken.None)) is still pending, and SslStream rejects the overlapping read.

    This looks like the same publish-before-break ordering behind #4971, where SqlTransaction dispose races the background close. Here the race is between the command's own cleanup and the break.

    To reproduce

    All synthetic: one database, a one-row table, local SQL Server 2022 (16.0.4305.5) in Docker, TLS on, MARS off.

    1. Connect through a local TCP proxy that forwards TLS unchanged, but withholds all server replies on the one connection under test for about 6.5 s. Other connections are forwarded normally.
    2. Run one awaited command with CommandTimeout = 1: await connection.ExecuteAsync("WAITFOR DELAY '00:00:08'; SELECT 42;") (Dapper 2.1.35), or the equivalent SqlCommand.ExecuteNonQueryAsync.
    3. The command times out, sends attention, and waits for the acknowledgment, which the proxy withholds.

    The window is narrow, so to make it deterministic our harness attaches an ExecuteSynchronously continuation to the pending _networkPacketTaskSource task, read by reflection. When that task faults or is cancelled, the continuation pauses 200 ms. It writes no driver fields and issues no SQL. It only holds the timeout publisher after TrySetException while the command's completion path runs.

    With that pause: 6 of 6 runs fail with the exception above on 6.1.3 (the NuGet package and a source build of tag v6.1.3) and on 6.1.7. It also fails with Pooling=false. A new pooled connection afterwards succeeds on a different physical connection, so it isn't pool poisoning. SqlConnection.ClearPool after the failure doesn't help, since the exception is thrown inside the failing await.

    Without the pause it reproduces intermittently. We first saw it in a CI-style test suite against a SQL Server that stopped responding for several minutes.

    Expected behavior

    The command fails with the original timeout SqlException. Cleanup doesn't start another read on a transport whose read is still pending.

    Possible fix (verified only in a scratch build)

    Mark the parser broken and break the connection before publishing the failure:

                                             catch (Exception ex)
                                             {
    
    •                                            _parser.State = TdsParserState.Broken;
      
    •                                            Interlocked.CompareExchange(ref _networkPacketTaskSource, null, source);
      
    •                                            _parser.Connection.BreakConnection();
                                                 if (source.TrySetException(ex))
      

    With only this change and the same fault and pause, the exception no longer reproduces, and the caller gets the original timeout. This was a causal check, not a reviewed fix. MARS, native SNI and concurrent close or cancel paths weren't tested.

    Further technical details

  4. moved this from To triage to Backlog in SqlClient Boardon Nov 17, 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

    Area\Managed SNI

    Type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions