Skip to content

Fix race between mutation registration and KILL TRANSACTION leaving an orphaned mutation - #110226

Merged
tiandiwonder merged 16 commits into
ClickHouse:masterfrom
tiandiwonder:fix-mutation-kill-transaction-race
Aug 17, 2026
Merged

tiandiwonder merged 16 commits into
ClickHouse:masterfrom
tiandiwonder:fix-mutation-kill-transaction-race

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Problem

KILL TRANSACTION racing with ALTER TABLE ... UPDATE/DELETE executed inside a transaction can leave an orphaned mutation entry: registered in the table's mutation map, but its transaction is rolled back and gone, and its CSN will never be assigned. The consequences (reproduced deterministically with the failpoint added in this PR):

  • Debug/sanitizer builds: the server aborts — the ALTER's waitForMutation hits chassert(txn || mutation_entry.tid.isNonTransactional() || from_another_mutation) in getIncompleteMutationsStatusUnlocked, and the background selectPartsToMutate independently raises a logical error Cannot find transaction ... that has started mutation ... and mutation CSN is still unknown.
  • Release builds: the ALTER hangs, the background job throws the logical error on every scheduling round, and the orphaned entry is never removed (clearOldMutations handles only finished mutations), blocking all subsequent mutations of the affected parts until a server restart.

Root cause

prepareMutationEntry calls txn->addMutation before startMutation registers the entry in current_mutations_by_version. A rollback in that window snapshots the transaction's mutation list (which already contains the new mutation) and calls killMutation, which finds nothing to remove because the entry is not registered yet. The registration then completes, creating the orphan. The window has existed since the ordering was introduced; it is merely a few instructions wide, which is why it is hit rarely in practice.

Solution

After addPreparedMutationEntry, re-check the transaction state under the same critical section as the registration. If the transaction was rolled back in the window, unregister the entry immediately, remove the mutation file (logged), and fail the query with INVALID_TRANSACTION — the same error the client would get if the KILL had landed a moment earlier. Both interleavings are covered: a rollback that starts after the critical section finds the registered entry and removes it via killMutation as usual; a rollback that started before is detected by the re-check (its CSN change precedes its killMutation call, so it is visible). Holding the lock across registration and re-check also keeps the transient state invisible to selectPartsToMutate, which reads the map under the same mutex.

The metadata-ALTER path in StorageMergeTree::alter also registers a prepared mutation entry with a wider gap, but killing a rename mutation on rollback there would be incorrect (the durable metadata commit cannot be rolled back, and removing the rename mutation while keeping the new metadata reopens the #80648 data-loss scenario); metadata alters inside transactions have separate unresolved semantics and are out of scope here.

A PAUSEABLE failpoint mt_pause_before_register_mutation and a stateless test reproduce the race deterministically: without the fix, the test aborts a debug server; with the fix, the ALTER fails with INVALID_TRANSACTION, no mutation entry or file is left behind, and subsequent mutations proceed.

Related: #110202
Related: #83252

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed a race between KILL TRANSACTION and ALTER TABLE ... UPDATE/DELETE executed inside a transaction: a rollback landing between the mutation's registration in the transaction and its registration in the table left an orphaned mutation entry, which raised a logical error (Cannot find transaction ... that has started mutation ...) in background jobs and blocked all subsequent mutations of the affected parts until server restart.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.8.1.1523 (included in 26.8 and later)

prepareMutationEntry adds the mutation to the transaction before
startMutation registers the entry in current_mutations_by_version.
A rollback in that window (e.g. KILL TRANSACTION) calls killMutation,
which finds nothing to remove, and the entry registered afterwards is
orphaned: its transaction is gone and its CSN will never be assigned.
Background jobs then raise a logical error "Cannot find transaction ...
that has started mutation ..." (which aborts debug builds, as does the
chassert in getIncompleteMutationsStatusUnlocked reached from
waitForMutation), and the orphaned entry blocks all subsequent
mutations of the affected parts until server restart.

Re-check the transaction state under the same critical section as the
registration: a rollback that starts after the critical section finds
the registered entry and removes it via killMutation as usual; a
rollback that started before is detected by the re-check and the entry
is removed immediately, failing the query with INVALID_TRANSACTION.

