Skip to content

Refuse DETACH and MOVE PARTITION while a mutation is still pending for the part - #121032

Closed
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/refuse-detach-of-part-with-unapplied-mutation
Closed

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/refuse-detach-of-part-with-unapplied-mutation

Conversation

@groeneai

@groeneai groeneai commented Sep 19, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

On plain MergeTree, ALTER TABLE ... DETACH PART, DETACH PARTITION and MOVE PARTITION TO TABLE are now refused while an unfinished UPDATE, DELETE or metadata mutation is still pending for one of the affected parts. Previously such a removal marked the mutation is_done = 1 without touching the rows, and re-attaching the part brought them back unmutated, so an acknowledged ALTER TABLE ... UPDATE/DELETE was permanently and silently not applied. DROP PART, DROP PARTITION and TRUNCATE are unchanged, since they destroy the data. Closes #120902.

Description

A mutation completes when no active part still owes it: removing one completes it. Right for
DROP and TTL; wrong for DETACH and MOVE PARTITION: the data returns renumbered above every mutation
version, all that mutation assignment and on-fly conversions key on. alter/index.mdx:63
guarantees data inserted before a mutation gets mutated; that breaks for every command.

The three are refused while a mutation is pending for an affected part: the heavyweight
twin of the patch-part guard a91e82954c2, at three of its four call sites; the fourth,
replacePartitionFrom, narrows nothing (its source keeps its parts, its destination destroys them). What a part owes is asked of the executor's own predicate,
canSkipMutationCommandForPart: per command, regular parts only, and for a transactional mutation only
parts visible at its snapshot. A mutation whose WHERE matches no row in the part is refused too:
only reading the part settles that. The alter lock is taken before the merge blocker, so nothing
registers behind the check. Two gaps remain: a part another transaction makes visible between check and
removal (experimental transactions only), and an IN PARTITION value that resolves differently per
reader, since the scope is re-evaluated, not resolved once: a partition id from
session_timezone or currentQueryID(), or a subquery evaluated under the alter lock.

Two pre-existing bugs too. mutate declared its AlterLockHolder in an if init-statement, so it died
before startMutation, serialising nothing. And the patch guard ran only while
supportsLightweightUpdate() held, which MODIFY SETTING enable_block_number_column = 0 turns false
while the patch still applies on read: sum(v) went 110 to 10. It now keys on patch parts.

ReplicatedMergeTree loses it the same way (ReplicatedMergeTreeQueue.cpp:453 drops the part from
parts_to_do, :2573 completes an empty one), but a sound condition there has to come from the queue,
not the initiator. Follow-up, or fold it in here?


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

groeneai and others added 2 commits September 19, 2026 13:52
…r the part

A mutation's done-ness is derived from the currently active parts alone
(getMutationsStatus recomputes it on every query), so taking a part out of the
table completes any mutation that was still waiting for it. For DROP and TTL
that is correct: the data is gone, so nothing is left to rewrite, which is the
semantic the comment above markFinishedMutations already states.

For DETACH PART, DETACH PARTITION and MOVE PARTITION TO TABLE it is not
correct, because the data is recoverable and comes back out of the mutation's
scope. Mutation versions and part block numbers are drawn from one monotone
counter, and a part needs mutation V iff V > part->info.getDataVersion();
fillNewPartNameAndResetLevel gives an adopted part a fresh block number and
info.mutation = 0, so its data version is necessarily above every existing
mutation version. Both the mutation assignment (selectPartsToMutate) and the
on-fly conversions (MutationsSnapshot::getOnFlyMutationCommandsForPart) select
on that comparison alone, so nothing can ever apply the mutation to the part
again. A reversible removal therefore narrows an acknowledged mutation's scope
permanently, and the reversal cannot restore the obligation. That contradicts
the point-in-time rule documented in
docs/reference/statements/alter/index.mdx:63, and it drops every command kind,
not only UPDATE and DELETE: after a detach/attach round trip a pending
RENAME COLUMN leaves the renamed column reading as defaults.

