Repository navigation
Keep a pending partition-scoped mutation out of the other partitions - #118500
Conversation
While an `ALTER TABLE ... CLEAR COLUMN c IN PARTITION p` was pending on a plain `MergeTree`, reads of
*every* partition answered the column's default:
CREATE TABLE t (p UInt8, id UInt64, c UInt64 DEFAULT 777) ENGINE = MergeTree PARTITION BY p ORDER BY id;
INSERT INTO t VALUES (1, 1, 10), (2, 2, 20);
SYSTEM STOP MERGES t;
ALTER TABLE t CLEAR COLUMN c IN PARTITION '1' SETTINGS alter_sync = 0;
SELECT p, id, c FROM t ORDER BY id; -- (1, 1, 777), (2, 2, 777); the 20 comes back later
A pending command is applied at read time through the alter conversions of a part, and
`StorageMergeTree::MutationsSnapshot::getOnFlyMutationCommandsForPart` selected the commands for a part
by mutation version alone: the partition the command names was never consulted, so every part whose data
version predates the mutation read the column as defaults, in any partition, and went back to the stored
values once the mutation materialized. The replicated queue keeps its pending mutations keyed by
partition and is not affected.
The snapshot now resolves the partitions of the commands that name one and the per-part selection drops a
command that targets another partition. `MutationCommand::has_partition`, recorded where the command is
built, keeps that resolution to the few commands that have a partition; it is done outside the mutations
mutex, because evaluating a partition expression takes the data parts lock.
Closes: #118050
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Workflow [PR], commit [c8e4774] Summary: ✅
AI ReviewSummaryReviewed PR #118500 at The scope reaches both mutation snapshots, All five added regression tests passed in Fast test. The full workflow remains in progress. No local build or test rerun was performed. Final VerdictStatus: ✅ Approve |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes40 object files changed (+201.12 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units497 translation units recompiled, 3720 s compile time in total, 497 of them have a recent master baseline. |
…tition-scope-118050
One `ALTER` with several commands is a single mutation entry, and the replicated queue keys an entry by the partitions of *all* of its commands: `ALTER TABLE t CLEAR COLUMN c IN PARTITION '1', CLEAR COLUMN d` therefore put the entry in every partition, and their parts were handed the scoped `CLEAR COLUMN c` as well. Two explicitly scoped commands in one entry cross-applied for the same reason. `MutateTask` reads the source part through the very same alter conversions, so the default values the reader substituted for the column were written into the rewritten part: permanent data loss outside the partition the command names, surviving a restart. Compact parts take that path, since Wide parts hardlink the columns a mutation does not touch. The partition resolution and the per-part filtering now live in `MergeTreeData` and `MutationsSnapshotBase`, shared by the plain and the replicated snapshot. Closes: #118939
…tition-scope-118050
… the mutation entry is created or loaded A partition expression is arbitrary user SQL - `getPartitionIDFromQuery` ends in `evaluateConstantExpression`, and the expression may even contain a scalar subquery over the table being read - so resolving it while a storage snapshot is built put that SQL on the read path of every `SELECT` for as long as a scoped mutation was pending, on the global context (outside the submitting query's settings, quotas and limits, and bypassing the shared snapshot cache), with self-recursion available from such a subquery. The partition ids are now resolved exactly once and stored on the command (`MutationCommand::partition_ids`): in `StorageMergeTree::prepareMutationEntry` and `StorageMergeTree::loadMutations` for a plain `MergeTree`, and in `ReplicatedMergeTreeQueue::updateMutations` for a replicated one, which covers both the creation of an entry and reading it back. The per-part selection of the commands to apply on the fly now only looks at the resolved ids and evaluates nothing, so both `getMutationsSnapshot` implementations are back to their original shape - which also removes the lock-order claim a reviewer pointed out, since there is no longer any resolution to move out of the mutations mutex. A scoped command whose partitions could not be resolved (an anomaly: the entry was accepted when it was created) is applied on the fly to no partition at all rather than to the ones it does not name: that only defers its effect until the mutation materializes, while the other direction answers wrong values and can persist them. `IN PARTITION ALL` names no specific partition and is not treated as a scope. Tests: `05115_clear_column_in_partition_scope` now also covers the multi-partition `DELETE ... IN PARTITION '1', '2'` form, which the AST carries separately from the single-partition one (`ASTAlterCommand::partitions`), with a third untouched partition so the filter is proven in both directions. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: This PR fixes how mutations limited to specific partitions (ALTER ... IN PARTITION) are applied. Partition ids are now resolved once, when the mutation entry is created or loaded, and commands are filtered per partition when pending mutations are applied on the fly. None of this runs for plain SELECTs on tables with no pending mutations, which is what clickbench and tpch_adapted_1_official measure. The only flagged query, clickbench Q30 (-10.9%, 221 to 197 ms), has unchanged CPU time and sits just below master's recent range, so it is downgraded to not_sure. No real performance change can be attributed to this PR. clickbenchFlagged queries (1 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
…tition-scope-118050
…or mutation execution too `MutationCommand::partition_ids` was only read by the on-the-fly snapshot filter, while every path that decides what a mutation actually does still re-evaluated the partition expression of the command: - `MutateTask::canSkipMutationCommandForPart` - per part, when the mutation materializes; - `isStorageTouchedByMutations` and `getPartitionAndPredicateExpressionForMutationCommand` in `MutationsInterpreter` - which build the `_partition_id` filter the mutation is executed with, both for the background mutation and for the on-the-fly application of a pending one; - `StorageMergeTree::getPartitionScope`, when a merge decides which pending mutations it materializes. A partition expression is arbitrary user SQL, so re-evaluating it is wrong in two ways. It can name a different partition than the one resolved when the entry was created, which lets the rows the mutation rewrites drift from the rows the pending reads have already been answering from. And it can contain a subquery over the table itself: `getPartitionAndPredicateExpressionForMutationCommand` is reached from `AlterConversions::getMutationActions` on the read path, so `DELETE IN PARTITION tuple((SELECT min(p) FROM t))` re-entered the snapshot unboundedly and a plain `SELECT` with `apply_mutations_on_fly = 1` failed with `TOO_DEEP_RECURSION`. All four now read the ids resolved once by `MergeTreeData::resolvePartitionIdsOfScopedCommands` and fall back to evaluating the expression only for an entry whose ids are `std::nullopt`. The built filter keeps its previous shape: `equals` for a single partition, `in` over an ordered set for several, so it does not depend on the iteration order of a `NameSet`. New test `05229_delete_in_partition_dynamic_expression`: a pending `DELETE IN PARTITION` whose expression is a subquery over the table, with an insert in between that changes what the expression would evaluate to. It reproduced the recursion before this commit. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 The two red jobs on Upgrade check (amd_release) — BuzzHouse (amd_debug) — @groeneai, investigate the |
|
The fix is already in progress and open: #112978 ( Root cause, measured on a master debug build via
#112978 lets the parser accept a reset in any position and resolves it during parsing. RESTORE is covered identically to BACKUP, and |
…tition-scope-118050
…ts stored command The partition ids of a command scoped with `IN PARTITION` were resolved once when the mutation was created, but only `ast_text` is persisted, so `loadMutations` and `ReplicatedMergeTreeQueue::updateMutations` resolved the expression again - a data-dependent expression could name a different partition after a restart, each replica resolved it on its own, and it ran user SQL under `update_mutations_mutex`. `AlterConversions` also rebuilt `UPDATE` commands without `has_partition` / `partition_ids`, so the on-the-fly read path evaluated the expression again. `MergeTreeData::resolvePartitionIdsOfScopedCommands` now replaces each partition expression in `ast_text` with the `ID '...'` it resolved to. It is called when the entry is created (`StorageMergeTree::prepareMutationEntry`, and now `StorageReplicatedMergeTree::mutate` and the mutation part of `StorageReplicatedMergeTree::alter`, before the block numbers are allocated), so the persisted entry names exactly the resolved partitions: reloads, other replicas and the block-number allocation read them back without evaluating anything. Old entries still carry an expression and are resolved on load as before. `AlterConversions` copies the resolved scope onto its rewritten commands, and `getPartitionAndPredicateExpressionForMutationCommand` treats an engaged-but-empty set like the other consumers do. Test `05257_update_in_partition_dynamic_expression_pinned`: a pending scoped `UPDATE` with a self-referencing partition subquery, read on the fly, after `DETACH`/`ATTACH`, and on another `ReplicatedMergeTree` replica. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
🕵 Thanks @groeneai, noted: #112978 fixes the |
|
🕵 Merged The
|
|
Investigated. None of the three comes from this PR. Only
The |
`StorageReplicatedMergeTree::updateLightweight` passed the original commands both to `allocateBlockNumbersInAffectedPartitions` and to `updateLightweightImpl`, so the partition expression of an `UPDATE ... IN PARTITION` was evaluated in each step. Resolve the scoped partitions once on a copy of the commands, as `mutate` and `alter` do, and run every step from it. Within one query a scalar subquery in the partition expression is cached in the query context, so the two evaluations currently agree. This keeps the contract explicit rather than relying on that cache. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged the latest master to resolve the conflict in |
tiandiwonder
left a comment
There was a problem hiding this comment.
The SharedMergeTree on the sync PR still evaluates legacy partition expressions in Mutations::applySharedData and still has the try/catch that was removed elsewhere. Because this runs inside the metadata update, a slow expression stalls it.
…rageMergeTree::mutate` The lock was declared in the `if` initializer, so it was released before `startMutation` resolved the partitions of scoped commands and allocated the mutation version. Declare it in the enclosing block instead. Also tag `05172_clear_column_in_partition_no_data_loss` with `zookeeper`, because it creates a `ReplicatedMergeTree` table. Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov we need to fix the syn pr for shared merge tree. |
…`StorageMergeTree::mutate` Holding the `alter_lock` through the whole `startMutation` also covered the registration of the entry, so a metadata `ALTER` waited for it. That made `05331_mutation_not_skipped_before_registration` time out with `DEADLOCK_AVOIDED`: it pauses an `UPDATE` between allocating the version and registering it, and runs `ALTER ... DROP COLUMN` in that window. The lock is needed only for `prepareMutationEntry`, which resolves the partitions of scoped commands and allocates the version. Split `startMutation` so that it registers an already prepared entry, and release the lock between the two steps. Registration after the version is allocated is the same window that master already handles. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118500&sha=7cb4b2c3ac4303888454ad2fc1f04f46ca14d372&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20sequential%29 PR: #118500 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @tiandiwonder, fixed the sync PR: On this PR, |
|
🕵 |
|
🕵 |
…s not resolve partitions It allocates one global block number and persists no pending mutation entry, so the partition expression is evaluated only once, by `MutationsInterpreter`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=4 K_base=13 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
…artition-mutations `master` got its own resolution of the partition scope of mutation commands (#118500): `MutationCommand::has_partition`, `MutationCommand::partition_ids`, `MergeTreeData::resolvePartitionIdsOfScopedCommands` and `MutationsSnapshotBase::filterCommandsOutsidePartition`. It overlaps with what this branch did with `MutationCommand::resolved_partition_ids` and `rewritePartitionScopeToIds`, so the two are unified instead of being kept side by side: - `MutationCommand::resolved_partition_ids` is removed, `MutationCommand::partition_ids` of `master` is the only per-command scope. `MutationsInterpreter`, `MutateTask` and `AlterConversions` take the `master` side. - `rewritePartitionScopeToIds` now calls `resolvePartitionIdsOfScopedCommands` and only computes the scope of the entry as a whole (the union of the partitions of its commands). Where its result is not used (`StorageReplicatedMergeTree::mutate` and `alter`), `resolvePartitionIdsOfScopedCommands` is called directly, once. - `addSupportedCommands` is back to the signature of `master`: the commands of other partitions are dropped by `filterCommandsOutsidePartition`. A scoped command whose partitions are not resolved is therefore not applied on the fly, as on `master`. - `pinPartitionScopeOfLegacyCommands` fills `MutationCommand::partition_ids`. It already covers the commands in the `IN PARTITION ID` form, so the separate `resolvePartitionIdsOfScopedCommands(..., only_pinned)` calls of `master` in `ReplicatedMergeTreeQueue::updateMutations` and `StorageMergeTree::loadMutations` are dropped (the constructor of `MergeTreeMutationEntry` does it for `StorageMergeTree`). Co-Authored-By: Claude Fable 5.2 <[email protected]>
An
ALTER TABLE ... CLEAR COLUMN c IN PARTITION pwas applied outside the partition it names, both at read time and, once another mutation rewrote a part, in the stored data.While such a command was pending on a plain
MergeTree, reads of every partition answered the column's default:A pending command is applied at read time through the alter conversions of a part, and
StorageMergeTree::MutationsSnapshot::getOnFlyMutationCommandsForPartselected the commands for a part by mutation version alone: the partition the command names was never consulted, so every part whose data version predates the mutation read the column as defaults, in any partition.The same defect on
ReplicatedMergeTreeneeds oneALTERwith several commands, which is a single mutation entry: the queue keys an entry by the partitions of all of its commands, so an unscopedCLEAR COLUMN dsibling puts the entry in every partition and hands the scopedCLEAR COLUMN cto their parts as well. Two explicitly scoped commands in one entry cross-apply for the same reason.Because
MutateTaskreads the source part through those same alter conversions, the wrong values were not only read but written: any mutation that rewrote a Compact part of another partition while the scoped command was pending baked the defaults into the new part, and they stayed lost after a restart. Wide parts hardlink the untouched columns, so the loss hit Compact parts - the format of a typical fresh insert batch.The per-part selection now drops a command that targets another partition. The partitions of a command that names some are resolved once, where the mutation entry is created or loaded -
StorageMergeTree::prepareMutationEntryandStorageMergeTree::loadMutationsfor a plainMergeTree,ReplicatedMergeTreeQueue::updateMutationsfor a replicated one - and stored on the command inMutationCommand::partition_ids. A partition expression is arbitrary user SQL (getPartitionIDFromQueryends inevaluateConstantExpression, and the expression may contain a subquery over the table being read), so it must not be evaluated while a storage snapshot is built; the selection itself only reads the resolved ids. TheALTERpre-validation inMergeTreeData::checkAlterIsPossiblestill evaluates the expression to reject a malformed one early, but its result is discarded: only the id resolved at entry creation decides the scope of the mutation.MutationCommand::has_partition, recorded where the command is parsed, keeps that resolution to the few commands that have a partition, andIN PARTITION ALLis not treated as a scope.A scoped command whose partitions could not be resolved is applied on the fly to no partition at all rather than to the partitions it does not name: that only defers its effect until the mutation materializes, while the other direction answers wrong values and can persist them.
A pending
DELETE IN PARTITION ... WHERE ...applied on the fly had the same defect and is covered by the tests as well.The resolved ids are the source of truth for the execution of the mutation too, not only for the on-the-fly selection:
MutateTask::canSkipMutationCommandForPart,isStorageTouchedByMutationsandgetPartitionAndPredicateExpressionForMutationCommand(which build the_partition_idfilter the mutation runs with), andStorageMergeTree::getPartitionScopeall read them and evaluate the partition expression only for an entry whose ids are unresolved. Otherwise a data-dependent expression could name a different partition at materialization than at registration, so the rows the mutation rewrites would drift from the rows the pending reads had been answering from - and, because that filter is also built on the read path throughAlterConversions::getMutationActions,DELETE IN PARTITION tuple((SELECT min(p) FROM t))re-entered the storage snapshot unboundedly and a plainSELECTwithapply_mutations_on_fly = 1failed withTOO_DEEP_RECURSION.The resolution also pins the scope in the persisted entry: each partition expression of a scoped command is replaced in the stored command text with the
ID '...'it resolved to, when the entry is created (StorageMergeTree::prepareMutationEntry,StorageReplicatedMergeTree::mutate, and the mutation part ofStorageReplicatedMergeTree::alter, before the block numbers are allocated). A reload after a restart, every other replica, and the block-number allocation therefore read back exactly the partitions resolved at creation, and none of them evaluates user SQL (in particular, none of it runs underupdate_mutations_mutex). One visible consequence:system.mutations.commandshowsIN PARTITION ID '1'instead of the original expression.AlterConversionskeeps the resolved scope when it rewrites anUPDATEfor the on-the-fly read path.SharedMergeTreeneeds the same change on the private side.Closes: #118050
Closes: #118939
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Fixed a pending
ALTER TABLE ... CLEAR COLUMN ... IN PARTITIONbeing applied to partitions other than the one it names: such a partition read the column as default values while the mutation was pending, and a mutation that rewrote its parts meanwhile wrote those default values into them permanently. A pendingDELETE IN PARTITIONapplied on the fly ignored its partition scope in the same way. The partition expressions of a scoped mutation are now resolved when the mutation is created, sosystem.mutations.commandshows the resolvedIN PARTITION ID '...'instead of the original expression (e.g.IN PARTITION ID '96ef2e9c877ad3eadd557823e2c23c50'instead ofIN PARTITION ('CN', 202601)).Workflow [PR]
Sync PR [sync-upstream/pr/118500]
Version info
26.12.1.80-master(included in26.12and later)