Skip to content

Do automatic partition pruning for mutations when it's possible - #110968

Merged
alexey-milovidov merged 105 commits into
masterfrom
continue-pr-99933-mutation-partition-pruning
Aug 30, 2026
Merged

alexey-milovidov merged 105 commits into
masterfrom
continue-pr-99933-mutation-partition-pruning

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 19, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

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

ReplicatedMergeTree mutations now automatically prune the affected partitions based on the WHERE part of the query when possible. Also, mutation queries now accept multiple values in the IN PARTITION clause.

Closes: #98739
Related: #99933

This supersedes #99933 by @alesapin, whose commits are preserved in this branch. The original PR became CONFLICTING and could not be updated because maintainer edits are disabled on the fork; the branch had also fallen ~4.5 months behind master (in particular, the MutationCommand refactor to a text-backed lazy AST required reworking how commands carry partition/partitions/predicate).

On top of the original feature, this PR:

  • Merges current master and adapts the code to the MutationCommand refactor (commands are re-parsed from ast_text via command.ast()), the two-argument getInMemoryMetadataPtr and the three-argument ActionsDAGWithInversionPushDown.
  • Moves the optimize_mutations_with_partition_pruning entry to the current settings-history bucket (review thread on SettingsChangesHistory.cpp).
  • Makes the pruning analysis accept every predicate the mutation itself accepts, instead of hiding failures: the analysis follows the same analyzer selection as the mutation execution - the analysis context matches how the commands will actually be interpreted - for an ALTER mutation it is derived from the background context exactly like the background mutation workers derive theirs, so session-only analyzer settings cannot make the submit-time analysis and the asynchronous execution diverge (analyzer-only predicate shapes such as qualified column names work, and a predicate the background execution would reject fails fast at submit time; test 04759_mutation_pruning_background_analyzer_mode), while a lightweight UPDATE, which interprets its commands in the foreground, is analyzed with the submitting context, where the session settings and the current database apply (its predicate is not qualified with the default database, unlike ALTER commands; covered by the existing test 03100_lwu_43_subquery_from_rmt), the column list includes the virtual columns (e.g. _part, _partition_id) and the ALIAS / EPHEMERAL columns, and the re-parsed predicate's set operations (UNION / INTERSECT / EXCEPT) are normalized exactly as the mutation execution path does. There is no fallback: an analysis error propagates and fails the mutation rather than silently mutating every partition (review). Without the above, ALTER TABLE t DELETE WHERE _part = '...' and similar queries would fail since the setting is enabled by default. Covered by the new test 04612_mutation_pruning_exotic_predicates.
  • Requires the block_numbers version check only for predicate-pruned commands (review thread on StorageReplicatedMergeTree.cpp): for explicit IN PARTITION the target set is exact and does not depend on the observed partition list, so the ZBADVERSION retry loop is not needed.
  • In the ZNONODE recovery of EphemeralLocksInPartitions, reports ZBADVERSION to the caller after creating missing partition znodes instead of silently refreshing the version, so a concurrently created partition cannot be missed.
  • StorageMergeTree::mutate validates only explicit IN PARTITION ids instead of running the full pruning analysis and discarding the result (on the non-replicated path, parts of unaffected partitions are skipped per part by canSkipMutationCommandForPart).
  • Documents the multi-partition IN PARTITION syntax and the automatic pruning behavior. The statement pages under docs/reference/statements/ are now generated, so the text lives in the generator's source of truth - the .description and .syntax strings of the ALTER TABLE ... DELETE, ALTER TABLE ... UPDATE, DELETE and UPDATE statement registrations in ParserAlterQuery.cpp, ParserDeleteQuery.cpp and ParserUpdateQuery.cpp.
  • Recomputes the pruned partition set on every ZBADVERSION retry, so a new matching partition created by a concurrent insert on the initiating replica cannot escape the mutation (AI review blocker). Covered by the new failpoint-based test 04613_mutation_pruning_new_partition_race.
  • Widens the pruned set with ZooKeeper-only partitions by comparing against the partition set the pruning analysis itself iterated (returned by the pruner from its own parts snapshot), not against a separately read local partition list: a partition the pruner analyzed and ruled out is not re-added, while a partition it could not have seen is still widened in, so a same-replica insert racing with the analysis can neither escape the mutation nor drag an unaffected partition back into it (AI review). Covered by the failpoint-based tests 04614_mutation_pruning_local_partition_race and 04820_mutation_pruning_analyzed_partition_not_widened.
  • Does not prune predicates containing query-time non-deterministic constants (e.g. now, today) or deferred IN sets (subqueries, tables, table functions): both are evaluated again by the mutation execution - possibly later or on another replica - so the submission-time analysis could narrow block_numbers to a partition set the real execution does not match (AI review blocker). A predicate rewritten to literals on the initiator via mutations_execute_nondeterministic_on_initiator stays prunable. Covered by the new tests 05024_mutation_pruning_nondeterministic_predicate and 04909_mutation_partition_pruning_deferred_sets.
  • Scopes the setting description, the documentation and the changelog entry to the ReplicatedMergeTree family: on plain MergeTree, predicate-based pruning is not wired in, and an explicit IN PARTITION clause should be used (AI review).
  • Rejects the new alter->partitions carrier in StorageSystemWasmModules (exactly like the single-partition form) and preserves it in AlterConversions::createLightweightDeleteCommand, so the multi-partition clause cannot be silently ignored (AI review).