Refuse those three commands while a mutation still has to rewrite one of the
affected parts. This is the heavyweight-mutation twin of the patch-part guard
a91e829, at three of that guard's four call sites, with the same
SUPPORT_IS_DISABLED code, so a client that already handles "this partition
command is blocked by an unapplied update" keeps working. The fourth,
replacePartitionFrom's source side, needs nothing: the source keeps its parts,
so no obligation is narrowed there. Whether a part is owed anything is asked of
the mutation executor's own canSkipMutationCommandForPart rather than
reconstructed, so the guard cannot drift from what the executor does, and the
context it is evaluated under is built by the createContextForMutationRead both
callers now share, because that predicate can run an IN PARTITION value as a
query and two of those settings decide its answer: apply_mutations_on_fly,
which would let the value read another table with that table's own pending
mutations applied, and force_primary_key, which would make the read throw where
the executor's does not. A command scoped to another partition, an APPLY
PATCHES, an APPLY DELETED MASK on a part with no lightweight delete, and a
metadata-only Nullable or Variant widening are correctly not obligations,
because MutateTask clones such a part forward untouched. A mutation whose
transaction was rolled back is skipped, as selectPartsToMutate skips it: it
will never run, so it owes nothing.

The guard judges regular parts only, because a heavy mutation rewrites only
those: selectPartsToMutate walks getDataPartsVectorForInternalUsage(), which
filters to DataPartKind::Regular. Two of the three call sites can nevertheless
hand it patch parts. dropPartition's explicit-partition branch enumerates with
getVisibleDataPartsVectorInPartition, which indexes data_parts_by_state_and_info
by {state, partition_id} with no kind filter, so a patch partition id returns the
patch parts, and dropPart resolves by name through the equally kind-agnostic
getPartIfExists. Without the filter, a pending whole-table UPDATE made
DETACH PARTITION ID '<patch partition>' fail naming a part mutation would never
touch, and the neighbouring patch guard does not mask it: isPatchForPartition
compares a patch's ORIGINAL partition id, so asking for the patches of a patch
partition returns none and assertNoPatchesForParts early-returns. Measured on the
unfixed build: refused with "mutation with version 4 has not been applied to part
patch-<hash>-all_3_3_0_2 yet", a detach that
05046_lwu_patch_partition_detach_attach.sh already relies on succeeding.

A transactional mutation is additionally asked whether the part was visible at
its own snapshot, mirroring selectPartsToMutate: when the mutation's tid is
transactional and the part was not visible to it, the executor skips that part
permanently, and master's comment there records that such a part is not going to
be mutated, so it owes that mutation nothing. Only that branch is mirrored. The
non-transactional branch merely postpones an invisible part
(current_parts_postpone_reasons) and rewrites it once it becomes visible, so
there the obligation stands and copying the check would open a real hole. The
skip is per mutation, not per part, because each transaction has its own snapshot
and a part invisible to one may still be owed to another. Reachable with
01168_mutations_isolation.sh's ordering: a part another transaction commits after
the mutation transaction's snapshot but numbered below the mutation version is
never rewritten, the mutation stays is_done = 0 with parts_to_do = 1
indefinitely, and without this the part could never be detached at all.

The guard runs under the table's alter lock, taken before the merge blocker and
with no parts lock held. Both orderings are deadlock-critical. Taken after the
merge blocker it would deadlock against a barrier ALTER that holds the alter
lock while waiting for a mutation to finish, since the blocker is what stops
that mutation from running. Holding the parts lock across the call would invert
the established currently_processing_in_background_mutex -> parts lock order.
movePartitionToTable takes only the source table's alter lock, never both
tables', to avoid an ABBA between two concurrent opposite moves.

currently_processing_in_background_mutex is taken once, for a snapshot of the
metadata handle and the registered commands, and the predicate is evaluated
after releasing it. That split is required, not tidiness: MutationCommand::ast()
re-parses the stored command text on every call, and for an IN PARTITION value
canSkipMutationCommandForPart reaches evaluateConstantExpression, which executes
a subquery if the value contains one. ParserPartition constrains only the
top-level node, so UPDATE ... IN PARTITION tuple((SELECT p FROM t LIMIT 1))
parses and is stored, and evaluating it reads t, which reaches
getMutationsSnapshot and locks that same non-recursive mutex. Measured: with the
predicate under the mutex, that statement followed by DETACH PART hangs
indefinitely; with the snapshot split out it returns the refusal. Correctness
does not rest on the mutex either way, since the alter lock is what makes the
check and the commit atomic. The same split also stops the guard re-copying
StorageInMemoryMetadata and re-parsing every command once per part.

The parts the guard validates are the pre-removal snapshot, while
MergeTreeData::Transaction::commit computes the authoritative removed set, which
can be wider. The only path that makes an already-covered part Active again is
MergeTreeTransaction::rollback, so the window needs
allow_experimental_transactions; widening the guard to rollbackable Outdated
parts would instead cause false refusals in ordinary setups, because an Outdated
part's data version is at or below its coverer's.

That lock only serialises anything after a second, pre-existing bug is fixed:
StorageMergeTree::mutate declared its AlterLockHolder in an if init-statement,
whose scope is the if statement, so the holder was destroyed one line before
startMutation and the serialisation its own comment promises ("It's important
to serialize order of mutations with alter queries") never happened. Hoist it
into the enclosing block. Reverting only that hoist makes the new race test
fail, so it is load-bearing here and not cosmetic.

A third, also pre-existing bug is fixed in the same block. Patch
materialisation is not this guard's business: canSkipMutationCommandForPart
skips APPLY_PATCHES, and MutateTask appends the patch-sourced rewrite outside
that predicate as READ_COLUMN with read_for_patch, so the patch guard above owns
it. But that guard ran only while supportsLightweightUpdate() held, and support
turns false as soon as enable_block_number_column or enable_block_offset_column
is set to 0, which MODIFY SETTING allows after CREATE. Nothing on the read path
is gated that way: getPatchPartsVectorForPartition, getMutationsSnapshot and
assertNoPatchesForParts all key on the parts. So the patch kept applying on
SELECT while the guard protecting it had switched itself off, and a detach and
re-attach silently reverted the update, with is_done already 1 -- this issue's
consequence through a sibling door. Measured on master: sum(v) goes 110 -> 10.
Drop the capability condition from both DETACH patch guards so they ask whether
patch parts exist, which is what the obligation depends on; the sibling guards
in replacePartitionFrom and movePartitionToTable already keyed on the parts.
The removal only adds refusals: assertNoPatchesForParts counts only patches
whose data version is above the part's, and is a no-op when there are none.

The refusal names the mutation the user has to act on: it prints the mutation_id
that system.mutations reports for it, and the KILL MUTATION statement that
removes it, instead of pointing at system.mutations. KILL MUTATION selects on
mutation_id, which the version alone does not give.

Scope is plain MergeTree. ReplicatedMergeTree has the same defect, but an
initiator-local check cannot fix it: a replica that has not yet executed
MUTATE_PART still holds the pre-mutation part while the initiator's copy is
already past it, so each replica's detached/ holds its own copy at its own
mutation version and a sound condition has to be evaluated against Keeper for
every replica. Nothing here is shaped around that: the helpers stay private to
StorageMergeTree.

Four tests. The .sql file covers the three refusals, asserts that a refusal
leaves the mutation, the parts and the data untouched, and carries the controls
that define the boundary: DROP PART and DROP PARTITION stay allowed with the
same pending mutation, a command scoped to another partition and a skippable
metadata-only conversion do not refuse, a pending RENAME COLUMN does, and the
whole round trip works again once the mutation is materialised. The .sh file is
the concurrency oracle: it drives mt_pause_before_register_mutation so the
mutation is published while a DETACH is in flight, and asserts the DETACH is
blocked rather than winning the race. A tenth block covers the patch guard with
support switched off after the patch exists, and both tests pin
alter_update_mode and apply_mutations_on_fly, which the stress runner randomizes
as client options: both read a table while a heavy mutation is deliberately
pending and assert the pre-mutation value. Two further shell tests cover the two
domain limits, neither expressible in .sql: a patch partition id carries a
structure hash and has to be read at runtime, and the other needs transactions.
The first asserts that DETACH PARTITION ID of a patch partition is allowed while
a heavy mutation is pending, and that the base partition is still refused in the
same state. The second builds 01168's transaction ordering and asserts that the
part invisible to the mutation's snapshot can be detached, while a plain pending
mutation on another table is still refused, so neither can pass with the guard
removed altogether. A third table covers the complement of that skip, holding a
transactional ALTER at storage_shared_merge_tree_mutate_pause_before_wait the way
01168_mutations_isolation_3.sh's last block does, so a part that IS visible to a
registered, unfinished transactional mutation is refused; without that arm the
visibility conjunct could be deleted with every test still passing. The failpoint
is process-global, hence no-parallel on that file.

No existing test needed changing.

Closes: ClickHouse#120902

Co-Authored-By: Claude Opus 5 <[email protected]>
Remove comments narrating the new code's own design (lock placement, loop bounds, early returns, message ordering, a deleted-conversion workaround) and condense the surviving lock-order and pre-existing-semantics invariants. No code or test change.
@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 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 26 findings over 7 gate passes and
6 fix rounds), adjudicated against a repro and single-change mutation arms.

