Skip to content

MergeTree: do not mutate an empty part that cleanup is about to drop - #118499

Closed
groeneai wants to merge 13 commits into
ClickHouse:masterfrom
groeneai:fix-mutation-of-empty-part-after-restart
Closed

groeneai wants to merge 13 commits into
ClickHouse:masterfrom
groeneai:fix-mutation-of-empty-part-after-restart

Conversation

@groeneai

@groeneai groeneai commented Sep 7, 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):

An empty part that background cleanup is about to drop is no longer selected for mutation on non-replicated MergeTree tables, and system.mutations now reports why. Previously a server restart could revive such a part, left behind by ALTER TABLE ... DETACH PART, and start a mutation on it that cannot succeed, logging UNKNOWN_IDENTIFIER roughly once a second until cleanup removed the part.

Description

Closes: #120975
Related: #104510 (reported there).

A restart can revive an empty DETACH PART tombstone as Active, and mutation selection picks it up: its columns.txt still lists a column since renamed away and the renaming mutation entry is gone, so every attempt fails with UNKNOWN_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 clearEmptyParts stays inert until outdated-part loading finishes, while StorageMergeTree::startup has already started mutation scheduling. The fix skips a zero-row part in selectPartsToMutate under the droppability conditions clearEmptyParts itself applies, and only while cleanup is running, since those conditions say the part would be dropped, not that anything will. Under SYSTEM STOP CLEANUP it 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_seconds nor 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 = 0 arms, and a stateless test for an uncommitted empty part, each redden when their own condition is removed. 04653_mutation_rewrite_stale_part_column_type is unchanged.

The alternative, ordering clearEmptyParts before mutation scheduling starts, would serialise startup behind an asynchronous load. Whether a non-empty wide part with a stale READ_COLUMN behaves 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_1 is the empty tombstone left by DETACH PART, revived Active by the restart because "will drop empty part" is in-memory intent only:

17:06:53.381  Loading Active part all_1_1_1 from disk cached_s3
17:06:54.623  Found 2 outdated data parts. They will be loaded asynchronously
17:06:54.626  Loading mutation: mutation_2.txt entry, commands size: 1
17:07:02.639  Loading 2 outdated data parts asynchronously
17:07:02.642  {...::all_1_1_1_5} MutateTask: Mutating part all_1_1_1 to mutation version 5
17:07:02.645  first  MutatePlainMergeTreeTask: Code: 47 ... UNKNOWN_IDENTIFIER
17:07:03.297  Loaded 2 outdated data parts asynchronously
17:07:34.798  last   MutatePlainMergeTreeTask: Code: 47 ... UNKNOWN_IDENTIFIER   (147 lines)
17:07:35.060  t_stale_part_type_5: Will drop empty part all_1_1_1

mutation_4.txt, the RENAME COLUMN b TO d, is absent from the load in this artifact: a concurrent test's KILL MUTATION filters only on database = 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 at 9e46ee24a0a6 all three entries load and the burst is identical, because the rename ALTER changes the metadata whether or not its mutation entry survives, so a revived part owing MODIFY COLUMN b alone can never resolve b, 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. with all_1_1_1_2 is mutation 2 alone, In scope b, b, c. with all_1_1_1_5 is mutations 2 and 5 batched. The repeated b is the synthesized column_to_updated plus output_columns list printed as if it were a scope, not a second problem.


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

groeneai and others added 3 commits September 6, 2026 22:53
`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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 7, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Three review rounds, 9 AGREE and 2 DISAGREE. Every AGREEd finding was sent back for a fix before this
was pushed; the DISAGREEs are recorded here with their evidence rather than dropped.

  • ❌ Skipping an empty part assumed something would drop it. Twice false: under SYSTEM STOP CLEANUP
    nothing calls clearEmptyParts (round 1), and merge_tree_clear_old_parts_interval_seconds can defer
    it arbitrarily even when cleanup is running (round 2). Either way a synchronous ALTER that used to
    return at once stopped returning. Fixed: the part is only skipped while that removal can actually
    happen, and skipping asks for it directly instead of just waking the thread.
  • ⚠️ Four test-liveness gaps: the regression test relied on winning the startup race, the promised
    system.mutations postpone reason was asserted nowhere, the transaction-visibility condition had only
    a regression probe, and the interval mechanism had no arm at all. Fixed: the outdated-part loading
    delay is pinned, and each condition of the guard now has an arm that reddens when that condition alone
    is removed, including a stateless test for the uncommitted-part case.
  • 💡 Title and changelog were unqualified while the replicated selector keeps the old behaviour; both are
    now scoped, and the deferral is stated in the description rather than implied. The description also no
    longer says the replicated selector "has the same gap": what I checked is that it carries no such
    guard, which is not the same as showing the burst is reachable there, so it now says exactly that.
  • ✅ Kept Improvement rather than Bug Fix: with the default remove_empty_parts = 1 the observed
    consequence is a bounded, self-healing error burst (147 lines over 32 s, then the part is dropped and
    the mutation completes), and the permanently stuck case is the remove_empty_parts = 0 arm, which this
    PR deliberately leaves alone. Happy to switch if you would rather have it under Bug Fix.
  • ✅ Round 3 raised one more, and I did not change the code for it: dropping the part completes the
    mutation without retiring mutation_counters, so system.tables.active_on_fly_data_mutations
    over-reports and getColumnDefaultnessStatsUnavailableReason conservatively declines a stat until the
    next periodic pass. Three reasons. The window is one merge_tree_clear_old_parts_interval_seconds,
    which defaults to 1, and the requested cleanup only runs inside that interval. The effect is a
    monitoring column and a skipped optimisation, never a result: on-the-fly commands are filtered per part
    by mutation_version <= part_data_version, and every part surviving the drop is already at or past it,
    while system.mutations and mutations_sync read visible parts' data versions rather than that
    counter. And completion by part removal is already an unattributed event here, named as such in
    markFinishedMutations, shared with DROP PARTITION, and present in the periodic branch too, where
    clearOldMutations runs before clearEmptyParts. If you would rather have counters retired at every
    removal event, that is broader than this PR and I am glad to do it separately.
  • 💡 Noted, not changed: rows_count == 0 open-codes isEmpty(), kept for textual parity with
    clearEmptyParts, whose conditions the guard mirrors; and the guard does not mirror that function's
    outdated_data_parts_loading_finished early return, which is a timing gate that clears on its own and
    is the reason selection wins the race in the first place.

@clickhouse-gh clickhouse-gh Bot closed this Sep 7, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 7, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. python3 -m ci.praktika run "integration" --test "test_mutation_empty_part_after_restart" fails on base every run, not at some percentage. The test arms the carrier by construction: old_parts_lifetime = 10000 keeps the empty part on disk across the restart instead of relying on timing, and sleep_before_loading_outdated_parts_ms = 30000 pins the post-restart window that used to decide the race (measured: the tombstone stays Active until t+31.03 s instead of the 0.65 s seen in the CI artifact). The armed state is asserted both before and after the restart, so a run that did not arm fails loudly rather than passing vacuously.
b Root cause explained? Yes, and it has two independent halves. (1) DETACH PART replaces the part with an empty tombstone whose columns.txt is written at detach time, so it keeps the pre-rename column list. A restart inside the cleanup window revives it Active, clearEmptyParts returns early while outdated parts load, and StorageMergeTree::startup has already started mutation scheduling, so selection reaches the part first; the wide branch of splitAndModifyMutationCommands gates its READ_COLUMN arm on the part only (part_columns.has("b") is true), so the stale command is forwarded and MutationsInterpreter cannot resolve b against current metadata. Each attempt takes a fresh snapshot, so it cannot self-heal. (2) Skipping the part is only correct if something actually performs the removal, and the periodic path is gated behind merge_tree_clear_old_parts_interval_seconds, which a table may set arbitrarily high; a bare wakeup() schedules an iteration but does not make that gate grant.
c Fix matches root cause? Yes, and at the source, in both halves. The guard is in mutation selection, not at the throw site: it stops the pointless work from being scheduled, and it fires only for a part that already owes a mutation. It is not a widened bound, a no-random-* tag, a data-size reduction or a defensive check masking an upstream problem. Guarding the READ_COLUMN arm instead was considered and rejected, because that is the symptom site and its safety argument holds only for an empty part. For the second half, the skip issues a targeted requestEmptyPartsCleanup() that clearEmptyParts honours on the next iteration outside the shared period, rather than restarting the stopwatch (which would push the removal out by a full interval) or calling clearEmptyParts from the selector (self-deadlock on currently_processing_in_background_mutex).
d Test intent preserved / new tests added? Yes. 04653_mutation_rewrite_stale_part_column_type, whose part this is, is untouched and still passes: it is correct and it is what exposed the defect. New coverage: an integration module with three arms (the restart carrier, plus SYSTEM STOP CLEANUP and remove_empty_parts = 0 arms where behaviour must not change and which redden if their own condition is removed, plus a pinned-interval arm), and one stateless test for the transaction-visibility condition. Every arm is shown to redden against a specific condition of the diff.
e Both directions demonstrated? Yes, on six Build-ID-verified binaries, each condition of the diff reddened separately. Base 039909e1... fails the restart arm with the byte-identical CI signature (Unknown expression identifier `b`. Maybe you meant: ['a']. In scope b, b, c.); fix a0057a78... passes every arm; with the targeted cleanup request reverted to a bare wakeup(), c1bf2155..., the pinned-interval arm fails with TIMEOUT_EXCEEDED; with the postpone-reason line removed, 3449539d..., the reason assertion fails against an empty parts_postpone_reasons; with the transaction-visibility condition removed, 73742122..., the stateless transaction test fails with TIMEOUT_EXCEEDED; with the whole guard made runtime-opaque-false, 347a8a0f..., the restart arm fails with the CI signature again. Restoring the fix sources reproduced a0057a78... bit-for-bit, so the rows differ by source, not by build noise.
f Fix is general across code paths? Checked each carrier. The replicated engine does not use this function: selectPartsToMutate is a StorageMergeTree member and StorageReplicatedMergeTree assigns mutations through the replication queue, and all 36 CIDB rows are MutatePlainMergeTreeTask, the plain engine. Left out of scope deliberately, with no observed carrier, and named in the description. The compact and non-full-storage branch is covered by #115962, which is why these stay separate PRs. The three foreground clearEmptyParts callers (truncate, dropPart, dropPartition) need no request because they run it inline; the two periodic callers are the ones the request reaches. I have not measured whether a non-empty wide part with a stale READ_COLUMN behaves the same, and there is no such carrier in 30 days of CI data; stated as unmeasured in the description rather than as a claim.
g Fix generalizes across inputs (params/datatypes/wrappers)? The predicate keys on rows_count == 0, which is independent of column types and of Nullable / LowCardinality / Array / Map / Const wrappers, and of the mutation command shape. Mutation-count matrix is covered because both CI message variants are the same part mutated toward one and toward two batched mutations. Part storage: Wide plus full storage is asserted in the test, Compact is #115962's shape. Settings matrix: both values of remove_empty_parts (the second as a live control arm), cleanup blocked and running, and merge_tree_clear_old_parts_interval_seconds at its default and at 100000. Transaction visibility is covered by its own arm at both values of the condition.
h Backward compatible? (maintainer-approved exception only) Yes. No new setting, no default change, no format or serialization change, so no SettingsChangesHistory.cpp entry and no versioning gate. Behaviour changes only for zero-row parts that were already queued for deletion, and with remove_empty_parts = 0 or cleanup stopped it is unchanged, which two control arms assert. The added cleanup request only ever causes clearEmptyParts to run earlier than the shared period would; nothing else in the periodic block moves.
i Invariants and contracts preserved? The guard sits in the same loop under currently_processing_in_background_mutex as the rest of the chain, as that site's own comment requires, so part tagging is unaffected. requestEmptyPartsCleanup() sets a relaxed atomic and calls wakeup(), which takes only the schedule pool's own mutex and never runs the cleanup body, so no lock-order edge is added at the skip site (onActionLockRemove already makes the same wakeup() call at this layer); calling clearEmptyParts from the selector instead would self-deadlock on that mutex through outdatePart. On the consuming side the call stays inside iterate() under the same lockForShare that covers the periodic call, and the request is consumed with a single exchange, so a request cannot be lost while an iteration is in flight nor serviced twice. The invariant that matters is that no mutation is left permanently unfinishable: mirroring clearEmptyParts' droppability conditions establishes that the part would be dropped, and the cleanup-blocker check plus the targeted request establish that something actually will, at both extremes of the interval setting. clearEmptyParts' outdated_data_parts_loading_finished early return is deliberately not mirrored, since it is a timing gate rather than a droppability property, and mirroring it would leave the part neither mutated nor dropped. The test asserts is_done = 1 with an empty latest_fail_reason, and that no mutated descendant of the part was produced, so the mutation completes by the drop. No change to command splitting, mutation execution, cleanup ordering or startup ordering.

Session id: cron:clickhouse-impl-slot-6:20260906-234000

@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c1d1044]

Summary: ✅


AI Review

Summary

This PR makes non-replicated MergeTree mutation selection skip restart-revived empty parts and wake cleanup to remove them, which matches the intended fix for the stale DETACH PART tombstone race. I found one remaining blocker: the new skip predicate has drifted behind clearEmptyParts on UNIQUE KEY tables, so 0-row marker parts that still hold delete bitmaps are postponed as EMPTY_PART_WILL_BE_DROPPED even though cleanup explicitly refuses to drop them.

Findings

❌ Blockers

  • [src/Storages/StorageMergeTree.cpp:2431] The new "skip because cleanup will drop it" contract is no longer equivalent to clearEmptyParts: clearEmptyParts also rejects parts pinned by delete bitmaps (src/Storages/MergeTree/MergeTreeData.cpp:5171), and UNIQUE KEY DELETE creates exactly such 0-row marker parts to hold the only copy of those bitmaps (src/Storages/MergeTree/UniqueKey/UniqueKeyTxnCommit.cpp:742, src/Storages/MergeTree/UniqueKey/UniqueKeyTxnCommit.cpp:772). A later mutation on that table will therefore keep postponing the marker as EMPTY_PART_WILL_BE_DROPPED even though cleanup cannot remove it yet, so mutations_sync = 1 can now wait for old_parts_lifetime or forever under SYSTEM STOP CLEANUP on a supported UNIQUE KEY path.
    Suggested fix: mirror the delete-bitmap pin check here too, or extract a shared "cleanup can drop this empty part now" helper used by both selectPartsToMutate and clearEmptyParts, then add a regression with a UNIQUE KEY delete marker followed by a mutation.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: stop skipping empty parts that clearEmptyParts refuses to drop because they are pinned by delete bitmaps, and cover the UNIQUE KEY marker-part case with a regression.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Sep 7, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @tavplubix, could you review this? After a restart revives an empty DETACH PART tombstone as Active, mutation selection can pick it up and retry a mutation that can never resolve a since-renamed column, so this skips a zero-row part in selectPartsToMutate while cleanup can actually remove it, and asks cleanup for that removal rather than waiting for the period it shares with the other part cleanups.

@tiandiwonder tiandiwonder self-assigned this Sep 7, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). label Sep 7, 2026
Comment thread src/Storages/StorageMergeTree.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c1d1044d2 with master 63341c236 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of dca38d441; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

groeneai and others added 2 commits September 7, 2026 03:26
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 tiandiwonder left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

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 MergeTreeBackgroundExecutor: Exception while executing background task {...}, from the throw; at the end of that catch. In the 1a2a532f upgrade-check log the 147 <Error> lines split exactly 49 / 49 / 49 across MutatePlainMergeTreeTask (the LOG_ERROR), virtual bool DB::MutatePlainMergeTreeTask::executeStep() (the tryLogCurrentException) and MergeTreeBackgroundExecutor, and there are exactly 49 MutateTask: Mutating part all_1_1_1 to mutation version 5 traces to match.

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 According to exponential backoff policy ... lines, for any part, with Debug enabled.

The reason is tests/config/config.d/backoff_policy.xml, installed unconditionally by tests/config/install.sh:138: it sets max_postpone_time_for_failed_mutations_ms = 200 against a product default of 300000. That makes max_postpone_power = floor(log2(200)) = 7, so (1 << retry_count) * 1000us saturates at 128 ms, permanently below the selection cadence. Your scratch server ran the default: power 18, ceiling 262 s. Nothing is wrong on the recording side, the failure is registered under the source part name all_1_1_1 through the result_part->part_info.mutation == it->first branch; the entry just never gets old enough to matter at a 128 ms ceiling.

A/B on one debug-master server, two tables, only that setting differing, UPDATE b = throwIf(1):

max_postpone_time_for_failed_mutations_ms failures window intervals backoff-postpone lines
200 (what CI installs) 245 150.1 s 0.14 to 1.11 s, no growth 1
300000 (default) 17 141.0 s 10 sub-second, then 1.97, 2.66, 4.39, 8.38, 17.41, 33.15, 66.77 s 83

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 (tests/docker_scripts/upgrade_runner.sh:624-627), so one surviving <Error> line is enough. Replaying the default-config cadence into the 32.155 s the wedge actually lasted gives 14 failures and 42 error lines, still red. So the ceiling sets the burst size, not the outcome, and there is no engine amplifier behind it to fix: the 200 ms value is deliberate, it keeps the tests that exercise this policy fast, and production already runs the arithmetic you measured. The selection guard removes the burst rather than spacing it out, so I would keep this PR as it stands, with non-empty parts out of scope as before.

@clickhouse-gh

clickhouse-gh Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

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.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 16 not_sure 512 586 +14.4% <0.0001 aggregation: This query is a GROUP BY aggregation (+14.4%), and the PR only changes mutation scheduling and the background cleanup thread. That code is not on this SELECT path, and the median sits inside master's normal range for this noisy query.
⚠️ 18 not_sure 800 915 +14.4% 0.0016 aggregation: This query is a heavy GROUP BY (+14.4%) with noisy history on both sides. The PR's changes to empty-part mutation skipping and cleanup wakeups never run during a read-only aggregation, so nothing here can be attributed to the 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

🟢 No significant changes

Debug info
  • StressHouse run: 504256e2-809f-4607-bc7a-f32aa51caf7c
  • MIRAI run: b90600ac-257d-4707-a94c-ff28d82ef404
  • PR check IDs:
    • clickbench_944679_1791759376
    • clickbench_944692_1791759376
    • clickbench_944698_1791759376
    • tpch_adapted_1_official_944704_1791759376
    • tpch_adapted_1_official_944731_1791759376
    • tpch_adapted_1_official_944750_1791759376

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

Copy link
Copy Markdown
Collaborator Author

@tiandiwonder, I merged master to resolve a conflict in MergeTreeMutationStatus.h (master's UNREGISTERED_MUTATION and this PR's EMPTY_PART_WILL_BE_DROPPED were added on the same line; both are kept). The PR's own diff is unchanged by the merge.

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 isVisibleByLatestSnapshot(), the helper clearEmptyParts uses now) and two cleanups (aac4c63, f1f3e3d). On the merged tree the integration test passes 4/4 and 29 related stateless tests pass.

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]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

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-request PR origin: a maintainer pinged or directed groeneai pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Upgrade check: mutation of an empty DETACH PART tombstone revived by a restart retries UNKNOWN_IDENTIFIER until cleanup drops it

2 participants