Repository navigation
Conversation
…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.
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 bounce cap reached: published as-is; residual findings listed below. Nothing unresolved is a
Session id: cron:clickhouse-review-slot-48:20260919-140100 |
|
Workflow [PR], commit [ca85257] Summary: ❌
AI ReviewSummaryThis PR adds the missing plain- Findings❌ Blockers
Final Verdict❌ Changes requested. LLVM Coverage ReportMeasured on commit ca85257.
Changed lines: Changed C/C++ lines covered: 120/134 (89.55%) · Uncovered code |
Pre-PR validation gate (click to expand)
|
| if (mutations.entries_by_version.empty()) | ||
| return; | ||
|
|
||
| auto context_for_reading = createContextForMutationRead(getContext()->getBackgroundContext()); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Commit See the job log for details. |
CI finish ledger - a611e4eEvery 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
The Session id: cron:our-pr-ci-monitor:20260919-200112 |
|
Fixing PR for the |
| if (mutations.entries_by_version.empty()) | ||
| return; | ||
|
|
||
| auto context_for_reading = createContextForMutationRead(getContext()->getBackgroundContext()); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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]>
CI finish ledger - ca85257Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Notes on the rest of this head: 158 checks succeeded and 15 were skipped. Session id: cron:our-pr-ci-monitor:20260923-163416 |
|
Fixing PR for the |
|
expected behaviour, nothing should be fixed. |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
On plain
MergeTree,ALTER TABLE ... DETACH PART,DETACH PARTITIONandMOVE PARTITION TO TABLEare now refused while an unfinishedUPDATE,DELETEor metadata mutation is still pending for one of the affected parts. Previously such a removal marked the mutationis_done = 1without touching the rows, and re-attaching the part brought them back unmutated, so an acknowledgedALTER TABLE ... UPDATE/DELETEwas permanently and silently not applied.DROP PART,DROP PARTITIONandTRUNCATEare 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
DROPand TTL; wrong forDETACHandMOVE PARTITION: the data returns renumbered above every mutationversion, all that mutation assignment and on-fly conversions key on.
alter/index.mdx:63guarantees 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 onlyparts visible at its snapshot. A mutation whose
WHEREmatches 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 PARTITIONvalue that resolves differently perreader, since the scope is re-evaluated, not resolved once: a partition id from
session_timezoneorcurrentQueryID(), or a subquery evaluated under the alter lock.Two pre-existing bugs too.
mutatedeclared itsAlterLockHolderin anifinit-statement, so it diedbefore
startMutation, serialising nothing. And the patch guard ran only whilesupportsLightweightUpdate()held, whichMODIFY SETTING enable_block_number_column = 0turns falsewhile the patch still applies on read:
sum(v)went 110 to 10. It now keys on patch parts.ReplicatedMergeTreeloses it the same way (ReplicatedMergeTreeQueue.cpp:453drops the part fromparts_to_do,:2573completes 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]