bounce cap reached: published as-is; residual findings listed below. Nothing unresolved is a
blocker or a major. Rows 15, 16 and 17 are the residuals, each disclosed in the description as an
open gap rather than claimed as fixed.

# Sev Finding Verdict Evidence / action
1 ❌ Both patch guards were gated on supportsLightweightUpdate(), which MODIFY SETTING enable_block_number_column = 0 turns false while the patch still applies on read AGREE, fixed @ dfd3b8da94dc1 Measured bypass on master: DETACH then ATTACH took sum(v) 110 back to 10. Both guards now key on the patch parts themselves.
2 ❌ The guard evaluated the executor's predicate under a different context, so an IN PARTITION expression could resolve differently and let an affected part be removed AGREE, one axis fixed @ f0e2407, the other disclosed Both callers now build that context through one shared createContextForMutationRead, so they cannot drift. The session_timezone axis stays open: DateLUT::instance() reads it from the running thread, never from the context argument (DateLUT.cpp:166-192). Named in the description.
3 ❌ ReplicatedMergeTree loses the same obligation and has no equivalent guard (ReplicatedMergeTreeQueue.cpp:453 drops the part from parts_to_do, :2573 completes an empty one) AGREE Not folded in: the obligation source is the replication queue, a different subsystem with no single-node oracle, and the reported repro is plain MergeTree. The gap and where the fix should land are in the description.
4 ❌ Transactional DETACH is not fenced through transaction commit, and a rollback can enlarge the authoritative covered set after the guard runs DISAGREE on scope, AGREE the window exists The only Active-restoring path is restoreAndActivatePart (MergeTreeData.cpp:7423), whose single caller is MergeTreeTransaction::rollback, so it needs experimental transactions and is reachable identically through DROP PART: a defect of transactional part removal, not of this guard.
5 ❌ A lightweight UPDATE holds only a share lock, so it can publish a patch part between the DETACH's patch snapshot and its removal of the base part DISAGREE on layer, AGREE the race exists A pre-existing race in the patch guard (a91e82954c2), not in the mutation guard added here. This PR's only change to that guard removes its capability gate, so it fires in strictly more states and the window narrows.
6 ⚠️ Both new tests inherited the stress runner's randomization of apply_mutations_on_fly and alter_update_mode (stress.py:545, :560), which breaks them AGREE, fixed @ dfd3b8da94dc1 Both read a table while a heavy mutation is deliberately pending. Pinned per statement, with a negative control proving the pins load-bearing in both directions.
7 ⚠️ The guard judged patch parts, so DETACH PARTITION ID '<patch partition>' was refused while an unrelated whole-table mutation was pending AGREE, fixed @ 2ae22dc88d09c Restricted to regular parts, which is what selectPartsToMutate walks (MergeTreeData.cpp:11281), with the base partition's refusal asserted in the same state so the arm cannot pass with the guard removed.
8 ⚠️ The snapshot dropped each mutation's tid, so the guard could not reproduce the executor's transactional visibility skip and refused a part the mutation will never rewrite AGREE, fixed @ 2ae22dc88d09c Only the transactional branch is mirrored: the non-transactional branch merely postpones the part, which still owes the rewrite.
9 ⚠️ The guard evaluated mutation command ASTs under currently_processing_in_background_mutex, and that predicate can reach evaluateConstantExpression for an IN PARTITION value AGREE, fixed @ 4a9fa3dbe12a0 IN PARTITION tuple((SELECT ...)) re-entered the same non-recursive mutex and hung; it refuses cleanly now. The mutex is held only for a snapshot, and the predicate runs outside it.
10 ⚠️ The transactional-visibility skip is a conjunction and only the whole statement had an oracle: removing just part->version->isVisible(...) left all four tests green AGREE, fixed @ 22c6ef4f325ff The dangerous direction. A binary carrying that conjunct's removal alone now reddens the new assertions and not the old one.
11 ⚠️ The PR called itself the twin of the patch-part guard "at these same call sites", but that guard has four in this file and this one has three AGREE, fixed @ 4a9fa3dbe12a0 Wording corrected and the exclusion stated: replacePartitionFrom's source keeps its parts, so no obligation is narrowed.
12 ⚠️ The description claimed the guard "claims no more than" the executor does, and the title said the mutation "still has to rewrite" the part AGREE, contract corrected The executor has a second skip the guard does not mirror (isStorageTouchedByMutations, MutateTask.cpp:4014), so a pending UPDATE/DELETE matching no row in the part is refused too. Title, changelog entry and description now say so.
13 💡 Nine smaller items AGREE, fixed A rolled-back mutation no longer counts as an obligation; one message per statement instead of two; the refusal prints a copy-pasteable KILL MUTATION keyed on mutation_id, proved as printed including a database name needing quoting; stale "same guard as the Replicated engine" comments removed; the alter-lock timeout message names DETACH and MOVE PARTITION; dropPart resolves the part once for both guards.
14 💡 Eight declined DISAGREE Chiefly: Critical Bug Fix is not self-assigned here (my precedent for this shape, #107386, shipped as Bug Fix, and the entry states the impact plainly so it can be retagged in one click); the per-mutation transactional skip over-refuses rather than over-permits; catching the predicate's throw would turn a loud error into a silent allow; dropPartition's double partition resolution is under the alter lock and the merge blocker, so the two readings cannot disagree.
15 💡 DETACH PARTITION ALL reaches the guard through dropPartition's partition_ast->all branch, which no new test exercises; the multi-partition loop has no oracle either AGREE, not fixed Real (ParserPartition.cpp:41), low risk: both guards are invoked identically per partition id and the parts filter is kind-agnostic, so the branch differs only in how parts are collected. Left for a follow-up test rather than added after the last review round.
16 💡 The transactional visibility skip is evaluated per mutation, while the executor decides on the first pending mutation and then skips the whole part AGREE, not fixed So a part invisible to one transactional mutation but owed to a later one is refused although nothing will rewrite it. Over-refusal only, never a permitted removal, and the refusal prints the KILL MUTATION that clears it.
17 💡 The session_timezone axis of row 2 stays open AGREE, not fixed, disclosed Predates the guard: mutate validates an IN PARTITION expression under the submitting user's context (StorageMergeTree.cpp:1218-1233) while the executor resolves it on a background thread. Named in the description.

Session id: cron:clickhouse-review-slot-48:20260919-140100

@clickhouse-gh clickhouse-gh Bot closed this Sep 19, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ca85257]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_tsan, 2/6) FAIL
test_replicated_database_active_node_taken/test.py::test_active_node_owned_by_another_server FAIL cidb

AI Review

Summary

This PR adds the missing plain-MergeTree refusals for reversible part removal while a mutation is still pending, aligns the guard with makeQueryContextForMutate, and adds focused coverage for the main detach/move cases. I still see one blocker: the new guard still re-evaluates IN PARTITION in a different runtime context than the real mutation task, so runtime-dependent scopes can still let an owed part escape and take the same "mutation marked done without rewriting rows" path this PR is supposed to close.

Findings

❌ Blockers

  • [src/Storages/StorageMergeTree.cpp:2541-2545] The new refusal still is not executor-equivalent for runtime-dependent IN PARTITION expressions. assertNoUnappliedMutationsForParts builds one synthetic background context and re-runs getPartitionIDFromQuery, but the actual mutation task evaluates the same AST under a per-task query context instead (src/Storages/MergeTree/MutatePlainMergeTreeTask.cpp:207-210). That still diverges on context-sensitive carriers: currentQueryID() captures context->getCurrentQueryId() (src/Functions/currentQueryID.cpp:18-20), and timezone-sensitive expressions ignore the passed context and read CurrentThread's query context (src/Common/DateLUT.cpp:204-208). So IN PARTITION scopes that depend on currentQueryID(), session_timezone, or a subquery can still resolve to "out of scope" here while the background mutation task still owes the part, which reopens the same detach/attach data-loss outcome this guard is meant to prevent. Suggested fix: resolve and store the partition ids once when the mutation entry is created/loaded and have both the guard and executor consume those stored ids, or fail closed for runtime-dependent partition expressions instead of re-evaluating them here.
Final Verdict

❌ Changes requested.

LLVM Coverage Report

