Repository navigation
Conversation
`StorageMergeTree::killMutation` erased the `current_mutations_by_version` entry (and removed `mutation_*.txt`) before it resolved the owning transaction, and only then called `TransactionLog::rollbackTransaction`. When the transaction had already passed its commit point, that rollback is a complete no-op: `MergeTreeTransaction::rollback` CASes `csn` `UnknownCSN -> RolledBackCSN`, which fails once `beforeCommit` has set `CommittingCSN`, so `rollbackTransaction` takes its "cancelled or committed concurrently" early return. The erase, however, is permanent. The committing thread then reached `MergeTreeTransaction::afterCommit` -> `StorageMergeTree::setMutationCSN`, could not find the entry, and threw `LOGICAL_ERROR "Cannot find mutation"`. Because `afterCommit` is `noexcept`, that aborted the server. Resolve the transaction first and claim the cancellation through `rollback`'s `csn` CAS before destroying the entry or the file. That CAS contends with `beforeCommit`'s `UnknownCSN -> CommittingCSN` CAS on the same atomic, so exactly one of them wins and the kill/commit decision becomes atomic with respect to the commit point. When the commit wins, `killMutation` returns `CancellationCode::CancelCannotBeSent` (reported as `cant_cancel`) and changes nothing. Merely reading the CSN would not be enough: the commit does not take `currently_processing_in_background_mutex`, so a read-then-erase is a TOCTOU that reproduces the same abort. Refusing loses no work. `beforeCommit` waits for every mutation of the transaction to finish before its CAS, so once the CSN is `CommittingCSN` there is nothing left to cancel; the refusal is a truthful status. This matches how the rest of the subsystem already behaves: `InterpreterTransactionControlQuery::executeRollback` refuses for a COMMITTING/COMMITTED transaction, and `KILL TRANSACTION` already reports `CancelCannotBeSent` for that state. The non-transactional path is unchanged. Two pauseable failpoints are added so the race can be reproduced deterministically, and a new stateless test covers both outcomes: the kill refusing after the commit point, and the kill winning the claim before it (in which case `COMMIT` fails with `INVALID_TRANSACTION`).
…annot run Follow-up to the previous commit on this branch; the fix itself is unchanged. Three test-side changes. `04812_kill_mutation_racing_transaction_commit` gains `no-replicated-database`. In a `Replicated` database `InterpreterAlterQuery::execute` consults `shouldReplicateQuery` before `checkStorageSupportsTransactionsIfNeeded`, so the transactional `ALTER TABLE ... UPDATE` is enqueued as a distributed DDL and rejected with `NOT_IMPLEMENTED "Distributed DDL queries inside transactions are not supported"`. No mutation entry is registered on this server, nothing ever reaches the failpoint, and `SYSTEM WAIT FAILPOINT ... PAUSE` is an unbounded wait, so the test would hang until the per-test timeout and could leave a server-wide failpoint enabled for the rest of the job. Measured: 0 rows in `system.mutations` and a 25 s timeout on the wait, against 1 row and an immediate return in an `Atomic` database. This does not depend on the shard count; a plain `MergeTree` table already satisfies the `!is_replicated_table` disjunct at one shard, and a `ReplicatedMergeTree` table is rejected earlier still because it does not support transactions. `no-encrypted-storage` is added for symmetry with `04141_transaction_after_commit_no_premature_wakeup`, which carries it with the same rationale; transactions do work on the encrypted policy, so this is consistency, not a correctness gap. A third pauseable failpoint, `kill_mutation_pause_after_transaction_resolve`, parks `killMutation` between resolving the owning transaction and claiming it, and a new arm uses it to pin the property the fix rests on. The two existing arms each freeze one side for the whole window, so a plain CSN read behaves exactly like claiming through the CAS in both, and a variant that reads the CSN and then erases passed the entire test. With the killer parked after its read and the commit then allowed past its commit point, that variant reports `waiting`, erases the entry and aborts the server, where claiming through the CAS reports `cant_cancel` and keeps it. The new arm reddens for that variant alone, leaving the other two byte-identical. `killMutation` has two call sites, neither on a hot path, and a disabled `pauseFailPoint` is a single `fiu_do_on` check.
The regression test's third arm parked the killer before it read the owning transaction's CSN, so the arm could only make the *resolve* stale, never the *read*. A variant that keeps the shipped resolve but lets that read decide, erasing without claiming through the CAS, is a genuine read-then-erase TOCTOU (its read can be invalidated before its erase) yet it passed all three arms. Move the killer's park point one statement later, into the branch that reads the CSN, so the read itself can be made stale. No behaviour change: the park is only reachable when the test enables the failpoint, and the expected output of all three arms is unchanged, so the reference file is untouched. Verified by mutation: the variant above now reddens on arm 3 alone, on that arm's own assertions, followed by the abort in arm 3's own transaction. A control that holds the variant fixed and moves only the park back to its previous position still passes all three arms, which is what shows the position, and not merely the presence of the park, is what makes the arm a witness. Also drop no-encrypted-storage from the test. Transactions work on the CI encrypted policy (an encrypted disk over a metadata-append-capable disk supports the append that writeCSN needs), and the tag would have excluded the test from about half of the s3 and azure functional runs, which pick the encrypted policy at random. Confirmed by running all three arms against a server whose default storage policy is an encrypted disk. Co-Authored-By: Claude Fable 5 <[email protected]>
Internal second-model review (3 rounds, all findings adjudicated)Before opening this PR I ran three independent cold reviews of the diff plus my own line-by-line
Blocker, fixed. Measured rather than argued: in a Replicated database the Major, fixed. The finding was about the park point's position, not its existence. Moving Blocker, disagreed. The claim was that reaching Nit, fixed. The tag was inherited from a same-shape precedent but is unnecessary here:
Also noticed and deliberately not raised: the same precedent test's own Session id: cron:clickhouse-review-slot-48:20260808-150001 |
Pre-PR validation gate (a-i)
Five mutants, each with its Build ID asserted to move and the shipping ID ( Also run: 50/50 randomized and 50/50 plain runs of the new test on the shipping binary, 50 OK each; |
|
cc @CurtizJ @KochetovNicolai, could you review this? |
|
Workflow [PR], commit [5601e60] Summary: ✅
AI ReviewSummaryI reviewed the current PR diff plus all prior top-level discussion and inline review threads. The current revision makes Missing context / blind spots
Final Verdict✅ No new review findings. LLVM Coverage ReportMeasured on commit 5601e60.
Changed lines: Changed C/C++ lines covered: 61/64 (95.31%) · Uncovered code |
Build profile diff (arm_release)Commit See the job log for details. |
… of noexcept The previous revision claimed the cancellation by calling rollbackTransaction before erasing the mutation entry. For a transaction holding exactly one mutation, that made MergeTreeTransaction::rollback's own sweep re-enter killMutation for the same still-present entry and reach MergeTreeMutationEntry::removeFile() inside a noexcept frame. DiskLocal::removeFileIfExists throws CANNOT_UNLINK for any errno other than ENOENT, so an ordinary unlink failure terminated the server instead of surfacing to the client. Split the CAS out of the sweep: claimRollback performs only UnknownCSN -> RolledBackCSN, killMutation claims it before touching the entry, and the full rollback runs after the entry is erased. The claim keeps arbitrating against the commit's UnknownCSN -> CommittingCSN CAS, while the entry and the transaction are torn down in master's original order, so the re-entrant killMutation returns NotFound as before and no throwing code runs under noexcept. Measured with one transactional mutation and a directory whose write bit is cleared, so unlink fails with EACCES: master: KILL MUTATION -> Code: 458 to the client, server alive previous revision: KILL MUTATION -> std::terminate in rollback(), server dead this revision: KILL MUTATION -> Code: 458 to the client, server alive Reported by the automated reviewer on ClickHouse#113961. An earlier attempt that skipped the initiating mutation inside the sweep was dropped: it left the entry registered while the transaction was already removed from running_list, which is the orphan state getIncompleteMutationsStatusUnlocked and background selection reject. The same class stays reachable on master through a plain ROLLBACK of a transaction holding a mutation, where the sweep itself does the unlink; that is the pre-existing noexcept-escape family of ClickHouse#45736 and is deliberately not addressed here.
|
Confirmed, and fixed in 0355611. The blocker is real: I reproduced the termination Constructed it by giving a one-mutation transaction a data directory with the write bit
Stack on the previous head, confirming the path you described: I took your first option, separating the claim from the sweep. I first tried your second option (teaching A mutant that restores the previous ordering (rollback before the erase) terminates on this One clarification on scope: the class is not created by this PR. A plain Regression scope: 70 tests covering |
CI finish ledger - 0355611CI is fully finished on this head and every check that ran is green: 157 success, 18 skipped, 0 failure. The praktika report's top-level status is
Session id: cron:our-pr-ci-monitor:20260811-170000 |
Resolves one conflict in src/Common/FailPoint.cpp: both sides append to the
failpoint macro list at the same insertion point. The list is append-only, so
the resolution is the union - master's mt_pause_before_register_mutation is kept
alongside this branch's three pause points. Master's rename of
create_empty_part_inject_stale_dir to claim_inject_stale_part_dir is taken as
is; no consumer of the old name remains.
Master landed an adjacent fix in StorageMergeTree::startMutation ("Fix race
between mutation registration and KILL TRANSACTION") which re-checks
MergeTreeTransaction::getState() under
currently_processing_in_background_mutex and removes the entry when the
transaction is already ROLLED_BACK. getState() derives from the same csn atomic
that claimRollback CASes, so a claim made by killMutation is observed as
ROLLED_BACK by that check and it removes the entry itself; this is the state
that check exists to handle. StorageMergeTree.cpp merged without conflict and
the two changes touch disjoint functions.
CI finish ledger — 7856c49CI finished with no failures: 177 check runs, 0 incomplete, 0 failed, This branch's own new test Session id: cron:our-pr-ci-monitor:20260818-000000 |
|
📊 Cloud Performance Report
Release-transition baseline: compared against the most recent available 26.9 masters at or before the trusted base-commit anchor because no 26.10 master baseline exists there. This PR only touches KILL MUTATION handling, the transaction commit/rollback logic and test failpoints. None of the ClickBench or TPC-H SELECT queries run that code, so none of the eight flagged improvements can come from the diff, and seven are downgraded to not_sure. ClickBench Q32 (-30.3%) is large enough that its verdict is locked and stays an improvement, but it still should not be credited to this change. The source build is v26.10 and the baseline is v26.9, and two of the ClickBench source runs ran on the same host, so the version gap or host conditions are the more likely explanation for the faster aggregation results. clickbench🟢 1 improved · Flagged queries (5 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_officialFlagged queries (3 of 22)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. Debug info
|
One conflict, src/Common/FailPoint.cpp, where both sides append to the failpoint macro list at the same insertion point. Resolved as the exact union: all 367 of master's entries are preserved and our three are kept (370 total). The five entries the merge drops relative to the old head (remote_query_executor_receive_packet_pause, remote_query_executor_finish_drain_pause, aggregating_in_order_transform_mid_loop_pause, delta_lake_write_commit_pause, distributed_cache_cancel_query_in_response_wait) are master's own removals in cc5c647 and 28209d2, with no remaining references in src/ or tests/. The fix is unchanged by the merge: the delta against master is the same 8 files, +284/-12, and every added and removed line matches the previously pushed head file by file. master did not touch the code this fix contends with. killMutation is byte-identical to the merge base, and so are beforeCommit, afterCommit and rollback, so the csn CAS the fix claims through is the same one. master's changes to alter() (DDLGuard released around a mutation wait, in-memory metadata reverted when alterTable throws) leave the held_entry path content-identical, which is what the review thread on this PR turned on. setMutationCSN is still called from afterCommit under noexcept on master, so the defect this PR fixes is still present and unfixed there.
Master split TransactionLog into TransactionManager (ClickHouse#117822), so the claim/rollback split now lives on TransactionManager instead: rollbackTransaction(txn, already_claimed) and the static claimRollbackFor. MergeTreeTransaction::rollback now takes commit_gate exclusive around its UnknownCSN -> RolledBackCSN CAS and returns RollbackResult. claimRollback keeps that: it does the same gated CAS and the csn.notify_all that every csn writer owes, and rollback(already_claimed) skips both when the caller already won the claim. The commit's own CAS in beforeCommit is under the same gate, so exactly one of commit or KILL MUTATION still wins. Master now catches exceptions from the re-entrant killMutation in the rollback sweep, so the erase-before-rollback order no longer protects a noexcept frame; it is kept so the sweep finds nothing to remove and an unlink failure is reported to the KILL MUTATION caller instead of only being logged. Comments trimmed accordingly. The test pause point in beforeCommit stays outside commit_gate, so a parked commit does not hold the gate. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test arms server-wide fail points, and master's new `failpoint_tests_are_isolated` style check requires such tests to carry both `no-parallel` and `no-fasttest`. `no-parallel` was already there. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
The route needs no client commit and no second session:
With this PR step 2 cannot do that: the A test for it: inject the commit failure that leaves the transaction in the unknown list, run Read from the diff and the surrounding code; this route was not executed. |
When the Keeper response of a commit is lost, `commitTransaction` puts the transaction into `unknown_state_list` and `runUpdatingThread` finalizes it later through `tryFinalizeUnknownStateTransactions`. The transaction keeps `CommittingCSN` the whole time, so `KILL MUTATION` must refuse with `cant_cancel` there too. Arm 4 drives this with `transaction_force_unknown_state_after_commit` and parks the updating thread before the mutation-CSN loop; with the previous `killMutation` the server aborts with "Cannot find mutation" from `runUpdatingThread`. Suggested by @ filimonov in ClickHouse#113961 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflicts: - src/Interpreters/MergeTreeTransaction.cpp: master added a QueryCancellationBlocker at the top of rollback(). Here the CAS lives in claimRollback() (a mutex and an atomic, no cancellation check), so the blocker goes to rollback(already_claimed) next to the other guards. - src/Storages/StorageMergeTree.cpp: failpoint declarations, kept both. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The text_log lookup matched any earlier row with the same test/database prefix, so a rerun in the same database could pass it on a stale row. Only count rows logged after arm 4 started. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks, I ran it. The route is real, and this PR closes it. The existing failpoints are enough:
Added as arm 4 of |
|
@tuanpach #123134 (merged today) fixes the abort this PR targets:
So the only difference left is that answer, and keeping it would change the expected output of 05338. Should I close this PR as superseded, or do you want the |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
KILL MUTATIONnow reportscant_cancelfor a mutation whose transaction has already passed its commit point, instead of removing state that theCOMMITstill needs, which aborted the server withLOGICAL_ERROR: Cannot find mutation. Transactions are experimental (allow_experimental_transactions).Description
StorageMergeTree::killMutationerased thecurrent_mutations_by_versionentry and removedmutation_*.txtbefore resolving the owning transaction, callingTransactionManager::rollbackTransactiononly afterwards. Past the commit point that rollback is ano-op:
rollbackCASescsnUnknownCSN -> RolledBackCSN, which fails oncebeforeCommitstored
CommittingCSN, sorollbackTransactionearly-returns. The erase, however, is permanent. Thecommitting thread then reached
afterCommit->setMutationCSN, could not find the entry, andthrew
LOGICAL_ERROR "Cannot find mutation"from anoexceptfunction, aborting the server.The fix resolves the transaction first and claims the cancellation through
rollback'scsnCASbefore destroying anything. That CAS contends with
beforeCommit'sUnknownCSN -> CommittingCSNCAS on the same atomic, so exactly one wins and the decision isatomic with respect to the commit point. When the commit wins,
killMutationreturnsCancelCannotBeSent(cant_cancel) and changes nothing. Reading the CSN is not enough:the commit does not take
currently_processing_in_background_mutex, so read-then-erase is aTOCTOU that reproduces the same abort.
Refusing loses no work, because
beforeCommitwaits for every mutation of the transaction beforeits CAS, and it matches how
executeRollbackandKILL TRANSACTIONalready treat a committingtransaction. The non-transactional path is unchanged, and
setMutationCSNisuntouched: an early return there would silently drop a committed mutation's CSN.
Reaching this requires the experimental
allow_experimental_transactions, henceImprovement.Validation: the new stateless test drives the race deterministically with three new pauseable
failpoints, including a lost Keeper commit response that
runUpdatingThreadfinalizes later; itaborts the server without the fix and passes with it. 50/50 randomized and 50/50
plain runs pass, and a scope over every
KILL MUTATIONtest plus the transaction-isolationfamilies shows no new failure against the unmodified build.
afterCommitremainsnoexceptwith no internal guard, so any other future throw there is stillfatal; that is the #45736 family, for a separate change.
No related open issue found.
Workflow [PR]
Sync PR [sync-upstream/pr/113961]