Repository navigation
Fix assertion in selectPartsToMutate for a committed transaction's mutation - #110202
alexey-milovidov wants to merge 47 commits into
Conversation
…tation
`StorageMergeTree::selectPartsToMutate` could raise a `LOGICAL_ERROR`
("Cannot find transaction ... that has started mutation ... that is going to be
applied to part ...") and abort the server from a background job when it
encountered a transactional mutation whose transaction was no longer running.
This is especially reachable after a server restart, when no transactions are
running at all, so every still-present transactional mutation is looked up with
`tryGetTransactionForMutation` returning null.
The mutation entry's `csn` field is only an in-memory cache, filled by
`setMutationCSN` on commit and by `loadMutations` on startup. The authoritative
source of whether the transaction committed is the transaction log, which is
exactly what `loadMutations` and `clearOldMutations` already consult via
`TransactionLog::getCSN`. `selectPartsToMutate` now does the same: if the cached
CSN is still unknown it looks the transaction up in the log. If the transaction
is committed, the mutation proceeds without the transaction pointer; if it is
rolled back or otherwise not committed, the part is skipped (the mutation will be
removed by `killMutation` on rollback) instead of aborting.
Added an integration test that runs mutations inside implicit transactions (as
in the original report) and restarts the server, checking it comes back up with
consistent data and no failed or stuck mutations.
Closes: #83252
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [d8be011] Summary: ✅
AI ReviewSummaryThis PR hardens Final Verdict✅ No new blocking issues found in the current revision. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 213/257 (82.88%) · Uncovered code |
|
We tried to verify this on current The only state we found that reaches this branch is a race between mutation registration and |
| node.query("DROP TABLE IF EXISTS mt_race_stress SYNC") | ||
|
|
||
|
|
||
| def test_mutation_after_restart_does_not_abort(start_cluster): |
There was a problem hiding this comment.
this test passes without the fix: with implicit_transaction = 1 the commit waits for the mutation to finish (beforeCommit -> waitForMutation), so all 10 mutations are done before the restart and selectPartsToMutate never reaches the changed branch. verified against a build without this patch — all four assertions pass and the Cannot find transaction warning never fires.
There was a problem hiding this comment.
You are right — confirmed and addressed in 065fc00. The docstring now presents this test as a restart smoke test and points to the new deterministic test. The new test_kill_transaction_mutation_registration_race reproduces the orphaned-mutation state (the registration/KILL TRANSACTION race) with a pause failpoint and does fail without the patch: the orphaned mutation stays pending forever and blocks later mutations.
| /// The transaction that started this mutation is no longer running. | ||
| /// The mutation entry's `csn` field is only an in-memory cache; it is | ||
| /// filled in by `setMutationCSN` on commit and by `loadMutations` on | ||
| /// startup. The authoritative source of whether the transaction committed | ||
| /// is the transaction log, so consult it if the cached value is still | ||
| /// unknown (the same check that `loadMutations` and `clearOldMutations` do). | ||
| /// Without this, a mutation whose transaction has committed but whose cached | ||
| /// CSN was not updated would raise a spurious `LOGICAL_ERROR` and, in | ||
| /// particular, could abort the server via a background job after a restart. | ||
| /// See https://github.com/ClickHouse/ClickHouse/issues/83252 |
There was a problem hiding this comment.
the restart part of this comment doesn't hold: loadMutations already resolves the CSN from the log or removes the uncommitted entry at startup, and on commit setMutationCSN runs before the transaction leaves the running list, so the cache can't be stale for a committed transaction once tryGetTransactionForMutation misses.
| /// The transaction that started this mutation is no longer running. | |
| /// The mutation entry's `csn` field is only an in-memory cache; it is | |
| /// filled in by `setMutationCSN` on commit and by `loadMutations` on | |
| /// startup. The authoritative source of whether the transaction committed | |
| /// is the transaction log, so consult it if the cached value is still | |
| /// unknown (the same check that `loadMutations` and `clearOldMutations` do). | |
| /// Without this, a mutation whose transaction has committed but whose cached | |
| /// CSN was not updated would raise a spurious `LOGICAL_ERROR` and, in | |
| /// particular, could abort the server via a background job after a restart. | |
| /// See https://github.com/ClickHouse/ClickHouse/issues/83252 | |
| /// The mutation entry's `csn` field is only an in-memory cache and may be | |
| /// stale; the transaction log is the authoritative source, so consult it | |
| /// before deciding (as `loadMutations` and `clearOldMutations` do). |
There was a problem hiding this comment.
Fixed the comment in bfe495f — thanks. You are right: setMutationCSN assigns the CSN before the transaction leaves the running list and loadMutations resolves/removes entries at startup, so a committed transaction's cached CSN is not stale once tryGetTransactionForMutation misses. The comment now describes the cache/log relationship accurately and characterizes the not-committed case (including the orphaned-entry race that #110226 fixes at the source) instead of the old restart-abort claim.
There was a problem hiding this comment.
Follow-up: this comment block was reworked once more in 065fc00 — it now describes the terminal-state reasoning (commit caches the CSN before the transaction leaves the running list; rollback erases it only after the killMutation sweep) and the branch itself now removes the orphaned entry instead of skipping it.
| if (mutation_csn == Tx::UnknownCSN || mutation_csn == Tx::RolledBackCSN) | ||
| { | ||
| /// Transaction is not running but hasn't committed yet - this shouldn't happen | ||
| throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot find transaction {} that has started mutation {} " | ||
| "that is going to be applied to part {}, and mutation CSN is still unknown", | ||
| first_mutation_tid, mutations_begin_it->second.file_name, part->name); | ||
| /// The transaction was rolled back or is otherwise not committed. Its | ||
| /// mutation must not be applied (it will be removed by `killMutation` | ||
| /// on rollback); skip the part for now instead of applying a mutation | ||
| /// from a transaction that did not commit. | ||
| LOG_DEBUG(log, "Mutation {} was started by transaction {} that is not committed (CSN {}), skipping part {}", | ||
| mutations_begin_it->second.file_name, first_mutation_tid, mutation_csn, part->name); | ||
| current_parts_postpone_reasons[part->name] = PostponeReasons::TRANSACTION_NOT_COMMITTED; | ||
| continue; |
There was a problem hiding this comment.
if the log also returns UnknownCSN here, the transaction is gone from the running list and can never commit, so this skips the same dead mutation on every scheduling round forever — nothing removes it (clearOldMutations only handles finished mutations, and the killMutation mentioned above is exactly what failed to run) and it blocks all later mutations of these parts until a restart. the only way I found to reach this state is the registration race fixed in #110226; with that merged, this branch can keep the exception.
There was a problem hiding this comment.
Agreed — your analysis is correct. The committed-CSN case is already handled by the cached CSN (set before running_list.erase), and the only state that reaches txn == nullptr && csn == UnknownCSN here is the orphaned mutation left by the mutation-registration/KILL TRANSACTION race, which #110226 fixes at the source. This change is therefore defense-in-depth (turn a LOGICAL_ERROR into a skip) rather than a fix for a path reachable on current master, and skipping such an orphan indefinitely is not clearly better than the exception. Whether to keep this branch as defense-in-depth alongside #110226, or drop it and let #110226 be the sole fix, is left for @alexey-milovidov to decide once #110226 lands. I have not changed the skip-vs-throw behavior in this pass.
There was a problem hiding this comment.
Fixed in 065fc00 — you were right that skipping forever was not acceptable. When the transaction is gone from the running list and the log has no CSN for it, the entry is now removed on the spot (mirroring what loadMutations does with entries of uncommitted transactions at startup): counters are decremented, the entry is erased from current_mutations_by_version, and the mutation_*.txt file is deleted, so it no longer blocks later mutations of the parts. The cached RolledBackCSN case keeps the old skip behavior since killMutation is removing the entry in that window. Additionally, 3bd4eeb makes getIncompleteMutationsStatus report such an entry as killed instead of tripping the txn || isNonTransactional || from_another_mutation assertion, so waitForMutation waiters unblock immediately with the proper "Mutation was killed" error. The new failpoint test covers the whole flow deterministically.
| continue; | ||
| } | ||
| if (mutation_csn == Tx::UnknownCSN) | ||
| mutation_csn = TransactionLog::getCSN(first_mutation_tid); |
There was a problem hiding this comment.
optional: write the resolved CSN back to the entry (writeCSN) like loadMutations does.
as-is, a committed-but-stale entry repeats the log lookup on every scheduling round and system.mutations keeps showing no CSN.
There was a problem hiding this comment.
Done in 065fc00: when the log lookup finds a committed CSN, it is written back to the entry with writeCSN (under the same mutex that setMutationCSN uses), so system.mutations shows the CSN and subsequent scheduling rounds do not consult the transaction log again.
|
Since there is no reproducible test case, we can make it as a draft or just close it. |
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]>
…ation-restart-83252
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]>
…utationsStatus The assertion `txn || mutation_entry.tid.isNonTransactional() || from_another_mutation` in `getIncompleteMutationsStatusUnlocked` assumed that a transaction can never finish before a mutation it started, which is exactly the assumption an orphaned mutation entry violates: with the new deterministic test the waiting `ALTER` polls the orphaned entry and aborted a debug build on this assertion. Resolve the terminal state of the transaction instead: if it committed, report the status as usual; if it never committed, report the mutation as killed (the entry is either about to be removed by `killMutation`, or is an orphan that `selectPartsToMutate` removes), which also unblocks `waitForMutation` waiters immediately with the correct "Mutation was killed" error. Related: #83252 Co-Authored-By: Claude Fable 5 <[email protected]>
|
#110226 fixes the same race at the source: |
…n selectPartsToMutate The orphan cleanup added in the previous commit ran inside the per-part loop, after the `isVisible` check. If the earliest pending transactional mutation was orphaned but every candidate part was invisible to that orphaned snapshot, the loop hit `continue` at the `isVisible` check and never reached the `TransactionLog::getCSN` / erase path, so the orphaned entry stayed in `current_mutations_by_version` and kept blocking all later mutations of those parts until a restart. Move the terminal-state resolution of transactional mutation entries into a part-independent pre-pass at the top of `selectPartsToMutate`: committed entries get their CSN cached (mirroring `setMutationCSN`), rolled-back entries are left for the in-flight `killMutation`, and orphaned entries (transaction gone from the running list and never committed) are removed exactly as `loadMutations` discards entries of uncommitted transactions at startup. Because orphan detection depends only on the entry's transaction id and not on any part's visibility, it now runs regardless of current part visibility. The per-part branch is simplified accordingly: a still-unknown CSN there only means the transaction became terminal after the pre-pass in this call, so the part is postponed and rechecked next round. Related: #83252 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`system.transactions` is global to the server: it lists every running transaction, not only the paused `ALTER`. The regression test read a bare `SELECT tid_hash FROM system.transactions` and then asserted the whole table became empty after `KILL TRANSACTION`, so an unrelated running transaction could make the test kill the wrong transaction or fail the `count() = 0` assertion even when the paused `ALTER` was handled correctly. Snapshot the set of transaction hashes before starting the `ALTER`, identify the `ALTER`'s own transaction as the single hash that appears afterwards (the `SYSTEM WAIT FAILPOINT ... PAUSE` handshake guarantees it is already registered), kill only that hash, and assert that specifically that transaction disappears rather than that the server-global table empties. Related: #83252 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…saction The test identified the paused ALTER's transaction by diffing the server-global system.transactions before and after starting the ALTER, but background merge/mutation scheduling begins its own transactions at any moment, so the diff could match unrelated work: the count() = 1 assertion could fail intermittently or the test could kill the wrong transaction. Now the ALTER runs inside an explicit transaction (the race window is identical to the implicit one from the original report), and the test captures the transaction's identity with `transactionID()` right after `BEGIN TRANSACTION`, before the ALTER even starts, then kills exactly that transaction with `KILL TRANSACTION WHERE tid = ...`. No global-table diffing remains. Addresses the AI review Major on #110202 Co-Authored-By: Claude Fable 5 <[email protected]>
…ation-restart-83252
…ation-restart-83252
…nditional The AI review pointed out that `SYSTEM ENABLE FAILPOINT` and the explicit `BEGIN TRANSACTION` ran before the `try`/`finally` cleanup scope in `test_kill_transaction_mutation_registration_race`: if `BEGIN TRANSACTION`, `transactionID`, or the sanity assert failed, the test would exit with `mt_start_mutation_pause_before_register` still enabled and session 42 still holding an open transaction, poisoning later tests on the module-scoped node. Now the failpoint enabling and the transaction setup happen inside the `try`, and the `finally` always disables the failpoint, joins the `ALTER` thread (it holds the HTTP session lock while running), and detaches or rolls back the session transaction with a best-effort `ROLLBACK`. `ROLLBACK` on a killed (rolled-back) transaction only detaches it from the session and does not throw; when `BEGIN TRANSACTION` never succeeded it throws and is ignored.
…ation-restart-83252
…ation-restart-83252
…ation-restart-83252
…gainst its snapshot When the transaction that started a mutation has committed but its object is already gone from the running list, getIncompleteMutationsStatusUnlocked fell through to getVisibleDataPartsVector with a null transaction pointer, which checks the latest active parts instead of the parts visible to the mutation. A part with a smaller data version committed by another transaction after the mutation's snapshot is correctly skipped forever by the visibility gate in selectPartsToMutate, but the status path counted it and kept returning is_done = false, so waitForMutation could hang even after the mutation finished every part it was supposed to touch. Use getVisibleDataPartsVector(mutation_entry.tid.start_csn, mutation_entry.tid) in that case - the same snapshot the visibility gate in selectPartsToMutate applies. Co-Authored-By: Claude Fable 5 <[email protected]>
|
@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110202&sha=00fee23d374acf1b8df967afd9c40b9c4245e1b6&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.
|
…n on-fly test `test_kill_transaction_mutation_orphan_not_applied_on_fly` stopped merges on the shared node but only ran `SYSTEM START MERGES` and the table drop on the success path. A failed assertion would leave background merges disabled for the rest of the `test_transactions` module, so later tests could fail for unrelated reasons or stop exercising the background cleanup path. The whole post-setup section is now wrapped in `try`/`finally` that unconditionally restarts merges and drops the table. Co-Authored-By: Claude Fable 5 <[email protected]>
…ation-restart-83252
…ation-restart-83252
The previous guard in MutatePlainMergeTreeTask::executeStep checked txn->getCSN() == Tx::RolledBackCSN before prepare, but the task only becomes visible to killMutation's cancelPartMutations sweep when prepare inserts it into MergeList. A KILL TRANSACTION whose rollback started between the check and the insertion was missed by both the check and the sweep, so the task still ran the whole mutate pass and only threw from MergeTreeTransaction::checkIsNotCancelled at commit. Move the check into prepare, immediately after the MergeList insertion (and before the MUTATE_PART_START part log row): MergeTreeTransaction::rollback stores Tx::RolledBackCSN before the killMutation sweep, so a rollback that the check misses necessarily runs its sweep after the insertion and cancels the task through MergeList. Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 The three CI reds on
None of them touch the mutation/transaction code paths changed here; a fresh CI run on the new head should clear them. |
|
Both are mine to answer. Stress test (amd_debug), Two things worth knowing when keying sightings of this frame. The line number has moved ( Fast test (arm_darwin), The test does not predate the failure: I added it in #112913, merged 2026-08-07, and that merge commit is an ancestor of It is a cost timeout rather than a Darwin runner casualty: no The cost is process spawns, not queries. The test replays all six drivers' failure-handling blocks against stub clients, two phases each, which comes to roughly 10,700 I will send a separate pull request that cuts that spawn count, rather than raising the timeout or skipping the test, and I will link it here. |
|
Ask B, the Root cause, and it was mine: the test's interrupted-rerun probe keeps its sub-probe inside the probe The fix replaces both file-sentinel poll loops with blocking bounded reads on FIFOs, so the token I have no Darwin runner, so the wall-clock gain there is unmeasured from my side and CI on that pull Ask A, the |
After the rollback re-check moved into `MutatePlainMergeTreeTask::prepare` (before the `MUTATE_PART_START` row), an incorrectly selected cancelled mutation would also leave `system.part_log` empty, so the part_log poll no longer proved that `selectPartsToMutate` never fired. The loop now also asserts that the prepare re-check's skip message (which logs the transaction id, unique to this test) never appears in `system.text_log`, and the part_log check covers `MutatePartStart` in addition to `MutatePart`. Together they distinguish "never selected" from "selected but skipped". Co-Authored-By: Claude Fable 5 <[email protected]>
…ection-level signal The rollback-window test's evidence (no `MutatePartStart` row and no prepare-skip line) only proved that `MutatePlainMergeTreeTask::prepare` never ran for the cancelled mutation: `scheduleDataProcessingJob` can select the mutation and then drop the task before `prepare` when `scheduleMergeMutateTask` returns false. `selectPartsToMutate` now logs a selection message (part, target version, mutation ids, transaction id) at the only place a mutate task is built, and `test_kill_transaction_mutation_rollback_window` additionally asserts that this message never appears in `system.text_log` for the cancelled transaction. `test_kill_transaction_mutation_task_selected_before_rollback` pins both the selection and the prepare-skip message wording by asserting their presence, so the absence assertions cannot silently become vacuous. Co-Authored-By: Claude Fable 5 <[email protected]>
… snapshot A transactional mutation is applied only to the data parts visible to its transaction's snapshot: `selectPartsToMutate` skips every other part as `VERSION_NOT_VISIBLE`, so such a part is never mutated on disk. The on-fly mutations snapshot (`apply_mutations_on_fly`) stored only the commands of every pending entry and `MutationsSnapshot::getOnFlyMutationCommandsForPart` decided purely by comparing the mutation version to the part's data version. So a part with a smaller data version that was committed by another transaction *after* the mutation's snapshot still got the `UPDATE`/`DELETE` applied on the fly, returning data that the mutation never touched and that a plain `SELECT` does not show. `getMutationsSnapshot` now records, for every transactional entry it puts into the snapshot, the visibility it is allowed to touch - resolved exactly as `getVisibleDataPartsVectorForMutationStatus` and the gate in `selectPartsToMutate` resolve it: the live transaction's snapshot while it runs, and the snapshot recorded in the entry's transaction id once the transaction is gone (a rolled-back or orphaned entry is already skipped). `getOnFlyMutationCommandsForPart` skips a transactional mutation for a part outside that snapshot. Non-transactional mutations keep applying to every part, so the common path is unchanged; `getAllUpdatedColumns` deliberately keeps returning the superset, as it only decides which columns have to be read. New test `04838_transaction_mutation_on_fly_visibility`: transaction 1 creates a part, transaction 2 starts and commits a mutation with a larger version, and transaction 1 commits only afterwards - so its part is invisible to the mutation and must keep its original value with and without `apply_mutations_on_fly`. Without the fix the on-fly read returns the mutated value.
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110202&sha=702986aef420b1b00b18acf938bf37f9d3844e9d&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20azure%2C%20parallel%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.
|
|
Acknowledged, investigating. The root cause looks test-side rather than an engine bug, and I will follow up here with a PR.
The test tries to prevent this with The fix I intend is the one already used by the sibling tests: pin On breadth, I agree this is unrelated to this PR. Re-measuring 45 days of CIDB for this test name, the other hits decompose into unrelated causes rather than this signature: the 2026-07-30 hit on #112378 is a |
|
Fix: #114135. Pins On the class: I measured |
The test lists patch parts after `OPTIMIZE ... FINAL` and asserted a patch part the engine is entitled to drop at that point, so it intermittently lost the `patch-...-all_0_0_0_2` row from a `system.parts` listing. `MergeTreeData::clearUnusedPatchParts` drops a patch once its max source data version is <= the minimum data version among the partition's active regular parts. The `ALTER ... APPLY PATCHES, UPDATE` brings that minimum to 3, so from that point on the patch with version 2 is droppable while the one with version 4 is not. That asymmetry is exactly the observed diff, and it licenses the drop before all three of the test's part listings, not only the last one. The `OPTIMIZE ... FINAL` does not lower the minimum, it only merges the two regular parts into one; with `apply_patches_on_merge = 0` it does not consume the patches either. The `cleanup_delay_period = 1000` the test relied on was never a barrier: `IMergeTreeCleanupThread::start` schedules the first iteration with no delay (the delay only applies from the second iteration on), and `wakeup` is a bare `task->schedule` that bypasses the delay from any of its call sites. On `ReplicatedMergeTree` there is also no further interval gate before the patch cleanup. Pin `remove_unused_patch_parts = 0` instead and drop the two superseded delay settings, matching the existing idiom in `03100_lwu_01_basics` and `03100_lwu_15_future_reads`. The `.reference` file is unchanged. Validated in both directions on a single provoked state whose arms differ only in the pin value: forcing a cleanup `wakeup` between the `OPTIMIZE` and the final listing reproduces exactly the CI diff together with the `Will drop unused patch part` log line, and with the pin the same provoked run passes with that log line absent. 50/50 randomized runs pass. I measured the data version of every part in the 9 stateless tests whose `.reference` asserts literal patch-part names. Of those, only this one and the already-pinned `03100_lwu_01_basics` reach the drop condition, so no other test is touched. Tests that assert patch state in aggregate rather than by name are outside that set; `03100_lwu_15_future_reads` and `03100_lwu_51_condition_evaluated_once` are already pinned. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110202&sha=702986aef420b1b00b18acf938bf37f9d3844e9d&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20azure%2C%20parallel%29 Related: ClickHouse#110202
|
📊 Cloud Performance Report ✅ AI verdict: The one flagged item is a -13.8% "improvement" on clickbench Q17, but the change is confined to transactional-mutation and KILL TRANSACTION race handling (mutation selection, rollback windows, the barrier/rename ALTER prewait) plus test-only failpoints. Q17 is a plain read-only GROUP BY SELECT and executes none of that code, so the delta cannot plausibly be caused by this PR and is being read as run-to-run variance rather than a real speedup. Downgraded to not_sure; no other queries moved and no cross-query pattern is present. clickbenchFlagged queries (1 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_official🟢 No significant changes Debug info
|
`transactionID()` returns the tuple `(csn, ltid, host_id)` here, but some builds extend `TransactionID` with extra trailing fields that appear both in the tuple and in the log-message form of the TID. Unpacking exactly three fields fails there with `ValueError: too many values to unpack`. Build the expected log substring from however many fields the tuple has instead. Co-Authored-By: Claude Fable 5 <[email protected]>
The prewait scans in `alter` skip transactional mutations that are already dead when the scan runs, but the chosen mutation can also die during the wait: `KILL TRANSACTION` rolls back a transactional mutation at any moment, and its `killMutation` sweep removes the entry, so `getIncompleteMutationsStatusUnlocked` returns an empty status and `checkMutationStatus` failed the waiting `ALTER` with `Mutation ... was killed` - even though the same interleaving a moment earlier (before the scan) succeeds. Both prewait branches now loop: `tryWaitForAnotherMutation` returns false instead of throwing when the mutation was killed or removed during the wait, and the caller re-scans `current_mutations_by_version` for the latest mutation that can still be applied. A mutation that dies during the wait is handled exactly like one that was already dead at scan time. The new pauseable failpoint `mt_alter_prewait_pause_before_wait` holds the `ALTER` between the scan and the wait, so the deterministic integration test `test_kill_transaction_mutation_killed_during_alter_prewait` lands `KILL TRANSACTION` exactly inside the wait window.
Address review: `test_kill_transaction_mutation_registration_race` never proved that the orphaned entry was actually created - if the producer side of the race were closed, the assertions would pass trivially. Merges are now stopped while the orphan is created, the test asserts that `system.mutations` holds exactly one entry for the table before merges are restarted, and then waits for the background mutation selection to remove that entry (the full entry, not just `is_done = 0`). Also adds `test_kill_transaction_mutation_killed_during_alter_prewait`, the deterministic test for the prewait re-scan fix.
|
🕵 The three CI failures on
None of the fixes are on master yet, so a re-merge would not clear them; the new push runs fresh CI. |
|
Closing in favor of #110226 |
Fixes a
LOGICAL_ERRORraised from a background job, and a permanently stuck mutations queue, caused by an orphaned transactional mutation entry.StorageMergeTree::prepareMutationEntryregisters a transactional mutation in the transaction (txn->addMutation) beforestartMutationregisters it incurrent_mutations_by_version. IfKILL TRANSACTIONrolls the transaction back between the two steps, the rollback'skillMutationsweep finds nothing to remove, and the entry registered afterwards is orphaned: its transaction is gone from the running list and was never committed. The backgroundStorageMergeTree::selectPartsToMutatethen raised aLOGICAL_ERROR("Cannot find transaction ... that has started mutation ... that is going to be applied to part ...") on every scheduling round, and the orphaned mutation stayed pending forever, blocking all subsequent mutations of the affected parts. Found by a fuzzer in the linked issue.selectPartsToMutatenow resolves the state instead of throwing. When the transaction is no longer running and the entry's cached CSN is unknown, it consultsTransactionLog::getCSN— the authoritative source, the same check thatloadMutationsandclearOldMutationsuse. If the transaction committed, the CSN is cached in the entry and the mutation proceeds. If it never committed, the entry is a rolled-back orphan that nothing else will remove, so it is removed (the same wayloadMutationsdiscards entries of uncommitted transactions at startup) instead of blocking the mutations queue.getIncompleteMutationsStatusUnlockedresolves the same terminal states for waiters: a mutation of a rolled-back or orphaned transaction is reported as killed (unblockingwaitForMutationimmediately), and a mutation whose transaction committed but is already gone from the running list is checked against the mutation's original snapshot (getVisibleDataPartsVector(tid.start_csn, tid)) — the same visibility gateselectPartsToMutateapplies — so the status converges to done and waiters do not hang on parts the mutation was never supposed to touch.A transaction that is being rolled back is also treated as terminal for its mutations.
MergeTreeTransaction::rollbackstoresTx::RolledBackCSNbefore it starts thekillMutationsweep, andTransactionLog::rollbackTransactionerases the transaction from the running list only after that sweep returns, so in that window a cancelled transaction is still in the running list. Treating it as pending letselectPartsToMutateschedule a mutate task thatkillMutationcan no longer cancel (it only cancels tasks that are already inMergeList, andMutatePlainMergeTreeTaskentersMergeListinprepare), and made the read-only status paths report the cancelled mutation as unfinished, soSELECT ... SETTINGS apply_mutations_on_fly = 1applied anUPDATEof a transaction that will never commit.tryGetLiveTransactionForMutationnow hides an already cancelled transaction from every consumer that only asks whether the mutation is still going to be executed;killMutationkeeps using the raw lookup, because it needs the transaction object in exactly that state.A new pause failpoint
mt_start_mutation_pause_before_registerholds anALTERexactly inside the race window, making the orphaned state deterministically reproducible. The new integration testtest_kill_transaction_mutation_registration_racefails on an unfixed server (the orphaned mutation stays pending and blocks later mutations) and passes with the fix. A restart smoke test with mutations in implicit transactions is also included. The pause failpointtransaction_rollback_pause_before_kill_mutationsholdsKILL TRANSACTIONinside the rollback window described above, and the integration testtest_kill_transaction_mutation_rollback_windowasserts there that the cancelled mutation is neither applied on the fly, nor reported as unfinished, nor counted by the table-level mutation counters, nor selected for execution.Note: #110226 fixes the registration/
KILL TRANSACTIONrace at its source; this change makes the consumer side robust regardless of how the orphan appeared, and turns the previously fatal state into graceful cleanup.Closes: #83252
Related: #95009
Related: #110226
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a
LOGICAL_ERRORraised from a background job and a permanently stuck mutations queue when a transactional mutation entry outlived its transaction (a race between mutation registration andKILL TRANSACTION):StorageMergeTree::selectPartsToMutatenow rechecks the commit state in the transaction log and removes the orphaned mutation entry if the transaction did not commit.Documentation entry for user-facing changes