Skip to content

Simplified partition mutations - #123506

Open
alexey-milovidov wants to merge 152 commits into
masterfrom
continue-pr-48941-partition-mutations
Open

alexey-milovidov wants to merge 152 commits into
masterfrom
continue-pr-48941-partition-mutations

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Oct 2, 2026 •

Copy link
Copy Markdown
Member

IN PARTITION mutations of the MergeTree family now track the set of partitions they affect, so parts of unaffected partitions are left intact (their names and files are not changed). This is especially useful for backups and for remote disks.

This supersedes #48941 by @ilejn (the original commits and authorship are preserved). The branch of the original PR is in the author's fork, and the latest merge of master (which touches .github/workflows) could not be pushed there by the automation, so the work continues here. The review history is in the original PR.

On top of the original PR, this branch merges the latest master (one conflict in AlterConversions.cpp, where master started carrying mutation_version in createLightweightDeleteCommand next to this PR's resolved_partition_ids; both are kept), and fixes the Fast test failure of the last run: getMutationsWithLegacyPartitionScope refreshes /mutations from ZooKeeper without setting a ZooKeeper component, so every partition key type change of a ReplicatedMergeTree table threw a LOGICAL_ERROR exception.

The per-command partition scope is shared with #118500, which landed in master in the meantime: the scope of a command is resolved once into MutationCommand::partition_ids by resolvePartitionIdsOfScopedCommands and pinned into the command text as IN PARTITION ID. On top of that, this PR tracks the scope of a mutation entry as a whole (the union of the partitions of its commands), and pins the scope of legacy entries.

Related: #48941
Related: #118500
Related: #41344
Related: #21326

Changelog category (leave one):

  • Improvement

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

Improved IN PARTITION mutations in the MergeTree family to leave unaffected partitions intact. Especially useful for backups and for remote disks.

🤖 Generated with Claude Code


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

ilejn added 30 commits July 23, 2024 11:54
Comment thread src/Storages/StorageMergeTree.cpp Resolved
`getIncompleteMutationsStatusUnlocked` validated the `current -> intermediate`
and `intermediate -> earlier` wait edges independently, so it reported
`Deadlock detected` when they went through different partitions. A mutation
processes each part independently, so the intermediate mutation can finish its
work in the partitions where the current mutation waits for it without waiting
for the transaction to commit its work in other partitions: there is no cycle.
Now the `intermediate -> earlier` edge is checked only in the partitions where
the current mutation waits for the intermediate one.

The new test reproduces the reported case: a transaction updates partition 1,
a global non-transactional mutation is enqueued with merges stopped, and the
transaction then updates partition 2. It used to fail with
`Deadlock detected`, and now the statement and the commit succeed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageMergeTree.cpp Resolved
… mutations

`markFinishedMutations` and `getUnfinishedMutationCommandsUnlocked` checked each
retained mutation by walking the sorted part versions below the mutation version
until a part of an affected partition was found. After an `IN PARTITION` mutation
finishes, that prefix consists of parts of unrelated partitions, so the pass cost
O(parts x retained mutations) under `currently_processing_in_background_mutex`.

Compute the minimum data version over all parts and per original partition once,
and check each mutation against these aggregates: an unscoped mutation uses the
global minimum, a partition-scoped one the minima of its partitions. Patch parts
are still attributed to the partition of the data they patch, and the transaction
rules in `markFinishedMutations` are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The Stress test (amd_debug) failure (Cannot start clickhouse-server: Unknown expression or function identifier partition_strategy when attaching fuzzed tables) is unrelated to this PR. The open PR #122707 fixes it. Build profile diff failed because of an infrastructure problem (LogClusterNotReady).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123506&sha=f71f6562db41fe3579ad73696dd1749811e7c329&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

05227_mutate_part_ahead_of_table_metadata_version_mergetree still fails with the rewrite dropped the column: 1 / unfinished mutations: 2 after #127925 was merged: CIDB shows 127 failures across 113 PRs between 2026-10-27 13:58 and 2026-10-28 17:10, almost all in Fast test (arm_darwin). It passes 5 of 5 runs locally on this branch merged with the current master.

The Build profile diff failure is an infrastructure error (LogClusterNotReady: the endpoint never became ready), not related to this PR.

@groeneai

Copy link
Copy Markdown
Collaborator

The run you linked was created at 2026-10-28 00:23Z, about 14.5 hours before #127925 was merged (14:53Z). A PR workflow tests the merge commit made when the run was created, and re-run attempts reuse it, so that tree does not contain the fix.

Fast test (arm_darwin) runs of this test since the merge:

  • 12 failures (15:04Z to 17:10Z, the end of your window): all from workflows created before 14:53Z.
  • 26 passes, also from workflows created before 14:53Z.
  • 16 runs from workflows created after 14:53Z: all passed.

Plain Fast test has 80 passes and no failures since the merge. So #127925 (merged) is the fix, and I have nothing else in progress for this test. The new run on this PR (head 5791860, created 19:00Z) is the first one here whose tree contains it.

Comment thread src/Storages/StorageMergeTree.cpp Resolved
… and `getMutationsStatus`

After a partition-scoped mutation finishes, parts of other partitions keep
data versions below it, so finding the first affecting mutation for each part
scanned all retained scoped entries, and each scoped entry in the status
scanned the parts of all partitions. Build per-partition lookups once per pass
instead: global mutation versions separately from the scoped ones grouped by
partition, and the positions of the parts of each partition.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai, that settles it: the run I linked was created before #127925 was merged, so its tree did not contain the fix. Nothing more is needed for 05227_mutate_part_ahead_of_table_metadata_version_mergetree.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The CH Inc sync build failure (projectionsCommon.cpp:102: no viable conversion from 'bool' to 'std::expected<void, std::string>') was not caused by this PR: the sync branch merged a private master whose masking-policy check in canUseProjectionForReadingStep still did return false. Private master has since fixed it (it now returns std::unexpected). I merged the latest master into this branch (clean merge, clickhouse builds, the partition mutation tests pass locally), so the sync is regenerated against the fixed private master. The two open review threads are still waiting for a maintainer's design decision (see the replies there).

…e legacy mutations are pending

`changesTypeOfPartitionKeyColumns` treated every unequal type as a change that can make
an `IN PARTITION <value>` literal of a legacy mutation entry undecodable, so adding a
member to a partition key `Enum` was refused with `ALTER_OF_COLUMN_IS_FORBIDDEN` while
such an entry was pending. Adding members keeps the width, the existing name to value
mapping, and therefore both the decoding of the literals and the partition ids. Count
only changes which do not preserve all of that (a renamed member still counts), in
both `checkAlterEligibility` and the repeated check in `StorageReplicatedMergeTree::alter`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageMergeTree.cpp Resolved
alexey-milovidov and others added 8 commits November 2, 2026 11:50
…LTER`

Partition-scoped (`IN PARTITION`) mutations can finish out of order, so the
completion of the newest mutation no longer implies that the earlier ones are
done. `StorageMergeTree::alter` implemented the `RENAME COLUMN` barrier by
waiting only for `current_mutations_by_version.rbegin()`: a newer mutation of
an empty partition let the rename publish its metadata while an older mutation
was still pending in another partition, and the values of the renamed column
were lost when that mutation ran.

Wait for every unfinished mutation instead, and add a regression test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Storages/MergeTree/MergeTreeMutationEntry.cpp
#	src/Storages/MergeTree/MergeTreeMutationEntry.h
… in `selectPartsToMutate`

Master added a check of `isDropOrRename` that dereferences `single_mutation_commands`,
which this PR changed from a pointer to a `MutationCommands` value.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Storages/MergeTree/MergeTreeData.h
#	src/Storages/MergeTree/MergeTreeMutationEntry.h
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged the latest master. This time the merge was not mechanical: master got its own resolution of the partition scope of mutation commands in #118500 (MutationCommand::has_partition, MutationCommand::partition_ids, resolvePartitionIdsOfScopedCommands, filterCommandsOutsidePartition), which overlaps with this PR's MutationCommand::resolved_partition_ids and rewritePartitionScopeToIds (8 conflicted files). I unified the two instead of keeping them side by side:

  • MutationCommand::resolved_partition_ids is removed; MutationCommand::partition_ids from master is the only per-command scope. MutationsInterpreter.cpp, MutationsInterpreter.h and MutateTask.cpp are now identical to master.
  • rewritePartitionScopeToIds calls resolvePartitionIdsOfScopedCommands and only computes the scope of the entry as a whole (the union of the partitions of its commands).
  • addSupportedCommands is back to the signature of master; the commands of other partitions are dropped by filterCommandsOutsidePartition. One behaviour follows master here: a scoped command whose partitions could not be resolved (a legacy entry that cannot be decoded) is not applied on the fly at all, where this PR used to apply it to every partition.
  • pinPartitionScopeOfLegacyCommands fills MutationCommand::partition_ids, and it replaces the only_pinned calls of master at load time, because it already covers the IN PARTITION ID form.

The clickhouse binary builds locally. Against a local server with an embedded Keeper I ran 65 stateless tests selected by partition_mutation, in_partition, clear_column and the tests added by #118500: 63 passed, including all tests of this PR and all of that one. The 2 failures (05153_clear_column_stale_materialized_warning, 02675_sparse_columns_clear_column) are because my local server has no system.text_log. Integration tests were not run locally.

The arm_tidy builds of the previous run failed on modernize-use-nodiscard for MergeTreeMutationEntry::affectsPartition; it is now [[nodiscard]].

CH Inc sync will need another adaptation: the private sync branch was adapted to resolved_partition_ids, which no longer exists.

The review thread about mutation_pointer as a contiguous-prefix fence in ReplicatedMergeTreeQueue::tryFinalizeMutations is still open and still needs a maintainer decision; nothing changed there.

if (const auto * old_low_cardinality = typeid_cast<const DataTypeLowCardinality *>(&old_type))
{
const auto * new_low_cardinality = typeid_cast<const DataTypeLowCardinality *>(&new_type);
return new_low_cardinality

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.

[Major] Preserve safe LowCardinality wrapper changes while legacy mutations are pending

This requires both types to have the wrapper, so LowCardinality(String) -> String returns false; the reverse conversion falls through to false as well. Both changes are explicitly allowed by isSafeForKeyConversion, and convertFieldToType unwraps LowCardinality, so the existing partition literals and partition IDs remain valid.

For example, take the legacy multi-partition fixture from 05220, use p LowCardinality(String) with pending IN PARTITION 'a', 'b' commands, and issue ALTER TABLE t MODIFY COLUMN p String. The new guard rejects this previously supported conversion with ALTER_OF_COLUMN_IS_FORBIDDEN, requiring an otherwise valid mutation to finish or be killed first.

Please compare the effective partition value types when adding/removing LowCardinality, while retaining the enum name/value checks, and cover both wrapper directions in the legacy-scope regression test.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants