Skip to content

Do not kill a mutation whose transaction is past its commit point - #113961

Open
groeneai wants to merge 11 commits into
ClickHouse:masterfrom
groeneai:fix-kill-mutation-racing-transaction-commit
Open

groeneai wants to merge 11 commits into
ClickHouse:masterfrom
groeneai:fix-kill-mutation-racing-transaction-commit

Conversation

@groeneai

@groeneai groeneai commented Aug 8, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

KILL MUTATION now reports cant_cancel for a mutation whose transaction has already passed its commit point, instead of removing state that the COMMIT still needs, which aborted the server with LOGICAL_ERROR: Cannot find mutation. Transactions are experimental (allow_experimental_transactions).

Description

StorageMergeTree::killMutation erased the current_mutations_by_version entry and removed
mutation_*.txt before resolving the owning transaction, calling
TransactionManager::rollbackTransaction only afterwards. Past the commit point that rollback is a
no-op: rollback CASes csn UnknownCSN -> RolledBackCSN, which fails once beforeCommit
stored CommittingCSN, so rollbackTransaction early-returns. The erase, however, is permanent. The
committing thread then reached afterCommit -> setMutationCSN, could not find the entry, and
threw LOGICAL_ERROR "Cannot find mutation" from a noexcept function, aborting the server.

