Skip to content

Null Reference Exception during command timeout #4374

Open

Description

@m0a0k0s

Describe the bug

NullReferenceException on timeout instead of SqlException.
I see only couple of them in production for the last month.

ExceptionDetail_HResult -2147467261
ExceptionDetail_Message Object reference not set to an instance of an object.
ExceptionDetail_Source Microsoft.Data.SqlClient
ExceptionDetail_StackTrace
   at Microsoft.Data.SqlClient.TdsParserStateObject.ReadSniSyncOverAsync()
   at Microsoft.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer()
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
   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.EndExecuteNonQueryAsync(IAsyncResult asyncResult)
   at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location ---
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQueryAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQueryAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQueryAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.ExecuteSqlRawAsync(DatabaseFacade databaseFacade, String sql, IEnumerable`1 parameters, CancellationToken cancellationToken)
   at ...

ExceptionDetail_TargetSite Void ReadSniSyncOverAsync()
ExceptionDetail_Type System.NullReferenceException
observed_timestamp 1781769665345251900

CommandTimeout	'60'
CommandType	'Text',
EventId_Id	20102
EventId_Name	Microsoft.EntityFrameworkCore.Database.Command.CommandError
commandText	DELETE dbo.SYSException WHERE CreatedOn < @CutoffTime
elapsed		65,002
message_template_text	Failed executing DbCommand ({elapsed}ms) [Parameters=[{parameters}], CommandType='{commandType}', CommandTimeout='{commandTimeout}']{newLine}{commandText}
newLine	
observed_timestamp	1781769665329176300
parameters	@CutoffTime='?' (DbType = DateTime)
scope_name	Microsoft.EntityFrameworkCore.Database.Command

Further technical details

Microsoft.Data.SqlClient version: 6.1.2
EF Core: Microsoft.EntityFrameworkCore.SqlServer 9.0.7
.NET target: .Net 9
SQL Server version: SQL Server 2022
Operating system: Windows Server 2022
multipleactiveresultsets=True

Additional context
Similar to #3720

Activity

  1. cheenamalhotra commented on Jun 23, 2026

    @cheenamalhotra
    Member

    /triage

  2. github-actions commented on Jun 23, 2026

    @github-actions
  3. paulmedynski commented on Jul 16, 2026

    @paulmedynski
    Contributor

    /triage

  4. github-actions commented on Jul 16, 2026

    @github-actions

    🔍 Triage Summary (on-demand re-triage)

    Check Result
    Issue type Bug
    Environment All required environment details provided for investigation
    Area Area\Async
    Duplicates Potentially related: #3720 (NullReferenceException in async callback path, same SqlClient version / .NET 9 stack)
    Regression Not indicated

    Analysis

    When an async command (EndExecuteNonQueryAsync) times out (60s CommandTimeout, elapsed 65s), the cleanup path calls CloseSession() → ResetCancelAndProcessAttention() → ProcessPendingAck() → ProcessAttention() → TdsParser.Run() → ReadSniSyncOverAsync(), where a NullReferenceException is thrown instead of the expected SqlException. With MARS enabled (multipleactiveresultsets=True), concurrent session teardown can leave the SNI packet handle, _networkPacketTaskSource, or the underlying SNI session object null by the time the synchronous attention-acknowledgment read is attempted. This is a P2 bug — intermittent in production but causes an unhandled exception that can corrupt connection pool state.

    Next Steps

    • Assign this issue to Copilot coding agent to investigate TdsParserStateObject.ReadSniSyncOverAsync() — identify which object reference is null (likely the SNI handle, _networkPacketTaskSource, or an internal packet buffer) and apply a null-guard that converts the NullReferenceException into an appropriate SqlException so the session can be cleaned up gracefully.
    • Investigate TdsParser.ProcessAttention() and TdsParserStateObject.CloseSession() for the MARS code path — determine whether async timeout cancellation clears SNI state before ProcessPendingAck has finished its synchronous read, and whether a race condition exists between MARS session teardown and attention acknowledgment.
    • Review the fix (if any) applied for related issue Unobserved null reference exception #3720 (the ReadAsyncCallback/SniMarsHandle path) and apply the same null-guard pattern consistently to the sync-over-async path (ReadSniSyncOverAsync).

    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 issue #4374 · 28.4 AIC · ⌖ 6.4 AIC · ⊞ 8.4K · ◷

  5. moved this from To triage to No status in SqlClient Boardon Jul 16, 2026
  6. self-assigned this
    on Jul 16, 2026
  7. moved this to Investigating in SqlClient Boardon Jul 17, 2026
  8. added this to the 8.0.0-preview1 milestone on Oct 1, 2026
  9. cheenamalhotra commented on Nov 11, 2026

    @cheenamalhotra
    Member

    @m0a0k0s

    Could you please try v8.0.0-preview1 and let us know if you still observe this issue? #4680 will likely address this issue as well, but needs to be validated in customer space.

  10. removed this from the 8.0.0 milestone on Nov 11, 2026
  11. moved this from Investigating to In validation in SqlClient Boardon Nov 11, 2026
  12. m0a0k0s commented on Nov 11, 2026

    @m0a0k0s
    Author

    @cheenamalhotra The application affected by this issue is still running on .NET 9, and I don’t have a timeline yet for upgrading it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions