Skip to content

Fix SqlTransaction.Dispose racing the close of a broken connection - #4972

Merged
mdaigle merged 5 commits into
dotnet:mainfrom
MaceWindu:dev/macewindu/transaction-dispose-race
Nov 12, 2026
Merged

mdaigle merged 5 commits into
dotnet:mainfrom
MaceWindu:dev/macewindu/transaction-dispose-race

Conversation

@MaceWindu

Copy link
Copy Markdown
Contributor

Description

SqlTransaction.Dispose() can throw when it runs while the driver is closing a broken connection. When an async command fails fatally inside a local transaction, the driver faults the command's task first and closes the connection afterwards on another thread:

  • A network failure goes through TdsParser.ThrowExceptionAndWarning(asyncClose: true), which runs Close() from Task.Factory.StartNew.
  • A timeout whose attention is never acknowledged goes through OnTimeoutCore's delayed continuation, which calls TrySetException, then BreakConnection().

The caller's using block or catch disposes the transaction concurrently with that close. SqlInternalTransaction.Dispose(bool) checks _innerConnection != null, then Rollback() dereferences _innerConnection again, along with its _parser through IsLockedForBulkCopy. Meanwhile the close sets both to null, so the dispose throws NullReferenceException. If the connection is broken but the close has not run yet, ValidateConnectionForExecute throws InvalidOperationException ("The connection is closed"). Both are raised outside the try that honours _disposing, so they escape Dispose() and replace the caller's original SqlException.

The fix:

  • SqlInternalTransaction.Rollback() reads _innerConnection once. If the transaction is already zombied, there is nothing to roll back and it returns.
  • When disposing on a connection that is doomed, broken or closed, Rollback() returns without sending anything. The server ends the transaction with the session, and the connection's own close zombies the transaction. ExecuteTransaction already treats a rollback on a doomed connection as a no-op.
  • SqlConnectionInternal.IsLockedForBulkCopy no longer dereferences a parser that a concurrent dispose has released.

An explicit Rollback() on an open connection behaves as before. No public API changes.

Suggested release note: Fixed SqlTransaction.Dispose() throwing NullReferenceException or InvalidOperationException when it races the close of a connection broken by a network failure or an unacknowledged command timeout.

Issues

Fixes #4971

Related: #2879 and #1121 report the same kind of race (_innerConnection cleared by a concurrent close) in CheckTransactionLevelAndZombie() / GetServerTransactionLevel(). This PR does not change that path.

Testing

New ManualTests in SQL/TransactionTest/TransactionDisposeRaceTest.cs (Set 3). Each test breaks the connection under a pending ExecuteNonQueryAsync inside BeginTransaction() through ProxyServer, using PauseCopying() for the unacknowledged timeout and KillAllConnections() for the network failure. Each then disposes the transaction:

Test Order Before the fix
Dispose_ConnectionClosedAfterUnacknowledgedTimeout_DoesNotThrow while the close runs NullReferenceException
Dispose_ConnectionClosedAfterNetworkFailure_DoesNotThrow while the close runs NullReferenceException
Dispose_CloseStillPendingAfterUnacknowledgedTimeout_DoesNotThrow before the close runs InvalidOperationException
Dispose_CloseStillPendingAfterNetworkFailure_DoesNotThrow before the close runs InvalidOperationException

The tests are deterministic and need no product test hook:

  • The test thread holds the internal connection's close lock (DbConnectionInternal.CloseConnection takes lock (this)), so the driver's own background close blocks before it touches the transaction.
  • For the "while the close runs" tests, an EventListener on the driver's scope trace (keyword Scope, as DatabaseContextReconnectionTests does with Trace) reacts to the SqlInternalTransaction.Rollback | API event. That event is written after Dispose(bool)'s null check and before the dereference. The listener releases the lock and waits for the close to finish. It acts only on the disposing thread.
  • Each "while the close runs" test also asserts that the close ran inside that window, so a run that missed the race fails instead of passing vacuously.

The first commit adds the tests and the second adds the fix. Local results, SQL Server 2016:

  • On the first commit (unmodified main), all 4 tests fail with the exceptions listed above.
  • With the fix, all 4 pass on net10.0 (4 consecutive runs) and on net462.
  • TransactionTest passes. SqlCommandCancelTest shows the same results as main, except for one named-pipe login timeout that passed on two reruns. Its other local failures need the Northwind database or named pipes.
  • UnitTests filtered on Transaction (101 tests) pass on net10.0.

A timeout test takes about 7 s, because the driver waits its fixed 5 s attention timeout before breaking the connection. The network-failure tests take under 1 s.

