Cancelling `SqlBatch.ExecuteNonQueryAsync` throws `ArgumentOutOfRangeException` from `SqlCommand.GetBatchCommand` instead of a cancellation exception
I maintainer di solito rispondono entro 1 giorno
Valutazione
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Idoneità per principianti
- 53/100
Direzione di ricerca
Start with TdsParser.ThrowExceptionAndWarning and SqlCommand.GetBatchCommand, then trace how GetCurrentBatchIndex is used in TdsParser.TryRun and how both exception branches retrieve a batch command. Check how valid indices are defined in batch and non-batch mode. Done means cancellation and other errors at the end of a batch no longer become ArgumentOutOfRangeException; use the supplied LocalDB reproduction to verify.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Descrizione
Describe the bug
When the CancellationToken passed to SqlBatch.ExecuteNonQueryAsync fires just after the last batch command finished, ArgumentOutOfRangeException is thrown from inside SqlClient instead of the expected cancellation exception (SqlException "Operation cancelled by user" / OperationCanceledException).
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
at System.Collections.Generic.List`1.get_Item(Int32 index)
at Microsoft.Data.SqlClient.SqlCommand.GetBatchCommand(Int32 index)
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, SqlCommand command, Boolean callerHasConnectionLock, Boolean asyncClose)
at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at Microsoft.Data.SqlClient.SqlCommand.InternalEndExecuteNonQuery(IAsyncResult asyncResult, Boolean isInternal, String endMethod)
at Microsoft.Data.SqlClient.SqlCommand.EndExecuteNonQueryInternal(IAsyncResult asyncResult)
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)
We hit this in production in an ASP.NET Core endpoint that runs a single-command SqlBatch with HttpContext.RequestAborted: when the client goes away, the request fails with this exception rather than a cancellation, and the real cause is hidden.
Analysis
- Every DONEPROC increments
SqlCommand._currentlyExecutingBatch(SqlCommand.OnDoneProc). After the last command's DONEPROC it equals_RPCList.Count. - If the attention ACK is processed after that,
TdsParser.TryRunadds the "Operation cancelled by user" error withbatchIndex: cmdHandler?.GetCurrentBatchIndex(), which is now_RPCList.Count. ThrowExceptionAndWarningthen callscommand.GetBatchCommand(index)→_RPCList[_RPCList.Count]→ArgumentOutOfRangeException, which replaces the cancellation error.
The same applies to any error added with GetCurrentBatchIndex() after the last DONEPROC (e.g. the SevereError paths in TryRun).
A related spot: the temp.Count == 1 && temp[0].Exception != null branch calls command?.GetBatchCommand(temp[0].BatchIndex) without the >= 0 check the other branch has, so a BatchIndex of -1 (non-batch mode) would throw the same way.
Possible fix: check the index against _RPCList.Count (e.g. have GetBatchCommand return null for an index outside the list), and use the same guard in both branches of ThrowExceptionAndWarning.
To reproduce
LocalDB, .NET 10, Microsoft.Data.SqlClient 7.1.1. It fails in about 40% of iterations:
using Microsoft.Data.SqlClient;
const string cs = @"Server=(localdb)\MSSQLLocalDB;Database=tempdb;Integrated Security=true;Encrypt=false";
await using (var c = new SqlConnection(cs))
{
await c.OpenAsync();
await using var setup = new SqlCommand("IF OBJECT_ID('dbo.ReproItems') IS NULL CREATE TABLE dbo.ReproItems (Id int NOT NULL)", c);
await setup.ExecuteNonQueryAsync();
}
int aoore = 0, other = 0;
for (var i = 0; i < 20000; i++)
{
await using var conn = new SqlConnection(cs);
await conn.OpenAsync();
await using var batch = new SqlBatch(conn);
var cmd = new SqlBatchCommand("DELETE FROM dbo.ReproItems WHERE Id = @id");
cmd.Parameters.AddWithValue("@id", i);
batch.BatchCommands.Add(cmd);
using var cts = new CancellationTokenSource();
var spin = i % 400; // vary the moment the cancellation hits
var cancelTask = Task.Run(() => { Thread.SpinWait(spin * 20); cts.Cancel(); });
try { await batch.ExecuteNonQueryAsync(cts.Token); }
catch (ArgumentOutOfRangeException ex) { if (aoore++ == 0) Console.WriteLine(ex); }
catch { other++; }
await cancelTask;
}
Console.WriteLine($"ArgumentOutOfRangeException: {aoore}, other exceptions: {other}");
Result of one run: 6204 completed, 4429 cancelled as expected, 8925 ArgumentOutOfRangeException.
Expected behavior
A cancellation exception (as SqlCommand.ExecuteNonQueryAsync throws), never ArgumentOutOfRangeException.
Further technical details
- Microsoft.Data.SqlClient 7.1.1. The code is unchanged on
main(TdsParser.ThrowExceptionAndWarning,SqlCommand.GetBatchCommand/GetCurrentBatchIndex). - .NET 10, Windows 11, SQL Server Express LocalDB.
- Lingua principale
- C#
- Stelle
- 1k
- Fork
- 352
- Merge medio
- 2g 18h
- PR unite (30g)
- 133
Preparare l'ambiente
Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.
- Nessun Dockerfile né file Docker Compose
- Ha un modello di pull request
- Leggi la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di dotnet/SqlClient
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 62/100
dotnet/SqlClient#5061 · 1 commento ·
I maintainer di solito rispondono entro 1 giorno
-
Sync ExecuteReader on an STA thread deadlocks against a StateChange handler that marshals to the UI thread (OpenAsyncRetry path)Forse di nuovo libera @mdaigle l’ha presa 56 giorni fa e non c’è nessuna pull request aperta. ApertaExternal :link:
Difficoltà 2/5 1-3 ore Idoneità per principianti 64/100
dotnet/SqlClient#4534 · 2 commenti · 1 assegnatario ·
I maintainer di solito rispondono entro 1 giorno
-
Area\Tests
Difficoltà 2/5 1-3 ore Idoneità per principianti 68/100
dotnet/SqlClient#4377 · 2 commenti ·
I maintainer di solito rispondono entro 1 giorno
-
Managed SNI: TLS handshake ignores Connect Timeout, one stalled handshake blocks every OpenAsync on the poolForse già presa @mdaigle l’ha presa 1 giorno fa. ApertaArea\Managed SNI
dotnet/SqlClient#5045 · 2 commenti · 1 assegnatario ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 4/5 3-5 giorni Idoneità per principianti 35/100
dotnet/SqlClient#5040 · 9 commenti ·
I maintainer di solito rispondono entro 1 giorno
Tutte le issue di dotnet/SqlClient
Issue simili
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
-
area:repo elsa 3 prio low triaged type:bug
Difficoltà 2/5 1-3 ore Idoneità per principianti 72/100
elsa-workflows/elsa-core#9258 ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 1/5 Meno di un'ora Idoneità per principianti 90/100
iokode/OpinionatedFramework#140 ·
-
accessibility effort: small enhancement
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
pedersebastian/CustomBossChallenge#185 ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100