The fix resolves the transaction first and claims the cancellation through rollback's csn CAS
before destroying anything. That CAS contends with beforeCommit's
UnknownCSN -> CommittingCSN CAS on the same atomic, so exactly one wins and the decision is
atomic with respect to the commit point. When the commit wins, killMutation returns
CancelCannotBeSent (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 a
TOCTOU that reproduces the same abort.

Refusing loses no work, because beforeCommit waits for every mutation of the transaction before
its CAS, and it matches how executeRollback and KILL TRANSACTION already treat a committing
transaction. The non-transactional path is unchanged, and setMutationCSN is
untouched: an early return there would silently drop a committed mutation's CSN.

Reaching this requires the experimental allow_experimental_transactions, hence Improvement.

Validation: the new stateless test drives the race deterministically with three new pauseable
failpoints, including a lost Keeper commit response that runUpdatingThread finalizes later; it
aborts the server without the fix and passes with it. 50/50 randomized and 50/50
plain runs pass, and a scope over every KILL MUTATION test plus the transaction-isolation
families shows no new failure against the unmodified build.

afterCommit remains noexcept with no internal guard, so any other future throw there is still
fatal; that is the #45736 family, for a separate change.

No related open issue found.


Workflow [PR]
Sync PR [sync-upstream/pr/113961]

groeneai and others added 3 commits August 8, 2026 05:46
`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]>
@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author
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
read of every changed file and its callers. Four findings were raised across the rounds; all are
resolved. The final round raised none.

# Finding Severity Verdict
❌ 04812 lacked no-replicated-database, so in a Replicated database the transactional ALTER ... UPDATE is rejected before any mutation is registered, nothing parks at the failpoint, and SYSTEM WAIT FAILPOINT ... PAUSE waits forever blocker AGREE, fixed
⚠️ Arm 3's park point sat before the guard's CSN read, so it could make the resolve stale but never the read: a read-then-erase variant still passed all three arms major AGREE, fixed
⚠️ noexcept reachability of removeFile via rollback's mutation sweep blocker DISAGREE, with evidence
💡 no-encrypted-storage was unnecessary and excluded about half of the s3/azure runs nit AGREE, fixed

Blocker, fixed. Measured rather than argued: in a Replicated database the ALTER throws
Code: 48 NOT_IMPLEMENTED and system.mutations has 0 rows, versus 1 row in the Atomic control;
SYSTEM WAIT FAILPOINT ... PAUSE then returns rc=124 after 25s against rc=0 immediately on
Atomic. The mechanism is broader than first thought, since shouldReplicateQuery returns true
for a plain MergeTree table regardless of the cluster's shard count, so the tag is needed either
way. 19 of 24 stateless tests that wait on a failpoint, and 12 of 12 mutation-in-transaction
tests, carry it already.

Major, fixed. The finding was about the park point's position, not its existence. Moving
the one pauseFailPoint call inside the if branch, after the guard read, was a 0-net-line
relocation and left the expected output byte-identical, so the .reference is unchanged. What
makes the fix demonstrable is a pair of mutants: the read-then-erase variant that used to pass
now reddens arm 3 alone, on arm 3's own assertions (waiting with the entry erased, where the
fix reports cant_cancel with the entry kept, followed by the original abort in arm 3's own
transaction), while arms 1 and 2 stay byte-identical. A negative control that keeps the same
defect and moves only the park back to its previous position passes all three arms. That isolates
position from presence.

Blocker, disagreed. The claim was that reaching to_kill->removeFile() after a successful
claim puts a throwing call inside rollback's noexcept frame. Every cited line is true, but the
necessary step is refuted by master itself: rollback is already noexcept and its sweep already
re-enters killMutation for every mutation of the transaction, so on master today a transaction
holding two mutations plus a KILL MUTATION on the first already reaches removeFile() inside
that same frame. This PR widens the class from two mutations to one; it does not create it. The
one concrete throwing witness offered is unreachable as well, since killMutation's first
statement is assertNotReadonly(). The residual real route is a DiskLocal unlink error, which
is the #45736 noexcept family this PR deliberately leaves alone.

Nit, fixed. The tag was inherited from a same-shape precedent but is unnecessary here:
supportWritingWithAppend unwraps the encrypted layer to the cached object-storage disk, whose
metadata storage does support append, and DiskEncryptedTransaction implements WriteMode::Append

  • which is all writeCSN needs. Removing it was confirmed with a positive run on a server whose
    default policy is an encrypted disk, checked against the ENC header on the part's data.bin.

Also noticed and deliberately not raised: the same precedent test's own no-encrypted-storage
tag is probably unnecessary for the same reason. Not user-reachable, and not this PR's business.

Session id: cron:clickhouse-review-slot-48:20260808-150001

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (a-i)
# Question Answer
a Deterministic repro? Yes. clickhouse-test 04812_kill_mutation_racing_transaction_commit drives the race with three new pauseable failpoints, so there is no probabilistic component. Arm 1 parks the commit past its commit point immediately before the mutation-CSN loop; arm 2 parks it before its csn CAS; arm 3 parks the killer after it has read the transaction's CSN and before it claims the cancellation, then lets the commit pass its commit point, so the killer's read is stale when it resumes.
b Root cause explained? killMutation erased the current_mutations_by_version entry before resolving the owning transaction, then called rollbackTransaction. Past the commit point that rollback is a no-op (rollback's CAS UnknownCSN -> RolledBackCSN fails against CommittingCSN, so rollbackTransaction early-returns) while the erase is permanent, so afterCommit -> setMutationCSN missed the entry and threw LOGICAL_ERROR from a noexcept function. Abort trace: setMutationCSN (StorageMergeTree.cpp:1098) <- afterCommit (MergeTreeTransaction.cpp:302) <- finalizeCommittedTransaction (TransactionLog.cpp:510); line numbers are master's, since this PR shifts the first two.
c Fix matches root cause? Yes: the ordering/atomicity defect is fixed where it is, by claiming the cancellation through the transaction's own csn CAS before any destruction. setMutationCSN (the throw site) is untouched; an early return there would silently drop a committed mutation's CSN.
d Test intent preserved / new test added? No existing test modified. One new stateless test with three arms: a witness (kill must refuse, cant_cancel, entry kept, commit succeeds), a control (kill wins the claim, COMMIT fails INVALID_TRANSACTION, entry gone), and an interleaving arm that pins the atomicity of the claim itself.
e Both directions demonstrated? Yes. Same test, same server config, server identity asserted per arm: with the product fix reverted (67cd36230787f55b) the server aborts with Logical error: 'Cannot find mutation mutation_2.txt'; the shipping build (4aa406112aac86cc) passes all three arms.
f General across code paths? All 3 erasers of current_mutations_by_version enumerated (45 references in StorageMergeTree.cpp, 49 across src/): killMutation is the bug; clearOldMutations is not a carrier (its counting loop breaks at the first transactional entry); alter()'s failed-ALTER rollback is not a carrier, because it runs on the ALTER's own thread while its mutation is unfinished and beforeCommit waits for that mutation before its CAS, so the CSN is still UnknownCSN there. StorageReplicatedMergeTree::killMutation operates on Keeper only, never touches current_mutations_by_version, and replicated tables cannot join a transaction at all. StorageAlias/StorageProxy are pure delegation.
g Generalizes across inputs? Not an input-shaped fix; the change is control flow keyed on transaction state, independent of column types and values. All three reachable states are covered: no transaction (path unchanged), transaction pre-commit-point, transaction past its commit point. Re-entry from rollback's own mutation sweep (entry already RolledBackCSN) is handled by the cancelled_transaction flag and exercised by arm 2.
h Backward compatible? No setting, no default change, no serialization or format change, so no SettingsChangesHistory.cpp entry is owed. The only user-visible change is that KILL MUTATION now reports cant_cancel instead of waiting for a mutation whose transaction already committed, where it previously aborted the server.
i Invariants and contracts preserved? The invariant setMutationCSN asserts now holds. rollbackTransaction stays outside currently_processing_in_background_mutex, because rollback's sweep re-enters killMutation, which takes that mutex. No new lock-ordering hazard: none of the 9 TransactionLog::running_list_mutex critical sections takes a storage mutex. Both early returns (not-found, and the refusal) happen before any erase or removeFile.

Five mutants, each with its Build ID asserted to move and the shipping ID (4aa406112aac86cc)
returned byte-exactly after restore. Reverting to the original order, and falling through to the
erase after a failed claim, both abort at arm 1 with the original signature. Two read-then-erase
variants (the TOCTOU this fix rejects), one reading under the storage mutex and one reading
exactly where the shipped code reads, leave arms 1 and 2 byte-identical to the reference and redden
arm 3 alone, on its own stated reason: waiting with the entry erased where the fix reports
cant_cancel with the entry kept, followed by the same abort in arm 3's own transaction. That
asymmetry is why arm 3 exists; without it both variants passed the whole file. A fifth mutant is a
negative control: identical to the second TOCTOU variant except that the killer's park point sits
one statement earlier, before the CSN read instead of after it. It passes all three arms, which
is what shows the park's position (not merely its presence) is what makes arm 3 a witness.

Also run: 50/50 randomized and 50/50 plain runs of the new test on the shipping binary, 50 OK each;
and a scope covering every stateless test that uses KILL MUTATION plus every test sourcing
transactions.lib, run per test with server restarts and compared as reason-bucketed sets against
the reverted build: 0 only-in-fix failures, 0 reason changes, reason buckets identical. The residual
failures in that scope are environmental and identical on both arms; the new test is the one verdict
that differs, passing on the fix and aborting the server before it can report on the reverted build.
The test also passes all three arms against a server whose default storage policy is an encrypted
disk (verified from the ENC header on the resulting part files).

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @KochetovNicolai, could you review this? killMutation erased the current_mutations_by_version entry and removed mutation_*.txt before resolving the owning transaction, so past the commit point its rollbackTransaction was a no-op while the erase was permanent, and afterCommit -> setMutationCSN then threw LOGICAL_ERROR from a noexcept function; the fix claims the cancellation through rollback's csn CAS first, so the kill/commit decision is atomic and a kill that loses reports cant_cancel instead.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5601e60]

Summary: ✅


AI Review

Summary

I reviewed the current PR diff plus all prior top-level discussion and inline review threads. The current revision makes KILL MUTATION arbitrate against transaction commit through the same csn CAS, keeps the mutation entry alive once the transaction is past its commit point, and adds deterministic coverage for both the foreground commit path and the deferred unknown-state finalization path. I did not find any remaining correctness, concurrency, or coverage issue in the current revision.

Missing context / blind spots
  • ⚠️ I did not rerun 04812_kill_mutation_racing_transaction_commit locally because this workspace has no existing build* directory or test binary. A local run of that test would close the remaining execution gap.
Final Verdict

✅ No new review findings.

LLVM Coverage Report

Measured on commit 5601e60.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 92.10% +0.30%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 61/64 (95.31%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 8, 2026
Comment thread src/Storages/StorageMergeTree.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 5601e60e6976229ee19398ad53ae787e0058e59f was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

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

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

Confirmed, and fixed in 0355611. The blocker is real: I reproduced the termination
rather than reasoning about it.

Constructed it by giving a one-mutation transaction a data directory with the write bit
cleared, so unlink fails with EACCES instead of ENOENT:

binary KILL MUTATION, one transactional mutation, errno 13
master Code: 458 to the client, server alive
18d931e (previous head) std::terminate, server dead
0355611 (this push) Code: 458 to the client, server alive

Stack on the previous head, confirming the path you described:

 8. std::terminate()
10. MergeTreeTransaction.cpp:332  DB::MergeTreeTransaction::rollback()
11. TransactionLog.cpp:546        DB::TransactionLog::rollbackTransaction(...)
12. StorageMergeTree.cpp:1460     DB::StorageMergeTree::killMutation(String const&)

I took your first option, separating the claim from the sweep. claimRollback now performs only
the UnknownCSN -> RolledBackCSN CAS; killMutation claims before touching the entry, and the
full rollback runs after the entry is erased. The claim still arbitrates against the commit's
UnknownCSN -> CommittingCSN CAS on the same atomic, while the entry and the transaction are torn
down in master's original order, so the re-entrant killMutation returns NotFound exactly as it
does today and nothing throwing runs under noexcept.

I first tried your second option (teaching rollback to skip the initiating mutation) and dropped
it: skipping leaves the entry registered while rollbackTransaction has already removed the
transaction from running_list, and that orphan state is rejected by
getIncompleteMutationsStatusUnlocked's chassert at StorageMergeTree.cpp:1243 and by the
LOGICAL_ERROR in background selection at :1939-1943. Ordering the teardown against the claim
avoids introducing any new state at all.

A mutant that restores the previous ordering (rollback before the erase) terminates on this
construction, so the ordering is pinned rather than incidental.

One clarification on scope: the class is not created by this PR. A plain ROLLBACK of a
transaction holding a mutation already reaches removeFile() inside the same sweep on master, and
terminates identically under the same construction (verified). What this PR had done was move one
additional route, KILL MUTATION, into that frame; that is what is fixed here. The remaining
ROLLBACK route is the pre-existing noexcept-escape family of #45736 and I have deliberately
left it alone, since the catch-and-log shape used there would silently swallow a committed
mutation's lost CSN in this code path.

Regression scope: 70 tests covering KILL MUTATION, transactions.lib, and the
ROLLBACK/BEGIN TRANSACTION families, run per-test against both this head and the previous one:
0 verdict differences, 0 only-in-fix failures, identical failure-reason buckets.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0355611

CI 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 OK with 0 dropped jobs, so the skips are genuine config-level skips ("not affected by the changed files", "no build-affecting changes", "reused from cache"), not a dropped matrix.

Check / test Reason Owner / fixing PR
none no failures on this head -
Sync - CH Inc sync (private, not actionable)

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.
Comment thread src/Storages/StorageMergeTree.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 7856c49

CI finished with no failures: 177 check runs, 0 incomplete, 0 failed, Config Workflow and
Finish Workflow both green. The result database holds 304,680 passing rows and zero
FAIL or ERROR rows across 162 checks at this commit, so there is nothing to own.

This branch's own new test 04812_kill_mutation_racing_transaction_commit ran and passed in
39 checks (321 passing rows, 24 skipped where the parametrization excludes it), so the clean
result is coverage rather than absence of coverage.

Session id: cron:our-pr-ci-monitor:20260818-000000

@groeneai groeneai added the groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet label Aug 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — 1 query(s) improved out of 31 analysed

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 · ⚠️ 4 inconclusive

Flagged queries (5 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 32 improvement 1342 935 -30.3% <0.0001 aggregation: The -30.3% shift is large enough to lock the verdict, so it stands. The diff does not touch this SELECT's path, so look for the cause in the baseline or build difference rather than this PR's code.
⚠️ 18 not_sure 1064 965 -9.3% <0.0001 aggregation: This PR only changes KILL MUTATION and transaction commit/rollback code, which this GROUP BY SELECT never runs. The query is also noisy on master, so the -9.3% does not come from this PR.
⚠️ 31 not_sure 308 257 -16.6% <0.0001 aggregation: The -16.6% is a consistent shift, but this query never runs the changed transaction or KILL MUTATION code, so the PR cannot have caused it.
⚠️ 33 not_sure 1236 1069 -13.5% <0.0001 aggregation: This query is noisy on master and never runs the changed mutation-kill or commit code, so the -13.5% is not caused by this PR.
⚠️ 34 not_sure 1244 1093 -12.1% <0.0001 aggregation: This query is noisy on master and never runs the changed mutation-kill or commit code, so the -12.1% is not caused by this PR.

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_official

⚠️ 3 inconclusive

Flagged queries (3 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 1 not_sure 66 52 -21.2% <0.0001 This is a 14 ms shift on a fast, noisy query whose measurements varied a lot. The scan-and-aggregate path does not touch transaction code.
⚠️ 7 not_sure 82 62 -24.4% <0.0001 The -24.4% is only 20 ms on a query that is noisy on master. A join SELECT does not run KILL MUTATION or transaction commit code.
⚠️ 17 not_sure 100 60 -40.0% <0.0001 The base runs were very noisy and the shift is only 40 ms, below the lock threshold. The diff does not touch this query's path.

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
  • StressHouse run: 273d240d-03c0-48b7-a6f3-1005b78467aa
  • MIRAI run: 33181768-2dc3-426f-9c5f-fe302207b5aa
  • PR check IDs:
    • clickbench_756285_1791660643
    • clickbench_756291_1791660643
    • clickbench_756297_1791660643
    • tpch_adapted_1_official_756308_1791660643
    • tpch_adapted_1_official_756318_1791660643
    • tpch_adapted_1_official_756356_1791660643

@clickhouse-gh clickhouse-gh Bot added the comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). label Sep 4, 2026
groeneai and others added 2 commits September 17, 2026 12:12
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]>
@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Oct 1, 2026
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]>
@filimonov

Copy link
Copy Markdown
Contributor

claimRollbackFor closes a second route to the same abort, which the test does not drive. Worth a line in the test rather than a code change.

The route needs no client commit and no second session:

  1. A transaction that ran a mutation starts committing. MergeTreeTransaction::beforeCommit swaps csn to Tx::CommittingCSN. The Keeper multi is sent and its response is lost, so TransactionLog::commitTransaction appends the transaction to unknown_state_list instead of resolving it.
  2. KILL MUTATION arrives. Before this PR, StorageMergeTree::killMutation erases the entry from current_mutations_by_version and then calls rollbackTransaction, which is a no-op on a committing transaction — so the entry is gone and nothing has rolled back.
  3. After reconnect, TransactionLog::tryFinalizeUnknownStateTransactions finds the CSN in the log and calls finalizeCommittedTransaction. Its afterCommit reaches StorageMergeTree::setMutationCSN, which throws LOGICAL_ERROR "Cannot find mutation" — inside a noexcept frame, so the server terminates.

With this PR step 2 cannot do that: the UnknownCSN -> RolledBackCSN compare-and-swap fails, because a transaction sitting in unknown_state_list still holds Tx::CommittingCSN. MergeTreeTransaction::afterCommit notes the same fact in a comment of its own ("this->csn is still Tx::CommittingCSN here"). The statement then answers cant_cancel and the entry is still there at step 3.

A test for it: inject the commit failure that leaves the transaction in the unknown list, run KILL MUTATION and expect cant_cancel, let the updating thread finalize, then expect the server alive and the mutation's CSN in system.mutations. Whether the existing failpoints can hold a transaction in that list long enough for the KILL MUTATION to land was not checked.

Read from the diff and the surrounding code; this route was not executed.

groeneai and others added 3 commits October 7, 2026 18:06
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]>
@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, I ran it. The route is real, and this PR closes it.

The existing failpoints are enough: transaction_force_unknown_state_after_commit drops the response of the commit multi, so commitTransaction puts the transaction into unknown_state_list, and transaction_commit_pause_before_mutation_csn then parks runUpdatingThread inside the deferred finalizeCommittedTransaction, right before the setMutationCSN loop. The kill therefore lands during that finalization rather than while the transaction is still in the list (no existing failpoint pauses the updating thread earlier), but csn is CommittingCSN in both places, so the claim CAS fails the same way.

  • With this PR: cant_cancel, the entry stays, the updating thread writes the CSN, the row is updated, the server stays up.
  • With only killMutation reverted to master: the server aborts with Logical error: 'Cannot find mutation mutation_2.txt' in setMutationCSN <- afterCommit <- finalizeCommittedTransaction <- tryFinalizeUnknownStateTransactions <- runUpdatingThread.

system.mutations has no CSN column, so the arm checks the committed row and the surviving entry instead, plus the commit's own will finalize it later line in system.text_log, so it cannot pass on the foreground path (without the forcing failpoint, only that check fails).

Added as arm 4 of 04812 in d9c42ce and 5601e60 (test-only). Master is merged in too, since the PR conflicted.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@tuanpach #123134 (merged today) fixes the abort this PR targets: setMutationCSN now logs a warning instead of throwing out of afterCommit. I measured what is left on master 41a73dec, with the scenario of 05338_mutation_killed_during_commit (KILL MUTATION while afterCommit is paused before the CSN store):

  • master: KILL MUTATION answers waiting, the mutation leaves system.mutations, COMMIT succeeds and the UPDATE stays. A KILL of a finished non-transactional mutation gives the same result.
  • this PR: KILL MUTATION answers cant_cancel and the mutation keeps its record and CSN.

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 cant_cancel answer kept (then I merge master and update 05338)?

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

can be tested Allows running workflows for external contributors comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants