Repository navigation
Conversation
`ALTER TABLE ... DETACH PART` replaces the detached part with an empty part covering the same block range, and that empty part keeps the column list the table had at detach time. `clearEmptyParts` normally removes it right away, but it returns early while outdated parts are still loading, and `StorageMergeTree::startup` runs it before starting outdated-part loading while starting mutation scheduling concurrently. A server restart inside the window where the empty part is still on disk therefore revives it as Active and lets mutation selection reach it before cleanup does. Mutating such a part cannot succeed when a column it still lists was renamed away and the rename mutation entry is no longer in the queue: nothing maps the stale name, so `MutationsInterpreter` resolves it against current metadata and throws UNKNOWN_IDENTIFIER. Each attempt takes a fresh metadata snapshot, so it cannot self-heal; the part's mutation tag also holds off the drop that would end it, so the attempts repeat about once a second until cleanup finally wins the race. Measured on a CI upgrade run: 147 error lines over 32 seconds. Skip such a part in `selectPartsToMutate` instead. The mutation then completes by the part being dropped, which is what happens without a restart anyway. The conditions are the ones `clearEmptyParts` itself uses to decide that a part is droppable: no rows, `remove_empty_parts`, and transaction visibility. Co-Authored-By: Claude Opus 5 <[email protected]>
The conditions used to skip the part establish that `clearEmptyParts` would drop it, not that anything will run `clearEmptyParts`. `MergeTreeCleanupThread::iterate` is its only periodic caller, and `IMergeTreeCleanupThread::run` returns before that call while the cleanup blocker is held, which `SYSTEM STOP CLEANUP` does on non-replicated tables too. Skipping there left the part Active for as long as cleanup stayed stopped: the mutation was never attempted, so `is_done` never became true and `latest_fail_reason` stayed empty, and a second `ALTER TABLE ... DELETE` with `mutations_sync = 1` on an already empty table stopped returning where it used to return at once. Test the cleanup blocker as well, so that a part nothing is going to remove is mutated exactly as before. Two smaller gaps in the same skip. The cleanup thread's period backs off to `max_cleanup_delay_period` after an iteration that cleans nothing, and `wakeupEarlierIfNeeded` only fires above a few hundred outdated parts, so the drop that the skip defers to could be minutes away; wake the thread at the skip site, as `onActionLockRemove` already does when the blocker is released. And the skip recorded no postpone reason, unlike every sibling skip in that loop, which left `system.mutations` reporting neither a failure nor a reason for the wait; record one. In the test, pin `sleep_before_loading_outdated_parts_ms` so the restart case reddens by construction instead of by winning the startup race against cleanup, assert that the empty part really is revived as active, and add an arm for the stopped-cleanup case. Co-Authored-By: Claude Opus 5 <[email protected]>
Waking the cleanup thread does not make it remove the part. `MergeTreeCleanupThread::iterate` calls `clearEmptyParts` inside `compareAndRestartDeferred(merge_tree_clear_old_parts_interval_seconds)`, and `wakeup` only schedules an iteration: it does not make that gate grant. On a table created with `merge_tree_clear_old_parts_interval_seconds = 100000` the skip therefore deferred to a removal that would not happen for a day. The mutation was never attempted, so `is_done` never became true and `latest_fail_reason` stayed empty, and `ALTER TABLE ... DELETE` with `mutations_sync = 1` on an already empty table waited for the whole interval where it used to return at once. That is the same invariant as the cleanup blocker, reached by a second mechanism. `requestEmptyPartsCleanup` records the request and wakes the thread; the iteration consumes it before the interval block and, when that block does not grant, runs `clearEmptyParts` on its own. The call stays inside `iterate` so the same `lockForShare` covers it as covers the periodic one, and the periodic block is left unchanged so nothing in it moves. Restarting the stopwatch instead would push the removal out by a full interval, and calling `clearEmptyParts` from `selectPartsToMutate` would deadlock on `currently_processing_in_background_mutex` through `outdatePart`. Move the skip below the check for whether the part owes a mutation at all, so it can no longer request cleanup, or record a postpone reason that `getMutationsStatus` then discards, for a part that blocks nothing. In the tests: a new arm pins `merge_tree_clear_old_parts_interval_seconds` and bounds the wait with `max_execution_time`, so it reddens with `TIMEOUT_EXCEEDED` rather than hanging; the restart arm asserts `parts_postpone_reasons`, which is what a user reads to tell a skipped part from a stalled mutation; `05104_mutation_of_empty_part_in_transaction` covers the transaction-visibility condition, whose empty part cleanup refuses to drop while it is uncommitted, so the mutation must be attempted. `sleep_before_loading_outdated_parts_ms` is raised to 30 s, measured to hold the part active until t+31 s, which leaves the post-restart assertions about 16 seconds of margin instead of four. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model reviewThree review rounds, 9 AGREE and 2 DISAGREE. Every AGREEd finding was sent back for a fix before this
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20260906-234000 |
|
Workflow [PR], commit [c1d1044] Summary: ✅
AI ReviewSummaryThis PR makes non-replicated Findings❌ Blockers
Final Verdict
|
|
cc @CurtizJ @tavplubix, could you review this? After a restart revives an empty |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units247 translation units recompiled, 2590 s compile time in total, 247 of them have a recent master baseline. |
Three of the four conditions `clearEmptyParts` uses are mirrored at the skip in `selectPartsToMutate`. The fourth, `outdated_data_parts_loading_finished`, is not, because that window is the race the skip exists for: mirroring it would send the part back to the mutation attempt exactly while the restart has revived it. Nothing at the site said so, so a later patch making the two consistent would quietly undo the fix. Name the condition where such a patch would look. `iterate` consumes the empty-parts request before the interval block whether or not that block grants, which is correct only because the block also calls `clearEmptyParts`. Note that too, so moving or dropping the periodic call does not silently start losing requests. Co-Authored-By: Claude Opus 5 <[email protected]>
`requestEmptyPartsCleanup` scheduled the cleanup task on every call, so a busy table whose empty part is temporarily undroppable took one `schedule()` per selection round instead of one per request. Raise the wakeup only on the false to true transition. A request the iteration has not consumed yet already has a wakeup outstanding, `iterate` consumes the flag unconditionally so no run can leave it set, and `BackgroundSchedulePoolTaskInfo::execute` clears `scheduled` before it calls the task, so the `schedule()` of a request raised while an iteration is in flight is still honoured rather than dropped. The three arms of `test_mutation_empty_part_after_restart` pass unchanged, including the one that pins `merge_tree_clear_old_parts_interval_seconds` out of reach and can only be satisfied through this request path. Co-Authored-By: Claude Opus 5 <[email protected]>
tiandiwonder
left a comment
There was a problem hiding this comment.
measured the retry cadence while working out how much of the burst is inherent, and the numbers don't line up with the report — handing it over since you have the only thing that reproduces the shape.
on a scratch 26.9 server, a mutation that always fails (UPDATE b = throwIf(1)) throttles cleanly: intervals double from failure ~11 onward — 2.7s, 4.2, 8.8, 16.7, 34.0. so mutation_backoff_policy works in the ordinary case. note each failure emits two <Error> lines (MutatePlainMergeTreeTask.cpp:155 and the tryLogCurrentException below it), so 147 lines is ~73 failures — and 73 in 32.15s with no visible slowdown is not compatible with the backoff accumulating at all. i could not find what defeats it from reading: prepare() bypassing the catch doesn't hold (the interpreter is built inside execute()), the version match in updateMutationEntriesErrors does fire for the target entry, and the success-path removePartFromFailed is gated on contains, so the partition-1 successes can't clear the partition-0 failure.
one side finding that holds regardless: the first ~10 retries are invisible to the backoff, because (1 << retry_count) * 1000us starts at 2ms — far below the background scheduler's polling floor. the early gaps i measured were 0.4-1.3s. so ~10-12 rapid failures, ~20 error lines, are inherent to any repeatedly-failing mutation no matter what else changes.
worth pinning down before this lands: if the CI burst is really ~73 failures rather than ~12, then whatever defeats the backoff there is the amplifier, and fixing that would be both smaller than the selection guard and more general — it would cover non-empty parts, which this PR by design does not.
|
Measured it against the artifact, then A/B'd the setting. Short version: the count is 49, not ~73, and what defeats the backoff in CI is a test config value, not engine behaviour. Lines per failure is 3, not 2. The third is Your conclusion holds anyway: nothing throttles there. The 49 attempt starts are 0.14 s to 1.65 s apart with no growth from the first to the last, and that whole 11 MB log contains zero The reason is A/B on one debug-master server, two tables, only that setting differing,
The second arm reproduces your 2.7 / 4.2 / 8.8 / 16.7 / 34.0, so your run and mine measured the same code on different configs. Your side finding holds, with the boundary at retry 11: retries 1 to 10 ask for 2 ms to 1.02 s, all at or below the selection cadence. On scope. The upgrade-check leaf fails when the filtered error file is non-empty ( |
|
📊 Cloud Performance Report ✅ AI verdict: No performance change can be attributed to this PR. It changes how mutations are scheduled for empty MergeTree parts and adds an on-demand wakeup to the background cleanup thread. None of this runs during read-only benchmark queries. ClickBench Q16 and Q18 (both +14.4%, with roughly 16-18% more CPU) are still inside master's recent range for these noisy aggregation queries, so suppressing them was correct and there are no grounds to contest it. No tpch_adapted_1_official queries were flagged, though two of its source runs shared a single node. clickbenchFlagged queries (2 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
|
Conflict in `MergeTreeMutationStatus.h`: master added the `PENDING_LIGHTWEIGHT_UPDATE` postpone reason on the line where this branch adds `EMPTY_PART_WILL_BE_DROPPED`; both are kept.
Master's `clearEmptyParts` now spells the visibility check as `VersionMetadata::isVisibleByLatestSnapshot` (e90374c). The skip in `selectPartsToMutate` mirrors that check, so it uses the same helper. The predicate is unchanged.
Conflict in src/Storages/MergeTree/MergeTreeMutationStatus.h: master added PostponeReasons::UNREGISTERED_MUTATION (f112590) on the line this branch added EMPTY_PART_WILL_BE_DROPPED. Both are kept. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@tiandiwonder, I merged master to resolve a conflict in Since your approval on 0322fa2 there is one behaviour change, ea7897f: the cleanup thread serves the empty-parts request before its other cleanups, so an exception in one of those cannot leave the request unserved. The rest is c91a3ff (the skip calls Could you take another look? The Upgrade check failure this fixes (#120975) keeps landing on unrelated PRs, most recently #101264. |
| /// only produce another empty part, while the mutation tag holds off the removal. Skipping | ||
| /// it is correct only while something still runs that removal, hence the cleanup check. | ||
| /// `clearEmptyParts`'s `outdated_data_parts_loading_finished` gate is deliberately not mirrored: that window is the race. | ||
| if (part->rows_count == 0 && (*storage_settings.get())[MergeTreeSetting::remove_empty_parts] |
There was a problem hiding this comment.
clearEmptyParts no longer drops every visible 0-row part that reaches this branch: on UNIQUE KEY tables a DELETE stages a 0-row marker part and writes the delete bitmaps into that part's directory (src/Storages/MergeTree/UniqueKey/UniqueKeyTxnCommit.cpp:742, src/Storages/MergeTree/UniqueKey/UniqueKeyTxnCommit.cpp:772). clearEmptyParts explicitly refuses to drop such a part while it is still pinned by those bitmaps (src/Storages/MergeTree/MergeTreeData.cpp:5171), but this selector still postpones it as EMPTY_PART_WILL_BE_DROPPED and never schedules a mutation for it.
That breaks the new contract on a supported surface: a later data-rewriting mutation on the same UNIQUE KEY table can now sit pending until the target parts age out under old_parts_lifetime or forever under SYSTEM STOP CLEANUP, even though mutating the marker part was the only way to let mutations_sync = 1 finish promptly. Can we mirror the delete-bitmap pin check here too, or better share one helper with clearEmptyParts, and add a regression for a UNIQUE KEY delete marker followed by a mutation?
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
An empty part that background cleanup is about to drop is no longer selected for mutation on non-replicated
MergeTreetables, andsystem.mutationsnow reports why. Previously a server restart could revive such a part, left behind byALTER TABLE ... DETACH PART, and start a mutation on it that cannot succeed, loggingUNKNOWN_IDENTIFIERroughly once a second until cleanup removed the part.Description
Closes: #120975
Related: #104510 (reported there).
A restart can revive an empty
DETACH PARTtombstone as Active, and mutation selection picks it up: itscolumns.txtstill lists a column since renamed away and the renaming mutation entry is gone, so every attempt fails withUNKNOWN_IDENTIFIER, roughly once a second, until the cleanup those attempts delay drops the part. 147<Error>lines over 32.15 s in the CI artifact. The final state is correct, but the burst trips the Upgrade check's log-scan leaf (109 CIDB rows across 103 PRs in 30 days).Selection wins that race because
clearEmptyPartsstays inert until outdated-part loading finishes, whileStorageMergeTree::startuphas already started mutation scheduling. The fix skips a zero-row part inselectPartsToMutateunder the droppability conditionsclearEmptyPartsitself applies, and only while cleanup is running, since those conditions say the part would be dropped, not that anything will. UnderSYSTEM STOP CLEANUPit is still mutated as before. It also asks cleanup for that removal directly, ahead of the thread's other work, so neither its adaptive period,merge_tree_clear_old_parts_interval_secondsnor a failing temporary-directory cleanup defers it, and records a postpone reason.The replicated selector carries no such guard either; no CI occurrence is replicated and reachability there is unmeasured, so it is out of scope.
A new integration test fails on base with the byte-identical CI signature and passes with the fix; its stopped-cleanup, pinned-interval, failing-cleanup and
remove_empty_parts = 0arms, and a stateless test for an uncommitted empty part, each redden when their own condition is removed.04653_mutation_rewrite_stale_part_column_typeis unchanged.The alternative, ordering
clearEmptyPartsbefore mutation scheduling starts, would serialise startup behind an asynchronous load. Whether a non-empty wide part with a staleREAD_COLUMNbehaves the same is unverified; CI shows no such carrier.No overlap with #115962 (same family, compact-part shape).
Startup race and CI carrier, from the upgrade log (click to expand)
Table
adb18f7c-eb4e-4b37-ac8a-c871903e1260(t_stale_part_type_5).all_1_1_1is the empty tombstone left byDETACH PART, revived Active by the restart because "will drop empty part" is in-memory intent only:mutation_4.txt, theRENAME COLUMN b TO d, is absent from the load in this artifact: a concurrent test'sKILL MUTATIONfilters only ondatabase = currentDatabase()and a mutation id, so in the shared test database one statement removed it from nine tables, eight of them unrelated to it. It is not what makes the signature frequent. On PR #117375 at9e46ee24a0a6all three entries load and the burst is identical, because the renameALTERchanges the metadata whether or not its mutation entry survives, so a revived part owingMODIFY COLUMN balone can never resolveb, and the defect needs no concurrent test at all.The two message variants in CI are the same part mutated toward two different versions:
In scope b, b.withall_1_1_1_2is mutation 2 alone,In scope b, b, c.withall_1_1_1_5is mutations 2 and 5 batched. The repeatedbis the synthesizedcolumn_to_updatedplusoutput_columnslist printed as if it were a scope, not a second problem.Workflow [PR]
Sync PR [sync-upstream/pr/118499]