One design note kept as in the original: in the ZNONODE recovery path, missing partition znodes are created one per multi-op (create + parent version bump), matching the established pattern of the insert path in allocateBlockNumber; batching them into a single parent bump was considered but rejected because a partial ZNODEEXISTS would fail the whole multi-op and require a more complex retry.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

alesapin and others added 30 commits March 13, 2026 14:36
Adapt the mutation partition-pruning feature to the refactored
`MutationCommand`, which no longer stores parsed `partition`/`predicate`
members. On master a `MutationCommand` serializes the alter command into
`ast_text` and re-parses it on demand via `MutationCommand::ast`, so all
access to the command's partition/predicate now goes through
`command.ast()->...`. The new multi-partition `IN PARTITION p1, p2, ...`
support is carried in the `ASTAlterCommand::partitions` field, which is
round-tripped through `ast_text` (parser, `clone`, `formatImpl` and
`forEachPointerToChild` all handle it).

Also resolved the `optimize_mutations_with_partition_pruning` setting
declaration (master relocated `use_partition_pruning`) and the updated
`MutationCommand::parse` signature.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Fix compilation against APIs that changed on master while this branch
was open:

- `IStorage::getInMemoryMetadataPtr` now requires `(ContextPtr, bool
  bypass_metadata_cache)`; pass `(query_context, false)` in
  `getPartitionIdsPrunedByPredicate`.
- `ActionsDAGWithInversionPushDown` gained a `bool boolean_context`
  parameter; pass `true` (partition pruning analyzes a `WHERE` predicate
  as a filter, matching the other index-analysis call sites).
- `StorageReplicatedMergeTree.cpp` now dereferences the parsed
  `ASTAlterCommand` returned by `MutationCommand::ast`, so include
  `Parsers/ASTAlterQuery.h` for the complete type.

Verified all touched translation units pass `-fsyntax-only` against the
current master headers.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…utation-partition-pruning

# Conflicts:
#	src/Core/Settings.cpp
#	src/Interpreters/MutationsInterpreter.cpp
#	src/Storages/MergeTree/MergeTreeData.cpp
The previous master merge picked the stale one of the two criss-cross merge
bases and resurrected the `query_plan_read_in_order_through_spilling_join`
settings-history record for a setting that master had already reverted, which
broke every `compatibility` test. Drop the record.

Master turned the mutation statement pages into autogenerated regions, so move
the `IN PARTITION` syntax and the automatic-pruning paragraph into the
generator's source of truth - the `.description` and `.syntax` strings of the
`ALTER TABLE ... DELETE`, `ALTER TABLE ... UPDATE`, `DELETE` and `UPDATE`
statement registrations - and restore the generated `.mdx` bodies.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pass 43 (2026-08-28): merged master and fixed the two reds, pushed 5c75d9ba25ed.

Both failures at dfe159ee0dd4 were caused by this branch, not by master.

1. 33 Fast test failures, all of the compatibility family (02324_compatibility_setting, 03999_stateless_settings_history, 04508_datetime_number_input_raw_value_compatibility, ...), all with Code: 115. DB::Exception: Unknown setting 'query_plan_read_in_order_through_spilling_join': in attempt to set the value of setting 'compatibility'.