Sync API: a synchronous command breaks and closes the connection on the caller's thread before it throws (ReadSniError calls BreakConnection() before ThrowExceptionAndWarning(), and the non-async close path runs inline), so no background close can race the dispose there. SqlTransaction has no DisposeAsync override; DbTransaction.DisposeAsync() calls Dispose(), which these tests cover.

  • Tests added or updated
  • Both sync and async code paths tested (where applicable; see above)
  • Public API changes documented (none)
  • Verified against customer repro (the repro in the issue)
  • No breaking changes introduced

Guidelines

Please review the contribution guidelines before submitting a pull request:

…nection

Each test breaks the connection while an async command is pending in a
transaction. The break goes through ProxyServer, either as a timeout whose
attention the server never acknowledges or as a network reset. The driver
faults the command first and closes the connection afterwards on another
thread.

The tests hold that close at the internal connection's close lock. They
dispose the transaction either before the close runs, or while it runs. A
SqlClient scope-trace listener on the disposing thread places the second
case between Dispose's null check and Rollback's dereference.

On main, the dispose throws InvalidOperationException ("The connection is
closed") or NullReferenceException from SqlInternalTransaction.Rollback().
The background close of a broken connection zombies the transaction and
releases the parser. SqlInternalTransaction.Rollback() read _innerConnection
several times without a lock, so a dispose that raced that close could throw.

Rollback() now reads the connection once and returns if the transaction is
already zombied. When disposing on a connection that is doomed, broken or
closed, it returns without a rollback. Nothing can be sent there, and the
server ends the transaction with the session. IsLockedForBulkCopy no longer
dereferences a released parser.

Fixes dotnet#4971
Copilot AI balanced review requested due to automatic review settings November 3, 2026 14:23
@github-project-automation github-project-automation Bot moved this to To triage in SqlClient Board Nov 3, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.

@MaceWindu
MaceWindu marked this pull request as ready for review November 3, 2026 14:34
@MaceWindu
MaceWindu requested a review from a team as a code owner November 3, 2026 14:34
@cheenamalhotra

Copy link
Copy Markdown
Member

/azp run

@cheenamalhotra cheenamalhotra added this to the 8.0.0 milestone Nov 4, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 2 pipeline(s).
1 pipeline(s) were filtered out due to trigger conditions.

The tests connect through ProxyServer, which rewrites the data source to
127.0.0.1. On Azure SQL and on the named-instance setup the server
certificate never matches that name, so the connection failed in the
pre-login handshake before any test code ran. Skip them there, as the
other ProxyServer tests do.
Copilot AI balanced review requested due to automatic review settings November 4, 2026 12:45

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

@MaceWindu

Copy link
Copy Markdown
Contributor Author

The failing CI jobs were the new TransactionDisposeRaceTest tests on Azure SQL and on the named instance. They failed while opening the connection, before reaching any transaction code:

AuthenticationException: Certificate name mismatch. The provided 'DataSource' or 'HostNameInCertificate' does not match the name in the certificate.

The tests connect through ProxyServer, which rewrites the data source to 127.0.0.1. I added IsNotAzureServer and IsNotNamedInstance to their conditions, the same gating as the other ProxyServer tests (SqlCommandCancelTest.TimeOutDuringRead_Tcp, DataStreamTest.TimeoutDuringReadAsync_WithClosedReader_TimesOut). The localhost jobs, where these tests run, passed.

The other failures in that run (SqlSchemaInfoTest deadlock victims, ConnectionPoolTest.MaxPoolWaitForConnectionTest, IsolationLevelLeakTest pool reuse) also show up on other PRs' runs of this pipeline today.

Could a maintainer set the milestone to 8.0.0-preview1? The milestone check expects SqlClientNextVersion, and the PR is on 8.0.0.

@paulmedynski
paulmedynski requested a balanced review from Copilot November 4, 2026 13:30
@paulmedynski paulmedynski moved this from To triage to In review in SqlClient Board Nov 4, 2026
@paulmedynski

Copy link
Copy Markdown
Contributor

Hi @MaceWindu - We will take this work as part of 8.0.0, so the milestone is accurate. The check is correctly failing, so we don't merge this prematurely (we release previews from main). I'll trigger the pipelines again.

@paulmedynski

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 2 pipeline(s).
1 pipeline(s) were filtered out due to trigger conditions.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

A disposal race can still replace the original timeout exception, while unsafe test cleanup can trigger an ObjectDisposedException that masks the underlying failure.

2 open issues

Review effort: Balanced

…alidation

After an unacknowledged timeout, the attention-timeout callback faults the
command's task and marks the parser broken a few lines later. A dispose
started by the fault can pass Rollback()'s broken-connection check and then
fail in ValidateConnectionForExecute, which still throws while disposing.

Nothing observable runs in that window, so the test uses a new DEBUG-only
hook, SqlInternalTransaction.s_afterRollbackConnectionCheck, following the
existing test hooks in TdsParserStateObject. The test marks the parser
broken from the hook on the disposing thread. On this commit the dispose
throws InvalidOperationException ("The connection is closed").

Also unsubscribe BackgroundCloseGate's StateChange handler before its event
is disposed.
… validates it

If the connection breaks after Rollback() has checked it, the validation
throws. While disposing, Rollback() now returns in that case too, for the
same reason as the check: nothing can be sent, and the server ends the
transaction with the session. An explicit Rollback() still throws.
@codecov

codecov Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 67.25%. Comparing base (ddef008) to head (a45f54d).
⚠️ Report is 44 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4972      +/-   ##
==========================================
- Coverage   68.36%   67.25%   -1.12%     
==========================================
  Files         311      307       -4     
  Lines       45355    68956   +23601     
==========================================
+ Hits        31009    46378   +15369     
- Misses      14346    22578    +8232     
Flag Coverage Δ
CI-SqlClient ?
PR-SqlClient-Project 67.25% <100.00%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copilot AI balanced review requested due to automatic review settings November 4, 2026 15:09

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

@paulmedynski

Copy link
Copy Markdown
Contributor

/azp run

@paulmedynski
paulmedynski requested a balanced review from Copilot November 9, 2026 12:49
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 2 pipeline(s).
1 pipeline(s) were filtered out due to trigger conditions.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The concurrency-sensitive parser teardown was reviewed only statically, with independent test execution unavailable and required repository policies missing.

No open issues 🎉

2 resolved since last review

Review effort: Balanced

@mdaigle mdaigle self-assigned this Nov 9, 2026
@paulmedynski paulmedynski modified the milestones: 8.0.0, 8.1.0-preview1 Nov 11, 2026
@paulmedynski paulmedynski added the Hotfix 8.0.0 PRs that must be backported to release/8.0 label Nov 11, 2026
@mdaigle
mdaigle merged commit 457ed73 into dotnet:main Nov 12, 2026
129 of 132 checks passed
@github-project-automation github-project-automation Bot moved this from In review to Done in SqlClient Board Nov 12, 2026
mdaigle pushed a commit that referenced this pull request Nov 12, 2026
…4972) (#5053)

* Add tests for SqlTransaction.Dispose racing the close of a broken connection

Each test breaks the connection while an async command is pending in a
transaction. The break goes through ProxyServer, either as a timeout whose
attention the server never acknowledges or as a network reset. The driver
faults the command first and closes the connection afterwards on another
thread.

The tests hold that close at the internal connection's close lock. They
dispose the transaction either before the close runs, or while it runs. A
SqlClient scope-trace listener on the disposing thread places the second
case between Dispose's null check and Rollback's dereference.

On main, the dispose throws InvalidOperationException ("The connection is
closed") or NullReferenceException from SqlInternalTransaction.Rollback().

* Fix SqlTransaction.Dispose racing the close of a broken connection

The background close of a broken connection zombies the transaction and
releases the parser. SqlInternalTransaction.Rollback() read _innerConnection
several times without a lock, so a dispose that raced that close could throw.

Rollback() now reads the connection once and returns if the transaction is
already zombied. When disposing on a connection that is doomed, broken or
closed, it returns without a rollback. Nothing can be sent there, and the
server ends the transaction with the session. IsLockedForBulkCopy no longer
dereferences a released parser.

Fixes #4971

* Skip the transaction dispose race tests on Azure SQL and named instances

The tests connect through ProxyServer, which rewrites the data source to
127.0.0.1. On Azure SQL and on the named-instance setup the server
certificate never matches that name, so the connection failed in the
pre-login handshake before any test code ran. Skip them there, as the
other ProxyServer tests do.

* Add a test for the connection breaking between Rollback's check and validation

After an unacknowledged timeout, the attention-timeout callback faults the
command's task and marks the parser broken a few lines later. A dispose
started by the fault can pass Rollback()'s broken-connection check and then
fail in ValidateConnectionForExecute, which still throws while disposing.

Nothing observable runs in that window, so the test uses a new DEBUG-only
hook, SqlInternalTransaction.s_afterRollbackConnectionCheck, following the
existing test hooks in TdsParserStateObject. The test marks the parser
broken from the hook on the disposing thread. On this commit the dispose
throws InvalidOperationException ("The connection is closed").

Also unsubscribe BackgroundCloseGate's StateChange handler before its event
is disposed.

* Fix SqlTransaction.Dispose when the connection breaks before Rollback validates it

If the connection breaks after Rollback() has checked it, the validation
throws. While disposing, Rollback() now returns in that case too, for the
same reason as the check: nothing can be sent, and the server ends the
transaction with the session. An explicit Rollback() still throws.

Co-authored-by: MaceWindu <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Hotfix 8.0.0 PRs that must be backported to release/8.0

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

SqlTransaction.Dispose() throws NullReferenceException from SqlInternalTransaction.Rollback() when it races the background close of a broken connection

5 participants