Re-issue session isolation level on TransactionScope re-enlistment (fixes #146) - #4335
Conversation
When a pooled connection is re-checked-out inside the same System.Transactions transaction, the existing Enlist() short-circuit skipped re-issuing SET TRANSACTION ISOLATION LEVEL. sp_reset_connection_keep_transaction resets the session isolation level to the database default on Azure SQL DB, silently downgrading subsequent commands in the scope (e.g. Serializable -> Read Committed Snapshot). Fix: on the re-attach path, re-issue SET TRANSACTION ISOLATION LEVEL matching the ambient transaction's isolation level. The statement is queued onto the same TDS batch as the pending reset, so there is no extra round trip. Back-compat: gated behind AppContext switch Switch.Microsoft.Data.SqlClient.UseLegacyTransactionScopeIsolationBehavior (default false). Validated against on-prem SQL Server (no behavior change) and Azure SQL DB (downgrade gone). Adds ManualTests gated on IsAzureServer.
There was a problem hiding this comment.
Pull request overview
Fixes an Azure SQL DB-specific TransactionScope pooling regression where session isolation level can revert to the database default after transacted-pool re-checkout by re-asserting the ambient isolation level during re-enlistment.
Changes:
- Added a new AppContext switch (
Switch.Microsoft.Data.SqlClient.UseLegacyTransactionScopeIsolationBehavior) to gate the new re-assert behavior. - Updated
SqlInternalConnectionTds.Enlist(Transaction)to re-issueSET TRANSACTION ISOLATION LEVEL ...on the “same transaction” short-circuit path (intended to piggyback on the pending reset). - Added new Azure-gated ManualTests and wired them into the ManualTests project.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 4 comments.
| File | Description |
|---|---|
| src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/SqlConnectionInternal.cs | Adds re-attach logic to re-assert session isolation level when re-enlisting into the same ambient transaction. |
| src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/LocalAppContextSwitches.cs | Introduces a new AppContext switch to enable legacy behavior. |
| src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionScopeIsolationReassertTest.cs | Adds ManualTests validating isolation level stability across pooled re-opens inside a TransactionScope (Azure-only). |
| src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTests.csproj | Includes the new ManualTests source file in the build. |
| /// </summary> | ||
| private static SwitchValue s_useLegacyFailoverAlternationOnLoginSqlErrors = SwitchValue.None; | ||
|
|
||
| /// <summary> | ||
| /// The cached value of the UseLegacyTransactionScopeIsolationBehavior switch. | ||
| /// </summary> | ||
| private static SwitchValue s_useLegacyTransactionScopeIsolationBehavior = SwitchValue.None; | ||
|
|
There was a problem hiding this comment.
Fixed in 6c57f75 and 90c58a1. LocalAppContextSwitchesHelper now captures/restores s_useLegacyTransactionScopeIsolationBehavior and exposes a UseLegacyTransactionScopeIsolationBehavior accessor, and TestDefaultAppContextSwitchValues resets and asserts the new switch. After merging main I also switched the getter to GetSwitchPropertyValue to match the accessor pattern main moved to; the defaults test passes.
- SqlConnectionInternal.Enlist: guard on _parser._fResetConnection (runtime reset-pending flag) instead of _fResetConnection (static config). - ReassertSessionIsolationLevel: use ConnectionOptions.ConnectTimeout for the in-driver SET batch (matches ChangeDatabase convention) instead of timeout: 0. - LocalAppContextSwitchesHelper / LocalAppContextSwitchesTest: wire UseLegacyTransactionScopeIsolationBehavior into the RAII helper and the defaults test. - ManualTests: add LegacySwitch_PreservesAzureDowngradeBehavior negative test asserting the back-compat switch fully restores the prior Azure downgrade behavior.
…aded-dollop # Conflicts: # src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTests.csproj # src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/LocalAppContextSwitchesTest.cs
- ReassertSessionIsolationLevel: do not emit SET TRANSACTION ISOLATION LEVEL SNAPSHOT. Switching to SNAPSHOT while a transaction is active causes SQL Server to fail and roll back that transaction, and this path always runs with the preserved transaction still open. The transaction was already begun under snapshot isolation via the TM request, so there is nothing to re-assert. - Correct the Enlist comment: the queued reset piggybacks the SET batch, but the SET batch itself is an extra round trip on re-checkout. - LocalAppContextSwitchesHelper: use GetSwitchPropertyValue for UseLegacyTransactionScopeIsolationBehavior to match the accessor pattern main moved to, so the defaults test reads the resolved value instead of the uncached field. - Document the new switch in features.instructions.md. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.
Suppressed comments (2)
src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/SqlConnectionInternal.cs:2412
- The PR description states the isolation re-assert is queued onto the same batch as the pending reset with no extra round trip, but this implementation runs a synchronous
TdsExecuteSQLBatch+RunduringOpen/Enlist, which introduces an additional server round trip on the re-attach path. Please reconcile the PR description with the actual behavior, or adjust the implementation to truly piggyback without an extraOpen-time execute.
else if (!LocalAppContextSwitches.UseLegacyTransactionScopeIsolationBehavior
&& _parser._fResetConnection)
{
// Same System.Transactions transaction being re-attached to the same
// pooled physical connection (transacted-pool re-checkout inside an
// open TransactionScope). The queued sp_reset_connection_keep_transaction
// does not preserve the SQL Server session isolation level on every
// server (notably Azure SQL DB), so without re-asserting the level the
// second and later opens inside the scope would silently run at the
// database default. The queued reset piggybacks this batch's TDS
// header, so the reset itself costs nothing extra, but the SET batch
// is an additional round trip on re-checkout.
ReassertSessionIsolationLevel(transaction.IsolationLevel);
src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionScopeIsolationReassertTest.cs:19
- ManualTests in this folder are partitioned with
[Trait("Set", "3")](see TransactionTest.cs / TransactionEnlistmentTest.cs / DistributedTransactionTest.cs). This new test class is missing the trait, which can cause it to run outside the intended ManualTests set partitioning.
public static class TransactionScopeIsolationReassertTest
{
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #4335 +/- ##
==========================================
- Coverage 64.78% 62.79% -1.99%
==========================================
Files 288 283 -5
Lines 44418 67452 +23034
==========================================
+ Hits 28774 42358 +13584
- Misses 15644 25094 +9450
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:
|
Explains why the pool-return isolation-level scrub (dotnet#96) and the TransactionScope re-enlistment re-assert (dotnet#146) are opposite failures of the same sp_reset_connection inconsistency, and why neither fix subsumes the other. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 6a5c2db9-5c3a-4cbb-9ae5-d120b6aa1988
|
Added a design note at Short version: both bugs come from the same fact —
Neither subsumes the other: this PR only fires on the The two PRs do overlap textually (same file, same switches helper, same test folder). Suggested sequencing is #4330 first, then rebase this one on top and settle the open perf question (unconditional SET vs. Azure-gated vs. deferring the SET to prefix the user's next batch). |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 7 changed files in this pull request and generated no new comments.
Suppressed comments (1)
src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionScopeIsolationReassertTest.cs:18
- ManualTests are partitioned by the xUnit
Settrait (see build.proj TestSetFilter). This new test class doesn’t declare aSet, so it may be skipped when CI runs specific manual test sets (e.g., Set=1/2/3). Add the same[Trait("Set", "3")]used by other transaction manual tests so these new tests reliably execute in the manual test matrix.
public static class TransactionScopeIsolationReassertTest
Summary
Fix #146 —
TransactionScopeambient isolation level is silently downgraded after the first pooled connection re-checkout on Azure SQL DB.Repro
On on-prem SQL Server the level survives and all three opens report
serializable. On Azure SQL DB the second and subsequent opens report the database default isolation (e.g.read committed snapshot).Root cause
Open()inside the scope enlists the connection and sendsSET TRANSACTION ISOLATION LEVEL <ambient>;.Close()the physical connection is returned to the transacted pool still enlisted in the sameTransaction.Open()reuses the same physical connection.SqlInternalConnectionTds.Enlist(Transaction)seestransaction.Equals(EnlistedTransaction)and short-circuits — no SET is sent.sp_reset_connection_keep_transactionpiggybacks on the next batch. On Azure SQL DB this reset clears the session isolation level to the database default; on on-prem SQL Server it does not, which is why the bug is Azure-only in practice.Fix
On the short-circuit path in
Enlist, when reset is pending and the new behavior switch is enabled, re-issue:mapped from
Transaction.IsolationLevel. The statement is queued onto the same TDS batch as the reset, so there is no extra round trip.Gated behind a new AppContext switch for back-compat:
Switch.Microsoft.Data.SqlClient.UseLegacyTransactionScopeIsolationBehavior(defaultfalse).Same back-compat pattern used by the related companion PR #4330 (
UseLegacyIsolationLevelBehavior).Files changed
src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/LocalAppContextSwitches.cs— new switch.src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/SqlConnectionInternal.cs— new re-attach branch +ReassertSessionIsolationLevelhelper.src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionScopeIsolationReassertTest.cs— new ManualTests, gated onIsAzureServer.src/Microsoft.Data.SqlClient/tests/Common/LocalAppContextSwitchesHelper.cs+tests/UnitTests/.../LocalAppContextSwitchesTest.cs— switch wired into the RAII helper and defaults test.Validation
End-to-end repro against both back ends with
Pooling=true; Max Pool Size=1, opening 3 connections per scope.Build clean on
net462,net8.0,net9.0(0 warnings, 0 errors).Snapshot isolation is intentionally not re-asserted
Per SET TRANSACTION ISOLATION LEVEL, switching to
SNAPSHOTmid-transaction causes the transaction to fail and roll back. This re-attach path always runs with the preserved transaction still open, so emitting the SET for aSnapshotscope would throw out ofSqlConnection.Open().ReassertSessionIsolationLevelreturns early forSnapshot— the delegated transaction was already begun under snapshot isolation via the TM request, so there is nothing to re-assert.Notes
DataTestUtility.IsAzureServerbecause the bug does not manifest against on-prem SQL Server.LegacySwitch_PreservesAzureDowngradeBehaviorassertsNotEqual("Serializable"), so it assumes the target database default is not serializable.TransactionScope, on all back ends (the queued reset piggybacks its TDS header, so the reset itself is free). Flagging for maintainers in case this should be narrowed — e.g. gated on Azure, or deferred so the SET prefixes the user's next batch.