Repository navigation
Description
Under certain circumstances, when a combination of SqlCommands and transactional WCF calls is being run in a massively parallel manner, the current TransactionScope is occasionally "left over", SqlCommands do not get attached to it and therefore their updates are successfully committed, while the TransactionScope is rolled back. This leads to severe data corruption in a Line-of-Business application of one of our corporate customers.
Stable repro is outlined in this test project: https://github.com/scale-tone/InconsistencyDemo. See more detailed instructions on how to run it there. To reveal the issue more quickly, start and stop LoopHammer console app several times.
The LoopHammer console app emulates a message processing, consisting of the following steps:
- Creating a TransactionScope.
- As part of that TransactionScope, executing a couple of SQL statements against a local DB.
- As part of that TransactionScope, making a transactional WCF call, which fails with an exception. The call forces the transaction to be promoted to a distributed one. The exception causes the entire TransactionScope to be rolled back (including the above SQL statements).
This algorithm is executed multiple times, in parallel (just in the way the real message processing service operates). Note that the repro code only creates one TransactionScope and doesn't explicitly mix it with SqlTransactions or any other nested transactions.
Expected behavior
The distributed transaction is rolled back entirely, nothing is written to DB.
Actual behavior
After seconds to minutes of normal execution the WCF call fails with the following (not expected!) exception:
System.ServiceModel.ProtocolException: The transaction has aborted. ---> System.Transactions.TransactionAbortedException: The transaction has aborted. ---> System.Transactions.TransactionPromotionException: Failure while attempting to promote transaction. ---> Microsoft.Data.SqlClient.SqlException: The PROMOTE TRANSACTION request failed because there is no local transaction active.
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, 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.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at Microsoft.Data.SqlClient.TdsParser.TdsExecuteTransactionManagerRequest(Byte[] buffer, TransactionManagerRequestType request, String transactionName, TransactionManagerIsolationLevel isoLevel, Int32 timeout, SqlInternalTransaction transaction, TdsParserStateObject stateObj, Boolean isDelegateControlRequest) at Microsoft.Data.SqlClient.SqlInternalConnectionTds.ExecuteTransactionYukon(TransactionRequest transactionRequest, String transactionName, IsolationLevel iso, SqlInternalTransaction internalTransaction, Boolean isDelegateControlRequest) at Microsoft.Data.SqlClient.SqlDelegatedTransaction.Promote() --- End of inner exception stack trace --- at Microsoft.Data.SqlClient.SqlDelegatedTransaction.Promote() at System.Transactions.TransactionStatePSPEOperation.PSPEPromote(InternalTransaction tx) at System.Transactions.TransactionStateDelegatedBase.EnterState(InternalTransaction tx) --- End of inner exception stack trace --- at System.Transactions.TransactionStateAborted.CheckForFinishedTransaction(InternalTransaction tx) at System.Transactions.Transaction.Promote() at System.Transactions.TransactionInterop.ConvertToOletxTransaction(Transaction transaction) at System.Transactions.TransactionInterop.GetTransmitterPropagationToken(Transaction transaction) at System.ServiceModel.Transactions.WsatTransactionFormatter.WriteTransaction(Transaction transaction, Message message) at System.ServiceModel.Channels.TransactionChannel1.WriteTransactionToMessage(Message message, TransactionFlowOption txFlowOption)
--- End of inner exception stack trace ---
Server stack trace:
at System.ServiceModel.Channels.TransactionChannel1.WriteTransactionToMessage(Message message, TransactionFlowOption txFlowOption) at System.ServiceModel.Channels.TransactionChannel1.WriteTransactionDataToMessage(Message message, MessageDirection direction)
at System.ServiceModel.Channels.TransactionRequestChannelGeneric`1.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at DemoService.WcfAgents.IService1.DoWork(String correlationId)
at DemoService.WcfAgents.Service1Client.DoWork(String correlationId)
at LoopHammer.DostuffHandler.MakeTransactionalWcfCallThatThrows()
at LoopHammer.DostuffHandler.Handle()
This happens presumably because at the moment of promotion attempt, the TransactionScope (not itself, but some underlying internal transaction object) appears to be in an aborted state already. Because it appears to be in that state, the above SQL statements do not get attached to it and got committed immediately. So the TransactionPromotionException is just a visible part of the problem, while the actual issue occurs somewhere in between TransactionScope creation and execution of SqlCommands. We're able to detect that faulty state of TransactionScope beforehand, by executing "select @@trancount" against the DB - in a failure case it appears to be 0 (normally should be 1).
WORKAROUND: if we disable SqlConnection pooling (add "Pooling=false" to connection string), the problem disappears. This makes us thinking, that the bug is somewhere in connection sharing mechanism. Probably, a connection is sometimes not fully detached from one thread, and occasionally allows it to influence a TransactionScope belonging to another thread. If that is the case, then it can not only lead to data corruption but also introduce serious security issues.
The problem is reproducible with the latest Microsoft.Data.SqlClient v1.0.19269.1. Originally it was detected in System.Data.SqlClient coming from .Net Framework - see this variant of the same repro project: https://github.com/samegutt/InconsistencyDemo.
.Net Framework version doesn't matter (tried with all from 4.5.1 to 4.8).
When compiled against sources from this repo, the problem is also reproducible.
If we compile and start LoopHammer.exe in Debug mode, we immediately hit this debug assert. If we disable it, the further execution either leads to the same TransactionPromotionException OR to some others:
System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'SqlDelegatedTransaction'.
at Microsoft.Data.SqlClient.SqlDelegatedTransaction.GetValidConnection()
at Microsoft.Data.SqlClient.SqlDelegatedTransaction.Rollback(SinglePhaseEnlistment enlistment)
at System.Transactions.TransactionStateDelegatedAborting.EnterState(InternalTransaction tx)
at System.Transactions.Transaction.Rollback()
at System.Transactions.TransactionScope.InternalDispose()
at System.Transactions.TransactionScope.Dispose()
at LoopHammer.DostuffHandler.Handle()
or even to:
Microsoft.Data.SqlClient.SqlException (0x80131904): The Microsoft Distributed Transaction Coordinator (MS DTC) has cancelled the distributed transaction.
at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) in C:\projects\CSA\temp\SqlClient\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlConnection.cs:line 2103 at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) in C:\projects\CSA\temp\SqlClient\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlInternalConnection.cs:line 814
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) in C:\projects\CSA\temp\SqlClient\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\TdsParser.cs:line 1572
at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) in C:\projects\CSA\temp\SqlClient\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\TdsParser.cs:line 2792
at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData() in C:\projects\CSA\temp\SqlClient\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlDataReader.cs:line 1310
at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData() in C:\projects\CSA\temp\SqlClient\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlDataReader.cs:line 275
at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted) in C:\projects\CSA\temp\SqlClient\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlCommand.cs:line 5550
at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest) in C:\projects\CSA\temp\SqlClient\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlCommand.cs:line 5312
at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) in C:\projects\CSA\temp\SqlClient\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlCommand.cs:line 4907
at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) in C:\projects\CSA\temp\SqlClient\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlCommand.cs:line 4762
at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) in C:\projects\CSA\temp\SqlClient\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlCommand.cs:line 2401
at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader() in C:\projects\CSA\temp\SqlClient\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlCommand.cs:line 2322
at LoopHammer.DostuffHandler.GetTransactionDetails()
at LoopHammer.DostuffHandler.Handle()
ClientConnectionId:48c113c4-6fcd-4082-85bf-0f39023375bf
Error Number:1206,State:137,Class:18
A transactional WCF call is the essential part of the scenario. Surprisingly, forcing a transaction promotion by other means (e.g. by accessing another DB) does not lead to the same problem
For some reason, the MaxDegreeOfParallelism set to 4 maximizes chances for the issue to appear. Experiments with connection pool size didn't show any differences.
As mentioned above, the issue causes a serious damage to the customer's large LoB system. Furthermore, concerns are that it might indicate a severe security issue (multiple threads being able to influence each other's transaction flow).
Activity
cheenamalhotra commentedon Oct 2, 2019
Hi @scale-tone
Just to let you know I was able to reproduce the issue from the provided repro, and currently investigating into it.
[-]System.ServiceModel.ProtocolException ---> System.Transactions.TransactionAbortedException ---> System.Transactions.TransactionPromotionException ---> Microsoft.Data.SqlClient.SqlException: The PROMOTE TRANSACTION request failed because there is no local transaction active[/-][+]SqlException: The PROMOTE TRANSACTION request failed because there is no local transaction active[/+]cheenamalhotra commentedon Oct 3, 2019
Hi @scale-tone
Could you give the latest v1.1.0-preview1 version we released today a try in your repro app? I don't see the error occurring again with this release version. I'm wondering if @Wraith2 's PR #232 did the trick?
Let me know how that goes!
samegutt commentedon Oct 3, 2019
Hi, I've been working with @scale-tone on this issue, and I am still able to reproduce with the new package. However, it took a few more minutes than longer to reproduce.
ramonsmits commentedon Oct 4, 2019
I'm currently running your reproduction. How long should it run before it occurs?
samegutt commentedon Oct 4, 2019
Originally I’m able to reproduce from between 20 to 3000 iterations. With the new package, I had to wait until 5000 iterations.
Edit: query the ImportantBusinessData table with nolock, and check the Id column to get current iteration count.
cheenamalhotra commentedon Oct 4, 2019
I was able to reproduce the error before in a min (after 100 transactions), but now even after 30 mins, I don't get any errors, wondering how long should I wait for.
As you can see I've crossed 15000 transaction count, but no error so far. Test is going on.
ramonsmits commentedon Oct 4, 2019
My test run in Release, I added the duration since start to the exception logging and only logging the message property. Just after a minute it happens for the first time and after 14 minutes 15 exceptions got logged.
cheenamalhotra commentedon Oct 4, 2019
@ramonsmits The repro uses package reference 1.0.19269.1, which reproduces issue quickly.
Please test with "1.1.0-preview1.19275.1"
cheenamalhotra commentedon Oct 4, 2019
After few more mins (nearly 45 mins from beginning), I get this:
132c09b9-7c84-4adc-ab0a-5de35248d8a4 trandetails is TranCount = 2, Xact = 1, TranId = 187726, WE'RE ABOUT TO CREATE INCONSISTENT DATA 132c09b9-7c84-4adc-ab0a-5de35248d8a4 System.ServiceModel.ProtocolException: The transaction has aborted. ---> System.Transactions.TransactionAbortedException: The transaction has aborted. ---> System.Transactions.TransactionPromotionException: Failure while attempting to promote transaction. ---> Microsoft.Data.SqlClient.SqlException: The PROMOTE TRANSACTION request failed because there is no local transaction active.But here I see TranCount = 2, is that expected?
Interestingly, database table [ImportantBusinessData] contains entry:
This should not be committed ever, since the WCF call below always fails.. Transaction details: TranCount = 0, Xact = 1, TranId = 187746ramonsmits commentedon Oct 4, 2019
Running it with
1.1.0-preview1.19275.1resulted in 8 inserts in 58 minutes that should not have happened.cheenamalhotra commentedon Oct 4, 2019
I got 6 inserts in 2 hours. Looking into it.
samegutt commentedon Oct 4, 2019
@cheenamalhotra,
Trancount = 2only means that the current iteration has a transaction session leftover from another iteration, and that is is not yet aborted. If you add logging to the database, as I have in my original repo, it becomes clear that different iterations (with differentCorrelationId) has inserted logs with the sameTransId(Transidis reallyselect CURRENT_TRANSACTION_ID()). The query that illustrates this isselect TransId, count(*) from LogData group by TransId Having count(*) > 1If the insert into the
ImportantBusinessDatatable was executed whenTrancount = 2, it would at least have a transaction, and it would be rolled back when the transaction was aborted. But more often than not, the transaction is already aborted at the time of the insert toImportantBusinessData.@@trancountis at that moment 0, and we have no transaction.samegutt commentedon Oct 4, 2019
@cheenamalhotra, the reason you see different
TransIdin the Console app compared to what was incorrectly inserted into the database, is thatselect CURRENT_TRANSACTION_ID()returns a new value each time when@@trancount = 0.18 remaining items
scale-tone commentedon Dec 4, 2019
No it doesn't, @cheenamalhotra . What you're proposing is yet another workaround. Effectively your proposed line promotes the transaction into a distributed one early. While normally that transaction is being automatically promoted to a distributed one inside the MakeTransactionalWcfCallThatThrows() call (if it were not promoted at that point, the whole scenario wouldn't work).
SqlClient is expected to do that automatic promotion for us, and it is expected to do that correctly, especially it should never lead to a data loss (no matter what internal threading issues it experiences).
Besides, OK, we could add that line to this particular place in our code. Would you then expect us to pepper the entire codebase with that line (because how do we know when this early promotion is needed and when it is not?)?
We do not need another workaround, we already have one. We need an ultimate fix, which is now less important for us, but way much more important for other customers, who might not even know that they're loosing data due to this!
samegutt commentedon Dec 6, 2019
@cheenamalhotra so far, this issue is reproduced for all .NET versions since (and including) 3.0. That is the first framework with WCF, which is a key component in this setup.
I have pushed a branch to my repo with the needed changes for that version.
The exception thrown in .NET 3.0 example:
cheenamalhotra commentedon Dec 6, 2019
Hi @jimcarley @corivera @geleems
Could you take a look and provide some insights for this issue reported by customer as it seems to be reproduced in System.Data.SqlClient with all .NET framework versions of starting 3.0 as mentioned above.
ramonsmits commentedon Dec 10, 2019
I tried the
TransactionInterop.GetTransmitterPropagationToken(Transaction.Current);approach after connecting the resource but it seems that this really must be done before using the first resource manager.This means that this workaround requires the ability to control the creation of the TransactionScope.
jimcarley commentedon Dec 10, 2019
I have only skimmed over this thread. But when I saw the comment about "early" promotion of the transaction, it made me think of something.
We had a situation where one of the enlistments, either volatile or durable, was an "EnlistDuringPrepareRequired" enlistment. This means that after Commit processing was started, a new enlistment might be attempted during "Phase 0" of the commit. When the transaction commit was delegated to SQL Server through the EnlistPromotableSinglePhase enlistment, there was a problem. SQL Server would start the commit processing by issuing the commit request to MSDTC and MSDTC would discover the Phase0 enlistment and tell that enlistment to prepare first. As part of the prepare processing, that Phase0 enlistment would try to create a new enlistment with SQL Server. But SQL Server would reject it because it thought the transaction was already in the process of committing. In other words, SQL Server didn't support the idea of a Phase0 enlistment.
I don't know if this was ever resolved. The workaround for this was to force "early" promotion of the transaction, before the first EnlistPromotableSinglePhase was attempted by SqlClient. That way, the commit processing would not be delegated to SQL Server, but rather go directly to MSDTC.
But it doesn't sound like this current issue is related to that. This definitely sounds like some sort of issue with the connection pooling. And it also sounds related to the situation where the transaction aborts before the first SQL operation and so a separate SQL transaction is used for the SQL operations, but when the WCF work is attempted, the aborted System.Transactions transaction is discovered. The SQL transaction(s) aren't affected and therefore commit.
Can someone modify the repro to have the application "register" for the Transaction.Completed event and then log the time and outcome when that event is fired? This might help narrow down why the transaction might be aborting early, before the SQL enlistments are made?
Also, I don't recall if there is some option to specify in the connection string that disables the automatic "switch" to using a SQL Transaction if the System.Transactions transaction is not usable at the time of the enlistment.
samegutt commentedon Dec 12, 2019
@jimcarley
When handling the
TransactionCompletedevent in my repo, the problem never occurs. Meaning, all transactions are properly rolled back.ramonsmits commentedon Dec 13, 2019
I added the following and issue is still happening:
Reported status is always
Aborted.The only way to currently solve this is by adding
cheenamalhotra commentedon Dec 31, 2019
Hi @jimcarley
I've been debugging over and over this issue and I've noticed a strange behaviour with Pooled Connections. I captured SQL Profiles for 1 round of cycle, for below 3 scenarios:
All further loops lead to same pattern over and over again.
As you can see when working with pooled connection, the local transaction does not propagate until the end of cycle. On debugging it seems to happen when
ServiceClient.DoWork()is called. Since the service is made to throw exception, the cycle terminates with propagated transaction.I looked into ServiceClient code, and found the tag used on
IService1.DoWork:[System.ServiceModel.TransactionFlowAttribute(System.ServiceModel.TransactionFlowOption.Allowed)]Upon removing this tag (only for investigation purposes), I see a different pattern where propagation does not happen and transaction is rollbacked when exception occurs:
Which makes sense since WPF service forces transaction promotion in this case. Also attached traces below, that can aid in investigations.
Traces.zip
At this point I'm not sure what's expected behaviour since this issue has occurred only in WPF applications like the repro and this issue has always been observed with all versions of SqlClient. To me it seems like the transactions should be promoted to DTC at the first place, but since they are pooled connections, their behaviour is different here.
Appreciate your insights on the same!
cheenamalhotra commentedon Dec 31, 2019
Another note I'd like to add specifically for pooled connections:
[This happens in the second round and onwards - post Promote Tran triggered by WCF Call]
When the connection is grabbed from pool and re-activated, during activation, the server first sends "EnvChange token Type 17: Transaction Ended" followed by "EnvChange token Type 8: Begin". As per Microsoft documentation:
The driver somehow doesn't know how to handle this state, and marks it as "Unknown" here:
https://github.com/dotnet/SqlClient/blob/master/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs#L2504-L2505
After which the local copy of pending transaction is re-used for addressing Begin transaction.
This activation of pooled connection also brings a "Warning" from SQL Server:
"The transaction active in this session has been committed or aborted by another session." which is not thrown since it is not an error.
ramonsmits commentedon May 1, 2020
@scale-tone Did you verify if 2.0.0-preview3 resolved your issue?
scale-tone commentedon May 6, 2020
@ramonsmits , I don't see any data losses happening anymore, yes.
But instead I'm occasionally observing this beautiful NRE:
@cheenamalhotra , as usual, you can easily see this yourself, if you compile the repro against SqlClient 2.0.0-preview3 and run/stop/run it several times.
So the bug isn't fully fixed still.
cheenamalhotra commentedon May 14, 2020
@scale-tone
We found it was introduced with the fix when logging information, now fixed it with #563
Thanks for letting us know!
Please give the current 'master' branch a try and let us know if you find any other concerns.
rygwdn commentedon Oct 8, 2020
@cheenamalhotra Do you know if this change be back-ported to
System.Data.SqlClientin .Net Framework (4.8) as well?cheenamalhotra commentedon Oct 8, 2020
@saurabh500 Could you provide an update?