Repository navigation
Fix SqlTransaction.Dispose racing the close of a broken connection - #4972
Conversation
…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
|
Azure Pipelines: There may be pipelines that require an authorized user to comment /azp run to run. |
|
/azp run |
|
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.
|
The failing CI jobs were the new The tests connect through The other failures in that run ( Could a maintainer set the milestone to |
|
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. |
|
/azp run |
|
Azure Pipelines: Successfully started running 2 pipeline(s). 1 pipeline(s) were filtered out due to trigger conditions. |
…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 Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
/azp run |
|
Azure Pipelines: Successfully started running 2 pipeline(s). 1 pipeline(s) were filtered out due to trigger conditions. |
There was a problem hiding this comment.
🔵 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
…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]>

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:TdsParser.ThrowExceptionAndWarning(asyncClose: true), which runsClose()fromTask.Factory.StartNew.OnTimeoutCore's delayed continuation, which callsTrySetException, thenBreakConnection().The caller's
usingblock or catch disposes the transaction concurrently with that close.SqlInternalTransaction.Dispose(bool)checks_innerConnection != null, thenRollback()dereferences_innerConnectionagain, along with its_parserthroughIsLockedForBulkCopy. Meanwhile the close sets both to null, so the dispose throwsNullReferenceException. If the connection is broken but the close has not run yet,ValidateConnectionForExecutethrowsInvalidOperationException("The connection is closed"). Both are raised outside thetrythat honours_disposing, so they escapeDispose()and replace the caller's originalSqlException.The fix:
SqlInternalTransaction.Rollback()reads_innerConnectiononce. If the transaction is already zombied, there is nothing to roll back and it returns.Rollback()returns without sending anything. The server ends the transaction with the session, and the connection's own close zombies the transaction.ExecuteTransactionalready treats a rollback on a doomed connection as a no-op.SqlConnectionInternal.IsLockedForBulkCopyno 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()throwingNullReferenceExceptionorInvalidOperationExceptionwhen 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 (
_innerConnectioncleared by a concurrent close) inCheckTransactionLevelAndZombie()/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 pendingExecuteNonQueryAsyncinsideBeginTransaction()throughProxyServer, usingPauseCopying()for the unacknowledged timeout andKillAllConnections()for the network failure. Each then disposes the transaction:Dispose_ConnectionClosedAfterUnacknowledgedTimeout_DoesNotThrowNullReferenceExceptionDispose_ConnectionClosedAfterNetworkFailure_DoesNotThrowNullReferenceExceptionDispose_CloseStillPendingAfterUnacknowledgedTimeout_DoesNotThrowInvalidOperationExceptionDispose_CloseStillPendingAfterNetworkFailure_DoesNotThrowInvalidOperationExceptionThe tests are deterministic and need no product test hook:
DbConnectionInternal.CloseConnectiontakeslock (this)), so the driver's own background close blocks before it touches the transaction.EventListeneron the driver's scope trace (keywordScope, asDatabaseContextReconnectionTestsdoes withTrace) reacts to theSqlInternalTransaction.Rollback | APIevent. That event is written afterDispose(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.The first commit adds the tests and the second adds the fix. Local results, SQL Server 2016:
main), all 4 tests fail with the exceptions listed above.TransactionTestpasses.SqlCommandCancelTestshows the same results asmain, except for one named-pipe login timeout that passed on two reruns. Its other local failures need the Northwind database or named pipes.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 (
ReadSniErrorcallsBreakConnection()beforeThrowExceptionAndWarning(), and the non-async close path runs inline), so no background close can race the dispose there.SqlTransactionhas noDisposeAsyncoverride;DbTransaction.DisposeAsync()callsDispose(), which these tests cover.Guidelines
Please review the contribution guidelines before submitting a pull request: