Skip to content

Reject commands after SQL Server aborts their transaction - #4857

Open
sanjaysingh wants to merge 13 commits into
dotnet:mainfrom
sanjaysingh:fix/4855-zombied-transaction-autocommit
Open

sanjaysingh wants to merge 13 commits into
dotnet:mainfrom
sanjaysingh:fix/4855-zombied-transaction-autocommit

Conversation

@sanjaysingh

@sanjaysingh sanjaysingh commented Oct 18, 2026 •

Copy link
Copy Markdown

A command bound to a transaction SQL Server had already aborted still ran and auto-committed.

The command now fails with the transaction-completed error. Assigning Connection again, or reading Transaction or IsolationLevel, keeps that aborted transaction attached. Rollback of the aborted transaction clears it. Disposing a transaction that is still live is a normal rollback, and the bound command can run again.

Fixes #4855

Test plan

  • Unit tests on net10.0: 1486 passed.
  • SQL Server 2022, net10.0 and net462: after disposing a live transaction, the same command inserts a row, sync and async.
  • SQL Server 2022, net10.0: after a server abort, assigning the connection again rejects the insert and the table stays empty.

Those commands were running outside the transaction and auto-committing.
@azure-pipelines

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

@sanjaysingh

Copy link
Copy Markdown
Author

@dotnet-policy-service agree

@priyankatiwari08 priyankatiwari08 self-assigned this Oct 19, 2026
@priyankatiwari08

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.

@priyankatiwari08 priyankatiwari08 added this to the 8.0.0-preview1 milestone Oct 19, 2026
…annot drop it.

The command was treating a remaining internal transaction as the only sign of a server abort, and both of those paths clear that field.
@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.

@paulmedynski paulmedynski 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.

@sanjaysingh - Thanks for the great contribution - this is a corner case that we had missed! A couple of items to address before we can accept.

@github-project-automation github-project-automation Bot moved this from To triage to Waiting for customer in SqlClient Board Oct 22, 2026
paulmedynski
paulmedynski previously approved these changes Oct 23, 2026
@paulmedynski

Copy link
Copy Markdown
Contributor

/azp run

@mdaigle
mdaigle requested a balanced review from Copilot October 23, 2026 18:11
@mdaigle

mdaigle commented Oct 23, 2026

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.

@mdaigle

mdaigle commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

The API contract for specifying transactions for a command doesn't make a lot of sense to me. We maintain so much more complexity by allowing silent reversion to auto commit mode.

Today, you can reference the same completed transaction indefinitely, even in new command objects and they'll all run in auto commit mode. This can open the door to bugs like this:

static bool TryReserveStock(SqlConnection connection, SqlTransaction transaction)
{
    using var command = new SqlCommand(
        """
        UPDATE Inventory
        SET Quantity = Quantity - 1
        WHERE ProductId = @id AND Quantity > 0
        """,
        connection,
        transaction);

    command.Parameters.Add("@id", SqlDbType.Int).Value = 42;

    if (command.ExecuteNonQuery() == 0)
    {
        transaction.Rollback();
        return false;
    }

    return true;
}

static void PlaceOrder(SqlConnection connection)
{
    using var transaction = connection.BeginTransaction();

    // BUG: ignores failure, including the helper's rollback.
    TryReserveStock(connection, transaction);

    // Still explicitly references the transaction, but it is completed.
    using var command = new SqlCommand(
        "INSERT INTO Orders (ProductId) VALUES (@id)",
        connection,
        transaction);

    command.Parameters.Add("@id", SqlDbType.Int).Value = 42;
    command.ExecuteNonQuery();

    transaction.Commit();
}

The code intends to roll back the transaction, but we have no guard that prevents the transaction from still being used, so the second command executes in auto-commit.

We should change the contract to disable silent reversion and require explicit transaction management. I would argue for changing the contract to address the issue in 8.0.0 and keeping this backwards compatible fix for <=7.1.

Then the fix is a simple check: before running the command, check that the transaction is not completed and that it matches the command on the connection.

These would now throw instead of silently switching to auto commit for the second execution:

command.Transaction = transaction;
command.ExecuteNonQuery(); // Inside transaction.

transaction.Commit();

command.ExecuteNonQuery();
command.Transaction = transaction;
command.ExecuteNonQuery(); // Inside transaction.

transaction.Rollback();

command.ExecuteNonQuery();

Let me discuss with the team.

@priyankatiwari08 priyankatiwari08 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.

Minor concerns:

  • Commit() now drains/validates before the bulk-copy lock guard (inline).
  • Dispose of a server-aborted tx leaves the bound command rejected (inline).
  • Execute_AfterCommitDrainsAbandonedRollback_DoesNotAutocommit discards the Commit result via Record.Exception; assert it throws InvalidOperationException (zombied) so a regression can't pass silently.

@paulmedynski paulmedynski added Hotfix 6.1.9 PRs targeting main that should be backported to release/6.1 for 6.1.9. and removed Hotfix 6.1.8 labels Oct 27, 2026
@sanjaysingh

Copy link
Copy Markdown
Author

I have addressed this. Thanks for catching these, @priyankatiwari08. Execute_AfterCommitDrainsAbandonedRollback_DoesNotAutocommit now asserts that Commit throws InvalidOperationException with the transaction-completed message. The bulk-copy lock and the dispose notes are answered on those threads.

@priyankatiwari08 priyankatiwari08 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.

Re-reviewed 60ff71a. The bulk-copy guard ordering and commit-exception assertion are addressed. Two remaining cases are detailed inline: deferred rollback during adapter batching, and disposal after full zombification. Findings are based on source tracing; no local tests were run.

@priyankatiwari08 priyankatiwari08 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.

  • Behavior regression: Rollback() after Dispose() now throws (inline).
  • Missing async coverage for the core abort scenario (inline).
  • mdaigle's contract/compat discussion (no auto-commit fallback) is still open; doc/switch decision pending.

@sanjaysingh

Copy link
Copy Markdown
Author

@priyankatiwari08 Disposal now clears only CompletedByServer, so Rollback() after Dispose() stays a no-op. Rollback_AfterDisposingLiveTransaction_DoesNotThrow covers that. ExecuteNonQuery_AfterAssigningSameConnection_DoesNotAutocommitAsync and ExecuteReader_AfterAssigningSameConnection_DoesNotAutocommitAsync cover the server abort: each throws, and the table stays empty. The 8.0 contract is unchanged.

@sanjaysingh

Copy link
Copy Markdown
Author

@paulmedynski RetainBatchTransactions copies the list, and the check walks that copy. Null means this command is not checking a batch. _retainedBatchTransactions and _batchTransactions are nullable. Append throws ObjectDisposed when the batch list is gone, and Clear uses _batchTransactions?.Clear().

@apoorvdeshmukh

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.

@sanjaysingh

Copy link
Copy Markdown
Author

@apoorvdeshmukh The 7 unit tests now have // Arrange, // Act, and // Assert. The 20 manual tests open with DataTestUtility.CreateConnection().

@cheenamalhotra cheenamalhotra added Hotfix 7.0.5 PRs targeting main that should be backported to release/7.0 for 7.0.5 Hotfix 7.1.3 PRs targeting main that should be backported to release/7.1 for 7.1.3. and removed Hotfix 7.0.4 labels Nov 17, 2026
paulmedynski
paulmedynski previously approved these changes Nov 18, 2026
@sanjaysingh

Copy link
Copy Markdown
Author

I merged main and resolved the conflict in ValidateCommand. The method keeps the enclave-attestation check and the server-abort check.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Hotfix 6.1.9 PRs targeting main that should be backported to release/6.1 for 6.1.9. Hotfix 7.0.5 PRs targeting main that should be backported to release/7.0 for 7.0.5 Hotfix 7.1.3 PRs targeting main that should be backported to release/7.1 for 7.1.3.

Projects

Status: Waiting for customer

Development

Successfully merging this pull request may close these issues.

Zombified transaction executes and auto-commits SQL command

7 participants