Root cause: the pass-42 merge silently resurrected a deleted line. git merge-base --all HEAD origin/master returns two bases — the recent one and adb2c1152851 from 2026-04-14 — and the ort virtual-ancestor merge of a criss-cross history reinstated the query_plan_read_in_order_through_spilling_join record in SettingsChangesHistory.cpp, which master had removed together with the setting itself in 5f8dc5a8a072 (the revert of #111973). A settings-history record without a matching setting makes every SET compatibility = ... throw. The record is now dropped, and the whole 26.9/26.8 diff of SettingsChangesHistory.cpp against master is again exactly this pull request's own single record.

This pass's master merge (11451 commits) was done with an explicit single merge base, git merge-tree --write-tree --merge-base=f0a219f5638f, which is conflict-free; a plain git merge produced ~50 spurious conflicts in files this branch never touched (catboostEvaluate.cpp, the bridge helpers, WasmEdgeRuntime.cpp, ...) for the same criss-cross reason. git diff origin/master HEAD --name-only now lists exactly the 71 files of this pull request.

2. Docs check (Mintlify): Direct edits inside AUTOGENERATED regions detected in alter/delete.mdx, alter/update.mdx, delete.mdx and update.mdx.

master has turned the statement pages into generated output: system.statements joined with system.documentation fills everything between the AUTOGENERATED_START/AUTOGENERATED_END markers, and the source of truth is the .description / .syntax string of the corresponding registerStatement call. The IN PARTITION partition_expr1 [, partition_expr2 ...] syntax line and the automatic-pruning paragraph moved into those C++ strings — for ALTER TABLE ... DELETE and ALTER TABLE ... UPDATE in ParserAlterQuery.cpp, for DELETE in ParserDeleteQuery.cpp and for UPDATE in ParserUpdateQuery.cpp — and the four .mdx bodies are restored to the generated text, so the nightly regeneration produces them. Verified against the freshly built binary: SELECT description FROM system.documentation WHERE type = 'Statement' AND name = 'ALTER TABLE ... DELETE' returns the new text.

Local verification: ninja clickhouse clean, and all 18 tests of this pull request pass against a local server (the four failpoint tests run one per clickhouse-test invocation), plus the three previously failing compatibility tests 02324_compatibility_setting, 03999_stateless_settings_history and 04508_datetime_number_input_raw_value_compatibility.

CH Inc sync (private #65003) was frozen at the pass-42 head. Updated by hand — private master and this public head both merged with an explicit single merge base for the same criss-cross reason, the private-only side kept for the eight files this pull request does not touch, and the same stale query_plan_read_in_order_through_spilling_join record removed there as well. The sync pull request is MERGEABLE again.

There are no unresolved review threads.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is reasonable.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 29, 2026
Merged via the queue into master with commit 596fd32 Aug 30, 2026
175 checks passed
@alexey-milovidov
alexey-milovidov deleted the continue-pr-99933-mutation-partition-pruning branch August 30, 2026 00:54
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 30, 2026
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Nov 7, 2026
…tations

A lightweight UPDATE on a ReplicatedMergeTree allocates block numbers before the
update_sequential_consistency wait. Since ClickHouse#110968 the allocation runs the automatic
partition pruning analysis, which resolved the predicate against
TableNode(storage, context). That constructor takes a data snapshot, and with
enable_shared_storage_snapshot_in_query = 1 the snapshot is cached for the query
together with the parts that were active at that moment. The wait then fetches the
part another replica inserted, but the update's MutationsInterpreter got the cached
snapshot, so the fetched part was never read and its rows never got a patch, on
every replica and for good.

The analysis needs only the table metadata (columns, ALIAS/EPHEMERAL definitions,
subcolumns, virtual columns) and reads the active parts itself, so give its TableNode
a snapshot from getStorageSnapshotWithoutData, which is not cached. The first data
snapshot of the query is then taken by the update after the wait. The same applies
to ALTER TABLE ... UPDATE with alter_update_mode = 'lightweight' and to DELETE with
lightweight_delete_mode = 'lightweight_update', which share this path.

Closes ClickHouse#126876

Co-Authored-By: Claude Opus 5.5 <[email protected]>
qiuyanjun888 pushed a commit to qiuyanjun888/ClickHouse that referenced this pull request Nov 24, 2026
…barrier that is not pruned

The replicated half waited for the pending partition-scoped mutation with
`ALTER ... UPDATE v = v WHERE 0 SETTINGS mutations_sync = 2`. On
ReplicatedMergeTree `optimize_mutations_with_partition_pruning` (ClickHouse#110968)
prunes `WHERE 0` to no partition, so the mutation is created with empty block
numbers and is finalized at once on both replicas: it never waits for the
scoped `UPDATE v = v + 100 IN PARTITION ID '1'`. Whether that one is applied at
the final read then depends only on whether a merge-selecting run has already
assigned its MUTATE_PART. In the failing CI job (Stateless tests
(arm_binary, parallel), PR 131750 @ 1efcd36) every selector run returned
`Limited` (not enough free threads for mutations), part_log had no MutatePart
for either replica, the final SYSTEM SYNC REPLICA found 0 entries, and r2 read
`1 1 10` instead of `1 1 110`.

`WHERE 1` cannot be pruned, so the barrier gets a block number in partition 1
and its completion on r2 needs r2's partition-1 part to reach a version that
includes the scoped mutation. Plain MergeTree (first half) completes mutations
in order, so its `WHERE 0` barrier is correct and stays.

Reproduced deterministically with failpoint
`rmt_merge_selecting_task_no_free_threads` (forces the `Limited` branch):
the original test prints `1 1 10` 3/3, the fixed one matches the reference 3/3.

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

This branch was successfully deployed

1 active deployment
staging - docs — 5c75d9ba Deployed Aug 28, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ALTER TABLE ... UPDATE mutation rewrite more partitions than needed (PARTITION BY toYYYYMMDD(toDate(ym_pv_dateTime)))

4 participants