Repository navigation
Description
Early cancellation of a table-lock-blocked INSERT can remain pending until holder release
No conclusion is being drawn about whether the provider, transport or SQL engine causes the delay.
Environment and results
macOS, Azure SQL Database (reported engine version 12.0.2000.8), MARS false, pooling true.
Microsoft.Data.SqlClient.Extensions.Azure is aligned with each provider version. The net9.0
provider asset is selected for both target frameworks. No application framework or domain code
is referenced. All combinations below reproduced the same symptom in sequential runs.
| Runtime / SqlClient | Completed after cancellation within 10 seconds | Timed out |
|---|---|---|
| .NET 9.0.20 / 7.0.2 | 55 | 5 |
| .NET 9.0.20 / 7.0.3 | 53 | 7 |
| .NET 10.0.12 / 7.0.2 | 53 | 7 |
| .NET 10.0.12 / 7.0.3 | 52 | 8 |
Each row is 60 diagnostic cases: 30 request cancellation 0/1/5/10/25/100 ms after starting the
INSERT operation; 30 request cancellation after sys.dm_exec_requests confirms the writer is
blocked by the exact holder. Every timeout was in the early group. Every observed-blocking case
completed within the bound. Every case verified rollback. Timely completions reported a
SqlException with Number 0 and “Operation cancelled by user”; the harness also permits
OperationCanceledException. These are diagnostic outcomes, not an assertion of a particular
SqlClient exception contract.
A prior no-OUTPUT control also reproduced six timeouts in 30 early-cancellation cases.
A separate initial matrix startup failed with Azure SQL 40613 before any table/test was created;
the successful-connection rerun is reported above, with no startup retry hidden in these counts.
Expected and observed
A reader holds a shared table lock inside a transaction on an owned temporary table. A second
transaction attempts an INSERT. After the caller requests cancellation, the INSERT can remain
pending past 10 seconds, still waiting LCK_M_IX behind the original holder. When the holder is
rolled back, the operation finishes and its own transaction rollback leaves the table unchanged.
No session is killed and no application data is touched.
A previous metadata-only client stream capture recorded an attention write returning about
0.23 ms after the cancellation request in a failing sample. Server Extended Events showed the
INSERT completing and an attention event only after holder release roughly ten seconds later.
The attention event does not establish packet arrival time; client and server clocks were not
assumed synchronized. The client wrapper changes timing, but an uninstrumented control also
reproduces. This is not conclusively assigned to issue 4424 or any specific internal path.
Reproduction
The generic program below is derived from the executed probe. The only adaptations remove local
user-secret/target identifiers in favor of environment inputs and remove optional tracing helpers.
This generic form builds on net9.0 with 7.0.3; live execution evidence above uses the local guarded
form. Use only an isolated test database where temporary-table diagnostics are authorized.
Never include connection strings or credentials in issue output.
Set SQL_CANCEL_REPRO_CONNECTION locally and SQL_CANCEL_REPRO_DATABASE to the matching test
database name. Run dotnet run; dotnet run -- no-output exercises the 30-case no-OUTPUT control.
Change TargetFramework and both aligned SqlClient package versions to compare combinations.
The process intentionally exits 1 on a timeout after normal cleanup. Allow cleanup to finish.
Would additional provider/server events distinguish delayed attention processing from a transport
problem here? Is there a known fix or supported way to preserve prompt cancellation and completed
rollback for this early-dispatch case?
Project file
<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net9.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup><ItemGroup><PackageReference Include="Microsoft.Data.SqlClient" Version="7.0.3"/><PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="10.0.11"/><PackageReference Include="Microsoft.Data.SqlClient.Extensions.Azure" Version="7.0.3"/></ItemGroup></Project>Program.cs
using System.Diagnostics;
using Microsoft.Data.SqlClient;
// Use only an isolated development/test database where temporary-table diagnostics are permitted.
var connectionString=Environment.GetEnvironmentVariable("SQL_CANCEL_REPRO_CONNECTION")
?? throw new InvalidOperationException("Set SQL_CANCEL_REPRO_CONNECTION locally; never publish it.");
var expectedDatabase=Environment.GetEnvironmentVariable("SQL_CANCEL_REPRO_DATABASE")
?? throw new InvalidOperationException("Set SQL_CANCEL_REPRO_DATABASE to confirm the test target.");
var b=new SqlConnectionStringBuilder(connectionString);
if(b.InitialCatalog!=expectedDatabase)throw new InvalidOperationException("Unexpected database target");
b.ConnectTimeout=60;
Console.WriteLine($"Runtime={System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription}; Driver={FileVersionInfo.GetVersionInfo(typeof(SqlConnection).Assembly.Location).ProductVersion}; MARS={b.MultipleActiveResultSets}; Pooling={b.Pooling}");
var name="##IAMCancel_"+Guid.NewGuid().ToString("N");
await using var owner=new SqlConnection(b.ConnectionString);await owner.OpenAsync();
async Task<object?> Scalar(SqlConnection c,SqlTransaction? t,string sql,CancellationToken ct=default){await using var q=new SqlCommand(sql,c,t){CommandTimeout=30};return await q.ExecuteScalarAsync(ct);}
await Scalar(owner,null,$"CREATE TABLE {name}(Id int NOT NULL PRIMARY KEY,Value int NOT NULL); INSERT {name} VALUES(1,0);");
int failed=0,passed=0;
try
{
for(int i=0;i<(args.Contains("no-output")?30:60);i++)
{
var delay=new[]{0,1,5,10,25,100}[i%6];
await using var holder=new SqlConnection(b.ConnectionString);await holder.OpenAsync();
await using var writer=new SqlConnection(b.ConnectionString);await writer.OpenAsync();
await using var tx=(SqlTransaction)await holder.BeginTransactionAsync();
await Scalar(holder,tx,$"SELECT COUNT(*) FROM {name} WITH(TABLOCK,HOLDLOCK);");
using var ct=new CancellationTokenSource();
async Task Write()
{
await using var wt=(SqlTransaction)await writer.BeginTransactionAsync();
try {await Scalar(writer,wt,args.Contains("no-output")?$"INSERT {name} VALUES(2,1);":$"INSERT {name} OUTPUT inserted.Id VALUES(2,1);",ct.Token);ct.Token.ThrowIfCancellationRequested();}
finally {await wt.RollbackAsync();}
}
var sw=Stopwatch.StartNew();var pending=Write();
// Match immediate cancellation and cancellation during a confirmed server lock wait.
if(i>=30)
{
var deadline=DateTime.UtcNow.AddSeconds(5);bool observedBlocked=false;
while(DateTime.UtcNow<deadline)
{
var wait=await Scalar(owner,null,$"SELECT COUNT(*) FROM sys.dm_exec_requests WHERE session_id={writer.ServerProcessId} AND blocking_session_id={holder.ServerProcessId};");
if((int)wait!>0){observedBlocked=true;break;}
await Task.Delay(5);
}
if(!observedBlocked)throw new Exception("Expected server lock wait not observed");
}
await Task.Delay(delay);
var cancelAt=DateTime.UtcNow;var cancel=ct.CancelAsync();string outcome="";
try
{
await cancel.WaitAsync(TimeSpan.FromSeconds(10));
try{await pending.WaitAsync(TimeSpan.FromSeconds(10));outcome="unexpected-success";}
catch(OperationCanceledException){outcome="cancelled";}
catch(SqlException ex)when(ct.IsCancellationRequested){outcome="sql-cancelled";Console.WriteLine($"SQL error number={ex.Number} state={ex.State} class={ex.Class} message={ex.Message}");}
catch(TimeoutException){outcome="timeout";}
if(outcome=="timeout")
{
await using var q=new SqlCommand($"SELECT session_id,status,command,wait_type,blocking_session_id FROM sys.dm_exec_requests WHERE session_id={writer.ServerProcessId}",owner);
await using var r=await q.ExecuteReaderAsync();while(await r.ReadAsync())Console.WriteLine($"WAIT {r[0]} {r[1]} {r[2]} {r[3]} {r[4]}");
}
}
finally
{
await tx.RollbackAsync();await cancel;
try{await pending;}catch(OperationCanceledException){}catch(SqlException)when(ct.IsCancellationRequested){}
}
var state=(int)(await Scalar(owner,null,$"SELECT COUNT(*) FROM {name} WHERE Id=1 AND Value=0;"))!;
var count=(int)(await Scalar(owner,null,$"SELECT COUNT(*) FROM {name};"))!;
if(state!=1||count!=1)throw new Exception("Rollback mismatch");
if(outcome is "cancelled" or "sql-cancelled")passed++;else failed++;
Console.WriteLine($"CASE {i} confirmedWait={i>=30} delay={delay} outcome={outcome} cancelAt={cancelAt:O} writer={writer.ServerProcessId} elapsed={sw.ElapsedMilliseconds}ms rollback=verified");
}
}
finally{await Scalar(owner,null,$"DROP TABLE {name};");Console.WriteLine("Owned temporary table dropped: "+name);}
Console.WriteLine($"TOTAL passed={passed} failed={failed}");
Environment.ExitCode=failed==0?0:1;Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsIn progress
Activity
github-actions commentedon Sep 15, 2026
test comment
bullmurf commentedon Sep 15, 2026
Additional controlled result: the early cancellation stall also reproduces with explicit
SqlCommand.Cancel()whileExecuteScalarAsyncreceivesCancellationToken.None.Using .NET 9.0.20 and Microsoft.Data.SqlClient / Extensions.Azure 7.0.2 against Azure SQL Database, I ran 48 alternating token/explicit-cancel cases. MARS was disabled and pooling enabled. Unlike the earlier harness, the writer transaction was fully opened before starting the INSERT and scheduling either cancellation path.
The temporary-table/shared-holder-lock setup and rollback checks were retained. The invocation difference was:
SqlCommand.Cancel()Each timeout showed the INSERT still suspended on
LCK_M_IXbehind the harness's own holder. Cancellation-request completion and operation completion were separately bounded at ten seconds. Releasing only the owned holder allowed the operation to drain, followed by writer rollback. All 48 unchanged-control-row/count checks passed; the temporary table was dropped and post-run inventory found no probe tables or remaining probe sessions. Timeouts remained failures.This establishes that the symptom can occur without an execution cancellation token and after transaction opening. It does not establish whether the cause is in the driver, transport, or engine, or imply comparative reliability from these small timing samples. Explicit cancellation is not a validated workaround. The confirmed-blocking control still completed in every case.
What client/server instrumentation would best distinguish attention receipt from subsequent handling in this early window? Is there a specific supported configuration or targeted regression test you would recommend for the next comparison? I have not changed application cancellation behavior or adopted a dependency upgrade as a remedy.
mdaigle commentedon Sep 23, 2026
Hi @bullmurf , I believe this will be addressed by #4435.