Add a pauseable failpoint mt_pause_before_register_mutation and a
stateless test that reproduces the race deterministically: without the
fix, the test aborts a debug server.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d4ecf23]

Summary: ✅


AI Review

Summary

This PR closes the prepareMutationEntry -> addPreparedMutationEntry rollback window in StorageMergeTree::startMutation and adds a deterministic stateless regression test for the orphaned-mutation race. After checking the current PR head diff and the prior review threads against the actual net changes, I did not find any remaining correctness, safety, or test-coverage issues in this PR itself.

Final Verdict

No findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.80% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 30/30 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 13, 2026
@tiandiwonder tiandiwonder added the can be tested Allows running workflows for external contributors label Jul 13, 2026
alexey-milovidov added a commit that referenced this pull request Jul 13, 2026
The previous comment claimed the getCSN fallback prevents a committed
transaction's mutation from aborting the server via a background job
after a restart. That is inaccurate: `setMutationCSN` assigns the
mutation CSN before the transaction leaves the running list, and
`loadMutations` resolves or removes unresolved transactional entries at
startup, so a committed transaction's cached CSN is not stale once
`tryGetTransactionForMutation` misses. Rewrite the comment to describe
what actually happens: the cached CSN may be stale, the transaction log
is authoritative, and the not-committed case (including an orphaned entry
left by a mutation-registration/`KILL TRANSACTION` race, fixed at the
source in #110226) is skipped instead of raising a `LOGICAL_ERROR`.

Per review thread by tiandiwonder on src/Storages/StorageMergeTree.cpp.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov added a commit that referenced this pull request Jul 13, 2026
Address review: the previous behavior of skipping a mutation whose
transaction is gone and uncommitted left the entry in
`current_mutations_by_version` forever. Since mutation selection always
starts from the earliest pending mutation of a part, such an orphaned
entry (left by a race between mutation registration in `startMutation`
and the `killMutation` sweep of a concurrent `KILL TRANSACTION`
rollback) blocked all subsequent mutations of the affected parts until a
restart. Now `selectPartsToMutate` removes the orphaned entry, the same
way `loadMutations` discards entries of uncommitted transactions at
startup, and caches the CSN in the entry when the transaction log shows
the transaction as committed (so `system.mutations` displays it and the
log is not consulted again on every scheduling round).

Add a pause failpoint `mt_start_mutation_pause_before_register` between
the transaction-side and the storage-side mutation registration, and a
deterministic integration test
`test_kill_transaction_mutation_registration_race` that reproduces the
orphaned state with `KILL TRANSACTION`: on an unfixed server the
background job raises a `LOGICAL_ERROR` exception on every scheduling
round and the orphaned mutation stays pending forever; with the fix it
is removed and later mutations proceed. Reframe the previously added
restart test as a smoke test, since it does not exercise this branch.

Related: #83252
Related: #110226

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.80% 85.80% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 78.00% 78.00% +0.00%

Changed lines: Changed C/C++ lines covered: 30/30 (100.00%) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov self-assigned this Aug 13, 2026
Comment thread src/Storages/StorageMergeTree.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d4ecf23e1 with master 369e1aafb (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 694.62 MiB 691.61 MiB -3.01 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

8 translation units recompiled, 23 s compile time in total, 8 of them have a recent master baseline.

Job report

Comment thread src/Storages/StorageMergeTree.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Addressed the remaining CI failure in ed9fe11. DatabaseReplicated::tryEnqueueReplicatedDDL now rejects all active transactions before the replicated-DDL worker can drop the transaction context; the regression test now asserts the HTTP error response instead of curl’s transport exit status.

Comment thread src/Storages/StorageMergeTree.cpp Resolved
@tiandiwonder
tiandiwonder added this pull request to the merge queue Aug 17, 2026
Merged via the queue into ClickHouse:master with commit 8746095 Aug 17, 2026
181 checks passed
@tiandiwonder
tiandiwonder deleted the fix-mutation-kill-transaction-race branch August 17, 2026 04:28
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants