Skip to content

Keep a pending partition-scoped mutation out of the other partitions - #118500

Merged
alexey-milovidov merged 37 commits into
masterfrom
clear-column-in-partition-scope-118050
Nov 20, 2026
Merged

alexey-milovidov merged 37 commits into
masterfrom
clear-column-in-partition-scope-118050

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 7, 2026 •

Copy link
Copy Markdown
Member

An ALTER TABLE ... CLEAR COLUMN c IN PARTITION p was 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:

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;   -- only to widen the window; it exists on its own under load
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)   <- partition 2's value 20 is replaced by the default
-- and comes back once the mutation materializes

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.

The same defect on ReplicatedMergeTree needs one ALTER with several commands, which is a single mutation entry: the queue keys an entry by the partitions of all of its commands, so an unscoped CLEAR COLUMN d sibling puts the entry in every partition and hands the scoped CLEAR COLUMN c to their parts as well. Two explicitly scoped commands in one entry cross-apply for the same reason.

Because MutateTask reads 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::prepareMutationEntry and StorageMergeTree::loadMutations for a plain MergeTree, ReplicatedMergeTreeQueue::updateMutations for a replicated one - and stored on the command in MutationCommand::partition_ids. A partition expression is arbitrary user SQL (getPartitionIDFromQuery ends in evaluateConstantExpression, 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. The ALTER pre-validation in MergeTreeData::checkAlterIsPossible still 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, and IN PARTITION ALL is 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, isStorageTouchedByMutations and getPartitionAndPredicateExpressionForMutationCommand (which build the _partition_id filter the mutation runs with), and StorageMergeTree::getPartitionScope all 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 through AlterConversions::getMutationActions, DELETE IN PARTITION tuple((SELECT min(p) FROM t)) re-entered the storage snapshot unboundedly and a plain SELECT with apply_mutations_on_fly = 1 failed with TOO_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 of StorageReplicatedMergeTree::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 under update_mutations_mutex). One visible consequence: system.mutations.command shows IN PARTITION ID '1' instead of the original expression. AlterConversions keeps the resolved scope when it rewrites an UPDATE for the on-the-fly read path. SharedMergeTree needs the same change on the private side.

Closes: #118050
Closes: #118939

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 to CHANGELOG.md):

Fixed a pending ALTER TABLE ... CLEAR COLUMN ... IN PARTITION being 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 pending DELETE IN PARTITION applied 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, so system.mutations.command shows the resolved IN PARTITION ID '...' instead of the original expression (e.g. IN PARTITION ID '96ef2e9c877ad3eadd557823e2c23c50' instead of IN PARTITION ('CN', 202601)).


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

Version info

  • Merged into: 26.12.1.80-master (included in 26.12 and later)

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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c8e4774]

Summary: ✅


AI Review

Summary

Reviewed PR #118500 at c8e4774dcaea038fd5f04adbb26dd73f399cea54. The change prevents pending partition-scoped mutations from affecting other partitions and persisting incorrect defaults. Partition scopes are pinned when entries are created and preserved across reloads and replicas. No unresolved actionable findings remain after reviewing the current code and all prior discussion.

The scope reaches both mutation snapshots, MutateTask, MutationsInterpreter, and merge eligibility; AlterConversions preserves it when rewriting commands. Persistence and block-number allocation consume the existing IN PARTITION ID representation. Legacy expressions are excluded from load-time evaluation.

All five added regression tests passed in Fast test. The full workflow remains in progress. No local build or test rerun was performed.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 7, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). label Sep 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c8e4774dc with master 864355afe (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

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

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

Object file sizes

40 object files changed (+201.12 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MutateTask.cpp.o 1.46 MiB 1.49 MiB +28.41 KiB (+1.89%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@tiandiwonder tiandiwonder self-assigned this Sep 9, 2026
Comment thread src/Storages/StorageMergeTree.cpp Resolved
Comment thread src/Storages/StorageMergeTree.cpp Resolved
alexey-milovidov and others added 5 commits September 9, 2026 15:53
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
… 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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 30 not_sure 221 197 -10.9% <0.0001 The PR only changes how IN PARTITION mutation commands are scoped, and this read-only SELECT never runs that code. CPU time is flat (2341 to 2339 ms), so the -10.9% wall-clock gain is not backed by less work.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 947f51dc-8c8f-4807-811d-ad56ed4f6de6
  • MIRAI run: 81b7c939-38d9-420f-a3bf-1cba5b254606
  • PR check IDs:
    • clickbench_1025068_1791798634
    • clickbench_1025074_1791798634
    • clickbench_1025080_1791798634
    • tpch_adapted_1_official_1025091_1791798634
    • tpch_adapted_1_official_1025101_1791798634
    • tpch_adapted_1_official_1025138_1791798634

alexey-milovidov and others added 2 commits September 18, 2026 18:56
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The two red jobs on ed839c18 are both unrelated to this PR, and the branch has just been updated with master (39fd3320) plus the fix for the review finding above (4dd2800c), so CI will re-run.

Upgrade check (amd_release) — Logical error: 'Virtual row has different type for CAST(__table1.json.b, 'String'_String) ...' in setVirtualRow / MergingSortedAlgorithm::initialize. Nothing to do with mutations or partitions. It was a fleet-wide failure: in CIDB it fired on ~35 unrelated PRs a day between 2026-09-11 and 2026-09-14 and then stopped, so the fix is already on master and merging master pulls it in.
report

BuzzHouse (amd_debug) — Logical error: 'Inconsistent AST formatting: the query: RESTORE ALL FROM File(...) SETTINGS ..., iceberg_snapshot_id = DEFAULT cannot parse query back ...'. This is the known open issue #112895 (BACKUP/RESTORE ... SETTINGS <name> = DEFAULT does not round-trip through the formatter), and it has no fix on master yet.
report

@groeneai, investigate the RESTORE ... SETTINGS <name> = DEFAULT failure: #112895 and provide a fix in a separate PR. If the fix is already in progress, link it here.

Comment thread src/Storages/StorageMergeTree.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

The fix is already in progress and open: #112978 (Closes #112895). It is green on head 661d7154 (152 checks successful, 20 skipped, MERGEABLE), but not merged, so the failure still reproduces on any master-based branch.

Root cause, measured on a master debug build via formatQuerySingleLine:

  • RESTORE ALL FROM File('b') SETTINGS iceberg_snapshot_id = DEFAULT, variant_throw_on_type_mismatch = 0 parses, and formats back with the reset moved behind the ordinary change: SETTINGS variant_throw_on_type_mismatch = 0, iceberg_snapshot_id = DEFAULT.
  • Parsing that output is a SYNTAX_ERROR: ParserBackupQuery accepts <name> = DEFAULT only when no other setting precedes it. A clause whose only item is the reset round-trips fine, which is why the fuzzer needs a second setting in the clause to reach this.

#112978 lets the parser accept a reset in any position and resolves it during parsing. RESTORE is covered identically to BACKUP, and tests/queries/0_stateless/04700_backup_settings_default_round_trip.sql asserts both orders, including a core setting reset that follows another item, which is the shape in the report above.

Comment thread src/Storages/MutationCommands.h Resolved
alexey-milovidov and others added 2 commits September 25, 2026 20:58
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai, noted: #112978 fixes the RESTORE ... SETTINGS <name> = DEFAULT BuzzHouse failure. On 4dd2800c the only reds were the Build (arm_tidy) duplicate include in src/Core/tests/gtest_settings.cpp (already fixed on master) and the new_tests_check that follows the dropped builds. The branch now has master merged, plus 322276cd, which addresses the open review findings: the resolved partitions are pinned as ID '...' in the stored command, and AlterConversions keeps the scope for UPDATE. CI is re-running.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch (42db6619caf). All four tests of this PR pass locally on the merged tree, including the ReplicatedMergeTree ones.

The Performance Comparison (arm_release) flags on the previous head (bitmap_cardinality, generate_random_json, read_in_reverse_order_final) are in queries that run no mutations, so this PR doesn't affect them. The jobs were also labelled disk-almost-full and under-utilized CPU. @groeneai, please investigate these perf flags: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118500&sha=322276cdaa75bfe64b10a0a16772e1cb8358f3df&name_0=PR. If they are real on master, please fix them in a separate PR.

CH Inc sync stays red until the private-side twin for SharedMergeTree is added to the sync PR (see the open thread on 05172). That needs the humans who own the sync.

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator

Investigated. None of the three comes from this PR. Only generate_random_json #1 is a real cost on master, and it already has a fixing PR.

  • read_in_reverse_order_final Repair subtree2 #1 (1/6): the two servers held different part sets (SelectedParts 28 on the reference, 39 on the candidate), which is the layout divergence fixed by Pin the part layout of the read_in_reverse_order_final performance test #122335. It merged on 2026-09-26 at 01:20Z, after this run's reference 586199119291 was built, so neither side had it. Since 2026-09-27, 1 of 1,990 arm runs of the query was more than 15% slower. 42db6619caf contains the fix.
  • generate_random_json Repair subtree2 #1 (2/6): the extra candidate time is all self time in SerializationDynamic::serializeBinary (CPU profile 855 -> 1250 samples, other frames flat). It copies a pooled SerializationPtr out of DataTypesCache for every value, so all threads update one shared reference counter, and on arm some server processes of either binary are much slower on it. This cost is on master, and the slow draw got more frequent there: 1 to 4% of arm server processes until 2026-10-01, 7 to 11% since. Fixing PR: Do not share the reference counter of cached serializations between threads #122464 (mine, open). In its own run it made Repair subtree2 #1 a third faster on both arches (arm 1.061 -> 0.709 s, amd 1.208 -> 0.795 s), with the other queries of the test flat.
  • bitmap_cardinality Repair subtree2 #1 (2/6): a per-binary mode. All the time is in CRoaring's roaring_bitmap_and_cardinality (404 -> 526 samples); the candidate took 0.44 s in 7 of 7 runs and the reference 0.334 s. Of the 796 master builds measured at least 3 times since 2026-09-04, 27 take 0.44 s in every run and 737 never do, and the master median stays at 0.334 s. The candidate build of this head drew the slow mode. It is not a regression and there is no fix PR; it belongs to the per-binary class of my open question on Evaluate the text index direct-read fallback once per read block, not once per granule #122350.

The under-utilized CPU and disk-almost-full labels are on all six arm shards of this run, including the four green ones. They are runner-sizing hints (ci/praktika/host_metrics.py), not a sign of a bad measurement.

`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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged the latest master to resolve the conflict in StorageMergeTree::loadMutations: master switched the loop to iterate over a pre-collected names vector, so the PR's resolvePartitionIdsOfScopedCommands call is kept and the log line now uses name instead of it->name(). All translation units touched by the PR compile on the merged tree.

@tiandiwonder tiandiwonder left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment thread src/Storages/StorageMergeTree.cpp Resolved
…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]>
@tiandiwonder

Copy link
Copy Markdown
Contributor

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.

@alexey-milovidov we need to fix the syn pr for shared merge tree.

alexey-milovidov and others added 2 commits November 14, 2026 12:27
…`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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @tiandiwonder, fixed the sync PR: Mutations::applySharedData now calls resolvePartitionIdsOfScopedCommands(entry.commands, storage.getContext(), /* only_pinned = */ true) with no try/catch, the same as ReplicatedMergeTreeQueue::updateMutations. A legacy partition expression is no longer evaluated inside the metadata update; such a command stays unresolved, is not applied on the fly, and its partitions are evaluated when the mutation materializes (commit 536e9dfaa0a on the private sync branch).

On this PR, 908073e474a merges the latest master (no conflicts). Before that, bead37a7ee0 fixes 05331_mutation_not_skipped_before_registration, which failed on every run of the previous head with DEADLOCK_AVOIDED. The alter_lock from 7cb4b2c3ac4 was held through the registration of the mutation too, so a metadata ALTER could not run while an UPDATE sat between allocating its version and registering it, and that window is exactly what the test covers. The lock is now held only through prepareMutationEntry (partition resolution and version allocation). startMutation registers the prepared entry after the lock is released, which is the window master already handles. StorageMergeTree.cpp compiles on the merged tree. A full local build was not practical on this machine right now, so CI will confirm the test.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CH Inc sync failed because the sync branch has a private adaptation commit (SharedMergeTree/Mutations.cpp), so the bot could not fast-forward it to the new public head 908073e474aa. I merged the public head and private master into the sync branch manually. It was a 3-way overlay of the PR files with no conflicts, and the adaptations in Mutations.cpp and StorageSharedMergeTree.cpp are kept. The affected files pass a Cloud-mode syntax check, and the sync PR is now MERGEABLE. All public CI checks are green and there are no open review threads, so this PR needs no code change.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CH Inc sync reported build failed, but the only failing job on the sync PR was the private Style check (Found duplicated setting declaration in src/Storages/StorageSharedSetJoin.cpp -> lock_acquire_timeout). That code is private-only and unrelated to this PR; the sync branch just predated the private-master fix 9eda97fcc62. I merged private master into the sync branch (clean merge, 4abbd153acb), which keeps the SharedMergeTree adaptations. I also merged the latest master into this PR (f094a9c2261, no conflicts); the affected translation units compile.

…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]>
@stresshouse

stresshouse Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

📊 Cloud Performance Report

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

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
  • StressHouse run: 24c8c025-7134-48e0-9509-0245402145d9
  • MIRAI run: 0cd10133-02d8-4ea8-9d9a-03db0ba65597
  • PR check IDs:
    • clickbench_518265_1795198010
    • clickbench_518271_1795198010
    • tpch_adapted_1_official_518277_1795198010
    • tpch_adapted_1_official_518330_1795198010

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 20, 2026
Merged via the queue into master with commit 2701c5f Nov 20, 2026
196 checks passed
@alexey-milovidov
alexey-milovidov deleted the clear-column-in-partition-scope-118050 branch November 20, 2026 17:22
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 20, 2026
alexey-milovidov added a commit that referenced this pull request Nov 21, 2026
…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]>
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-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

4 participants