Measured on commit ca85257.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 120/134 (89.55%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One clickhouse local --queries-file run, no randomness: is_done 0, parts_to_do 1 after the ALTER, 1, 0 after DETACH PART 'all_1_1_0', the part returns as all_3_3_0, final sum(v) = 1045 against an expected 11045. Same for DETACH PARTITION + ALTER DELETE and for a pending RENAME COLUMN.
b Root cause explained? Yes. Mutation versions and part block numbers share one monotone counter, and is_done is recomputed from the active parts only, so DETACH removes the part with no mutation bookkeeping and ATTACH renumbers it above every mutation version, out of reach of selectPartsToMutate and the on-fly conversions. Contradicts docs/reference/statements/alter/index.mdx:63.
c Fix matches root cause? Yes: it refuses the operation that breaks the invariant, at the user's own command, with an actionable message, in the same shape and the same SUPPORT_IS_DISABLED code as the merged patch-part guard a91e82954c2, at three of that guard's four call sites. No widened bound, no no-random-* tag, no dataset reduction. Two pre-existing bugs found on the way are fixed at their own source, and the guard's part domain is held to exactly what the executor rewrites, both false refusals having been measured before fixing.
d Test intent preserved / new tests added? Yes. No existing test is modified. Four new tests; each asserts the armed state (is_done, parts_to_do, part names) before every refusal and carries a refusal control in the same state, so none can pass with the guard removed. Both settings-sensitive tests pin alter_update_mode and apply_mutations_on_fly, which the stress runner injects as client options.
e Both directions demonstrated? Yes, against a pristine-HEAD control server: all six serverError annotations report "query succeeded but error 344 was expected" and the data oracle flips to the full loss signature (active parts 0, sum 0). On the final tree all four tests are 50/50 clean, 200 OK / 0 FAIL, and reverting each piece of the fix in turn reddens only its own block, including each conjunct of the visibility skip separately.
f Fix is general across code paths? Carriers enumerated from the complete modifyPartState inventory (17 rows). Fixed: dropPart(detach=true), dropPartition(detach=true) incl. PARTITION ALL, movePartitionToTable. Left alone with reasons: DROP/TRUNCATE/TTL and replacePartitionFrom's destination (data destroyed, asserted as a control), ATTACH/FETCH PARTITION and MOVE PARTITION TO DISK|VOLUME (data version unchanged or never in scope). Three residuals are disclosed in the description.
g Fix generalizes across inputs? Type wrappers do not apply (a part-lifecycle guard, not a type-dispatched predicate). The axes that do are covered: command kind (UPDATE, DELETE, RENAME COLUMN, MODIFY COLUMN), scope (IN PARTITION vs unscoped), partition shape (id, PARTITION BY p, PARTITION ID 'all', PARTITION ALL), part count, the skippable/non-skippable split of the same MODIFY COLUMN, part kind (regular vs patch) and mutation provenance (non-transactional vs transactional).
h Backward compatible? Yes. No new or changed setting (so no SettingsChangesHistory.cpp entry), no serialization, part-name or mutation-bookkeeping change; only new refusals on three plain-MergeTree commands plus the lock they now take. The message names all three ways out and prints the blocking mutation_id with an exact KILL MUTATION statement, which was run byte for byte as printed.
i Invariants and contracts preserved? The two lock contracts are pinned in the code: the alter lock is taken before stopMergesAndWait() (taken after, a barrier ALTER holding it while waiting for a mutation would deadlock against the blocker that stops that mutation), and the guard is called with no parts lock held (the established order puts currently_processing_in_background_mutex before the parts lock). movePartitionToTable takes only the source table's lock, never both, to avoid an ABBA between two opposite moves. The snapshot mutex is released before the skip predicate runs, because an IN PARTITION subquery re-enters it: measured, it hangs under the mutex and refuses cleanly outside it. A refusal throws before anything is written.

Comment thread src/Storages/StorageMergeTree.cpp Outdated
if (mutations.entries_by_version.empty())
return;

auto context_for_reading = createContextForMutationRead(getContext()->getBackgroundContext());

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.

canSkipMutationCommandForPart still diverges from the real mutation executor for timezone-sensitive IN PARTITION expressions. getPartitionIDFromQuery eventually reaches DateLUT::instance(), which reads CurrentThread's query context rather than the context_for_reading passed here, so during DETACH it sees the detach query's session_timezone, not the background mutation context. A mutation created/executed under one timezone and a later DETACH run under another can therefore treat an owed part as out of scope and allow the same "mutation marked done without rewriting rows" path this PR is trying to close. This needs either a truly executor-equivalent evaluation context on the thread, or a refusal for IN PARTITION expressions whose partition id depends on session_timezone.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Verified the mechanism instead of taking or refusing it on argument, and measured the outcome.

Confirmed: DateLUT::instance() reads session_timezone from CurrentThread::tryGetQueryContext() (src/Common/DateLUT.cpp:166-191), never from the context argument, so this call resolves IN PARTITION under the running session. Measured with no special configuration: stock users config, server timezone UTC, one part in 20200101, mutation scope IN PARTITION tuple(toDate(toDateTime(1577894400))), which is 2020-01-01 under UTC and 2020-01-02 under Asia/Tokyo. One binary, build id asserted on every server.

DETACH session observed
no DETACH, mutation left to run part rewritten, v = 1100, so the part is genuinely owed
default (UTC) refused, Code: 344
session_timezone = 'Asia/Tokyo' allowed, is_done = 1, v = 100 after re-attach

Two corrections to the framing. The mutation's creation timezone plays no part: MergeTreeMutationEntry records commands, block number, tid and csn, no settings, so a creation timezone cannot be honoured later; the pair that matters is the removing session against the background thread. And the path is narrowed rather than left open: without this change the same three arms all lose the update.

I am not closing it here. IN PARTITION is re-resolved from the AST at four sites: StorageMergeTree.cpp:1213 on the submitting session, :2368 and MutateTask.cpp:3653 on background threads, and this guard on the removing session. So "the executor's evaluation" is not a fixed target to match, and the executor is not submitter-equivalent either. #118500 resolves the ids once when the entry is created or loaded, and this guard calls that same predicate, so it inherits resolved ids with no code added here. The gap is named in the PR description. If a reviewer would rather have it folded in, say so and I will push it, the rig above is ready in both directions.

Changelog category stays Bug Fix. I do not self-escalate to Critical Bug Fix without being asked for it.

No test: a test for an open gap would assert the loss. It belongs with the fix.

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.

Yes, I would fold the remaining runtime-dependent IN PARTITION cases into this PR. The current guard still re-evaluates the scope under a different runtime context than the actual mutation task (session_timezone via DateLUT::instance(), currentQueryID() via the task query id, and subqueries by re-running them at detach time), so the acknowledged "mutation marked done without rewriting rows" path is still reachable until the scope is resolved once at mutation creation or these expressions are rejected fail-closed.

@clickhouse-gh clickhouse-gh Bot added the comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). label Sep 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a611e4e

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 6/6) perf-harness dashboard verdict added by #120927 (merged 2026-09-19 10:51Z): the shard now reds on 2 confirmed regression(s) on the performance dashboard, optimize_time_filter_with_preimage #4 (+18.0%) and read_in_reverse_order_final #0 (+15.0%, 2.4 ms to 2.8 ms). Both are micro benchmarks in subsystems this diff cannot reach: it changes only MutateTask and the StorageMergeTree partition-command path. The same verdict wording lands on 20 distinct pull requests within 24 h, and a re-run of an unchanged tree draws the opposite verdict, so the red is a property of the gate rather than of this branch. Shard report: https://s3.amazonaws.com/clickhouse-test-reports/PRs/121032/a611e4eb1fafaabee898b1ded5d461eb848c1d99/pr/performance_comparison_arm_release_master_head_6_6/report.html a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)

The PR and Mergeable Check reds mirror that single shard and clear with it. No other check failed at this head: 155 passed, 18 skipped, 0 running.

Session id: cron:our-pr-ci-monitor:20260919-200112

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Performance Comparison (arm_release, master_head, 6/6) dashboard-verdict row above: #121090. It makes a dashboard confirmed_regression fail a master_head shard only when that shard's own report also calls the same (test, query) slower, so a verdict on a query this diff cannot reach no longer fails the check.

Comment thread src/Storages/StorageMergeTree.cpp Outdated
if (mutations.entries_by_version.empty())
return;

auto context_for_reading = createContextForMutationRead(getContext()->getBackgroundContext());

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.

context_for_reading still is not built the same way as the real mutation executor. MutatePlainMergeTreeTask::createTaskContext calls makeQueryContextForMutate(*storage.getSettings()) before createContextForMutationRead, which force-enables allow_experimental_analyzer; this path clones getBackgroundContext() directly. getPartitionIDFromQuery resolves IN PARTITION through evaluateConstantExpression, so a mutation like ... IN PARTITION tuple(getSetting('allow_experimental_analyzer')) can be seen as out of scope here while the background mutation task still treats the part as owed, reopening the same detach/attach data-loss path this guard is meant to close. Please derive this context through the same makeQueryContextForMutate path, or move that normalization into createContextForMutationRead so the two callers cannot drift again.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reproduced, and fixed in ca85257.

The rig is a server whose default profile carries allow_experimental_analyzer = 0, which is the
reachability e68d2f448de established: a settings profile in the server configuration is applied
without the constraints that refuse a 0, and the default profile reaches the global context before
makeBackgroundContext. One part in partition 1, scope
IN PARTITION tuple(toUInt8(getSetting('allow_experimental_analyzer'))):

before after
DETACH PART allowed Code: 344
mutation is_done = 1, parts_to_do = 0 still owed, rewrites the part to 1100
v after re-attach 100, the update silently lost n/a

A plain IN PARTITION 1 scope is refused by both binaries, so the guard was armed in that rig
either way.

I took the first of the two options. makeQueryContextForMutate has three callers and only some of
them reach createContextForMutationRead, so moving the normalization down would drop it from the
others; routing through it also keeps the two in step on anything it normalizes later, not just this
setting. The comment there states that every context a mutation is analyzed and executed in comes
through it, which this call site was not doing.

The regression arm goes in test_mutation_analyzer_setting, the test that commit added, since the
default profile is the only place the value can still reach a context. It fails against the unfixed
guard and passes with it, and that commit's own arm is unaffected by either binary.

My own re-review then found two more instances of the same axis, both measured. I widened the gap
sentence in the description instead of fixing them here: currentQueryID() in the scope diverges the
same way on a stock server, with no profile needed at all, and a subquery is accepted inside
tuple(...), stored verbatim, and evaluated here under the alter lock with no cancellation callback.
Both are narrower than the status quo, since without this PR the detach is allowed in every one of
those shapes. #118500 resolves the class at the root by resolving the partition ids when the entry is
created, and this predicate then inherits them, so I would rather not add a fail-closed heuristic
here that it would delete.

The refusal resolved a mutation's `IN PARTITION` scope in a context cloned
straight from the background one, while the executor clones the same context and
then calls `makeQueryContextForMutate`. Master normalizes the obsolete
`allow_experimental_analyzer` there (e68d2f4), because a settings profile
written in the server configuration is applied without the constraints that
refuse a `0`, and the default profile reaches the global context before
`makeBackgroundContext`. So on such a server the two disagreed, and a scope that
reads the setting resolved to a partition that does not exist for the guard while
the executor still owed the part: the detach was allowed, the mutation was marked
done with the rows never rewritten, and attaching the part back returned them
unchanged - the loss this refusal exists to prevent.

Measured on a server whose default profile carries the `0`, one part in partition
`1` and scope `IN PARTITION tuple(toUInt8(getSetting('allow_experimental_analyzer')))`:
`DETACH PART` was allowed, the mutation went to `is_done = 1, parts_to_do = 0`,
and `v` was still `100` after the re-attach. It is refused now, and the mutation
then rewrites the part to `1100`. A plain `IN PARTITION 1` scope is refused by
both binaries, so the guard was armed in that rig either way.

Routed through `makeQueryContextForMutate` rather than normalizing the one
setting here: master's comment states that every context a mutation is analyzed
and executed in comes through it, so this keeps the two callers from drifting on
any setting it normalizes later, rather than only on this one.

The regression arm goes to the integration test that commit added, which already
carries the value in the default profile - the only place it can still reach a
context. It fails against the unfixed guard and passes with it, while that
commit's own arm is unaffected by either.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ca85257

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_tsan, 2/6) / test_replicated_database_active_node_taken.py::test_active_node_owned_by_another_server flaky, not this diff: the test races on which server reports REPLICA_ALREADY_EXISTS. 9 distinct heads in the last 5 hours, 8 of them unrelated PRs plus one true-master run. Nothing in this PR touches DatabaseReplicated or DDLWorker a fix task is created (investigating at full effort; fixing-PR link to follow here)

Notes on the rest of this head: 158 checks succeeded and 15 were skipped. Mergeable Check
and PR are the praktika aggregators reflecting the single red above, not separate failures.
The Bugfix validation (integration tests, aarch64 / amd64) rows for
test_mutation_analyzer_setting.py::test_mutation_cannot_be_told_the_analyzer_is_off are the
INTENDED result of that job (the new regression test must fail on a build without the fix) and
both checks are green.

Session id: cron:our-pr-ci-monitor:20260923-163416

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the test_active_node_owned_by_another_server flaky in Integration tests (amd_tsan, 2/6), as promised in the ledger above: #121820. It sequences the two replica claims so the loser is determinate, so the test no longer raises at the CREATE DATABASE.

@Michicosun

Copy link
Copy Markdown
Member

expected behaviour, nothing should be fixed.

@Michicosun Michicosun closed this Sep 29, 2026
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-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

DETACH/ATTACH PART (or PARTITION) silently drops a pending ALTER UPDATE/DELETE and marks the mutation done

3 participants