Repository navigation
Do automatic partition pruning for mutations when it's possible - #110968
Conversation
This reverts commit 54b63e1.
…kHouse into mutation-partition-pruning
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.
|
🕵 Pass 43 (2026-08-28): merged Both failures at 1. 33 Root cause: the pass-42 merge silently resurrected a deleted line. This pass's 2.
Local verification:
There are no unresolved review threads. |
alexey-milovidov
left a comment
There was a problem hiding this comment.
This is reasonable.
…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]>
…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]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
ReplicatedMergeTreemutations now automatically prune the affected partitions based on theWHEREpart of the query when possible. Also, mutation queries now accept multiple values in theIN PARTITIONclause.Closes: #98739
Related: #99933
This supersedes #99933 by @alesapin, whose commits are preserved in this branch. The original PR became
CONFLICTINGand could not be updated because maintainer edits are disabled on the fork; the branch had also fallen ~4.5 months behindmaster(in particular, theMutationCommandrefactor to a text-backed lazy AST required reworking how commands carrypartition/partitions/predicate).On top of the original feature, this PR:
masterand adapts the code to theMutationCommandrefactor (commands are re-parsed fromast_textviacommand.ast()), the two-argumentgetInMemoryMetadataPtrand the three-argumentActionsDAGWithInversionPushDown.optimize_mutations_with_partition_pruningentry to the current settings-history bucket (review thread onSettingsChangesHistory.cpp).ALTERmutation 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; test04759_mutation_pruning_background_analyzer_mode), while a lightweightUPDATE, 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, unlikeALTERcommands; covered by the existing test03100_lwu_43_subquery_from_rmt), the column list includes the virtual columns (e.g._part,_partition_id) and theALIAS/EPHEMERALcolumns, 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 test04612_mutation_pruning_exotic_predicates.block_numbersversion check only for predicate-pruned commands (review thread onStorageReplicatedMergeTree.cpp): for explicitIN PARTITIONthe target set is exact and does not depend on the observed partition list, so theZBADVERSIONretry loop is not needed.ZNONODErecovery ofEphemeralLocksInPartitions, reportsZBADVERSIONto the caller after creating missing partition znodes instead of silently refreshing the version, so a concurrently created partition cannot be missed.StorageMergeTree::mutatevalidates only explicitIN PARTITIONids instead of running the full pruning analysis and discarding the result (on the non-replicated path, parts of unaffected partitions are skipped per part bycanSkipMutationCommandForPart).IN PARTITIONsyntax and the automatic pruning behavior. The statement pages underdocs/reference/statements/are now generated, so the text lives in the generator's source of truth - the.descriptionand.syntaxstrings of theALTER TABLE ... DELETE,ALTER TABLE ... UPDATE,DELETEandUPDATEstatement registrations inParserAlterQuery.cpp,ParserDeleteQuery.cppandParserUpdateQuery.cpp.ZBADVERSIONretry, 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 test04613_mutation_pruning_new_partition_race.04614_mutation_pruning_local_partition_raceand04820_mutation_pruning_analyzed_partition_not_widened.now,today) or deferredINsets (subqueries, tables, table functions): both are evaluated again by the mutation execution - possibly later or on another replica - so the submission-time analysis could narrowblock_numbersto a partition set the real execution does not match (AI review blocker). A predicate rewritten to literals on the initiator viamutations_execute_nondeterministic_on_initiatorstays prunable. Covered by the new tests05024_mutation_pruning_nondeterministic_predicateand04909_mutation_partition_pruning_deferred_sets.ReplicatedMergeTreefamily: on plainMergeTree, predicate-based pruning is not wired in, and an explicitIN PARTITIONclause should be used (AI review).alter->partitionscarrier inStorageSystemWasmModules(exactly like the single-partition form) and preserves it inAlterConversions::createLightweightDeleteCommand, so the multi-partition clause cannot be silently ignored (AI review).One design note kept as in the original: in the
ZNONODErecovery path, missing partition znodes are created one per multi-op (create + parent version bump), matching the established pattern of the insert path inallocateBlockNumber; batching them into a single parent bump was considered but rejected because a partialZNODEEXISTSwould fail the whole multi-op and require a more complex retry.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/110968]