Skip to content

Do automatic partitions pruning for mutations when it's possible - #99933

Closed
alesapin wants to merge 27 commits into
ClickHouse:masterfrom
alesapin:mutation-partition-pruning
Closed

alesapin wants to merge 27 commits into
ClickHouse:masterfrom
alesapin:mutation-partition-pruning

Conversation

@alesapin

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):

Now ClickHouse do automatic partition pruning for mutation queries based on WHERE part of query. Also now it's possible to specify multiple partitions in IN PARTITION clause. Fixes #98739.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

This PR is made with help of Claude Code.

@clickhouse-gh

clickhouse-gh Bot commented Mar 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a88612f]

Summary: ❌

job_name test_name status info comment
Fast test failure
Build ClickHouse failure
Build (arm_tidy) failure
Build ClickHouse failure cidb
Fast test (arm_darwin) dropped
Build (amd_debug) dropped
Build (amd_asan_ubsan) dropped
Build (amd_tsan) dropped
Build (amd_msan) dropped
Build (amd_binary) dropped
Build (arm_debug) dropped
Build (arm_asan_ubsan) dropped

AI Review

Summary

This PR adds mutation partition pruning from WHERE predicates plus multi-value IN PARTITION syntax for UPDATE/DELETE, including replicated block-number allocation changes. High-level verdict: good direction, but there are correctness/robustness gaps in pruning-analysis failure handling and lock-allocation mechanics that should be fixed before merge.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeData.cpp:7468-7472] getPartitionIdsPrunedByPredicate can throw during TreeRewriter/ExpressionAnalyzer work, but the contract says pruning failure should fall back to nullopt (all partitions). With optimize_mutations_with_partition_pruning = 1 default, this can fail user mutations instead of degrading gracefully.
    • Suggested fix: catch analysis exceptions in this helper, log at LOG_DEBUG/LOG_TRACE, and return std::nullopt.

⚠️ Majors

  • [src/Storages/MergeTree/EphemeralLockInZooKeeper.cpp:253-265] In ZNONODE recovery, makeSetRequest(block_numbers_path, "", -1) runs inside the per-partition loop. For N missing partitions this performs N parent-version bumps and extra Keeper traffic/contention.
    • Suggested fix: create all missing partition znodes first, then bump parent version once.
  • [src/Storages/StorageReplicatedMergeTree.cpp:6638] Version-check retry (block_numbers_stat.version) is always used for explicit IN PARTITION mutations too. This can cause unnecessary retries/starvation from unrelated partition creation.
    • Suggested fix: require expected_block_numbers_version only for predicate-pruned mutations; use std::nullopt for explicit-only partition sets.
  • [tests/queries/0_stateless/04035_mutation_partition_pruning.sql:1, tests/queries/0_stateless/04037_mutation_in_partition_syntax.sql:1] no-parallel tags reduce stateless test parallelism; these tests appear isolated by table names.
    • Suggested fix: remove no-parallel unless there is a demonstrated race/flakiness reason.
Tests
  • ⚠️ Add a regression test where predicate-analysis fails (e.g. non-analyzable expression path) and mutation still succeeds by falling back to all partitions.
ClickHouse Rules
Item Status Notes
Deletion logging ✅
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ⚠️ Pruning-analysis exceptions currently fail mutation instead of graceful fallback when optimization is enabled by default
SettingsChangesHistory.cpp ✅
PR metadata quality ✅
Safe rollout ⚠️ Keeper lock-allocation behavior can add avoidable retry pressure in explicit-partition flows
Compilation time ✅
No large/binary files ✅
Performance & Safety
  • Predicate-analysis exceptions in partition pruning path are currently safety-relevant (unexpected mutation exception instead of optimization fallback).
  • Keeper writes/version churn in per-partition ZNONODE handling and unconditional version checks can increase contention/retry rate.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    1. Make getPartitionIdsPrunedByPredicate exception-safe with fallback to nullopt.
    2. Reduce Keeper version-churn in missing-partition creation path.
    3. Avoid global version-check retries for explicit-only IN PARTITION mutations.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Mar 18, 2026
@CurtizJ CurtizJ self-assigned this Mar 20, 2026
Comment thread src/Core/SettingsChangesHistory.cpp Outdated
addSettingsChanges(settings_changes_history, "26.4",
{

{"optimize_mutations_with_partition_pruning", true, true, "New setting to automatically prune partitions for mutations based on WHERE clause"},

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.

SettingsChangesHistory entry for a newly introduced setting should use the pre-feature value as previous_value to preserve old behavior under compatibility.

Here both previous_value and new_value are true, so compatibility cannot disable the new mutation partition-pruning behavior for older profiles.

Please change this entry to:

{"optimize_mutations_with_partition_pruning", false, true, "New setting to automatically prune partitions for mutations based on WHERE clause"}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think it's a valid review and it should be "optimize_mutations_with_partition_pruning", false, true.

@alexey-milovidov

Copy link
Copy Markdown
Member

The newly added test is shown as flaky.

Comment thread src/Parsers/ParserAlterQuery.cpp Resolved
Comment thread src/Storages/MutationCommands.h Resolved
Comment thread src/Core/SettingsChangesHistory.cpp Outdated
addSettingsChanges(settings_changes_history, "26.4",
{

{"optimize_mutations_with_partition_pruning", true, true, "New setting to automatically prune partitions for mutations based on WHERE clause"},

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think it's a valid review and it should be "optimize_mutations_with_partition_pruning", false, true.

Comment thread src/Core/SettingsChangesHistory.cpp Resolved
block_data,
*zookeeper,
affected,
block_numbers_stat.version);

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.

For explicit IN PARTITION mutations, this always passes block_numbers_stat.version and retries on ZBADVERSION when any unrelated partition is created concurrently.

That version check is required for predicate-pruned mutations, but for explicit partition lists it can cause avoidable retries (and potential starvation under frequent new-partition creation) without improving ordering guarantees for the explicitly targeted partitions.

Please pass expected_block_numbers_version only for pruned mutations, e.g.:

  • use std::optional<int32_t>{block_numbers_stat.version} when has_pruned_commands is true;
  • use std::nullopt for explicit-only mutations.

@alexey-milovidov

Copy link
Copy Markdown
Member

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

@clickhouse-gh

clickhouse-gh Bot commented Apr 9, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.00% +0.00%
Functions 90.90% 90.80% -0.10%
Branches 76.50% 76.50% +0.00%

Changed lines: 86.38% (463/536) | lost baseline coverage: 74 line(s) · Uncovered code

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member

@alesapin, tests for Azure will be fixed here: #102354

alexey-milovidov added a commit that referenced this pull request May 16, 2026
Some authors don't want this kind of automated help on their PRs. Pre-
filter the involves set on `author.login` against a configurable
`SKIP_AUTHORS` array (initially just `alesapin`), applied right after
the backport filter so all three downstream filters (authored, assigned,
taken-over) honour it.

NB: the jq predicate binds `.author.login as $a` first, otherwise the
subsequent `$skip | index(.author.login)` would evaluate `.author.login`
against `$skip` (an array) and fail with "Cannot index array with
string".

Verified live: 426 involves -> 415 after both filters, with the two
alesapin PRs (`#100950 Follow up changes for setting table_readonly`,
`#99933 Do automatic partitions pruning for mutations when it's
possible`) correctly identified for skipping.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

Dear @CurtizJ, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@alexey-milovidov

Copy link
Copy Markdown
Member

Superseded by #110968, which preserves the commits from this branch and brings the feature up to date with the current master (including the MutationCommand refactor), and addresses the outstanding review feedback. The branch here could not be updated because it is in a fork with maintainer edits disabled and it has been CONFLICTING for several months. Thank you @alesapin for the feature — authorship is preserved in the superseding PR.

pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Aug 30, 2026
…-history bucket

The entry was added to the 26.4 bucket when the PR was first written, but the
feature lands in 26.7. Addresses the review thread on `SettingsChangesHistory.cpp`
in ClickHouse#99933.

Co-Authored-By: Claude Fable 5 <[email protected]>
pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Aug 30, 2026
…uning

`getPartitionIdsPrunedByPredicate` analyzed the bare predicate against physical
columns only and propagated any analysis exception. A mutation like
`ALTER TABLE t DELETE WHERE _part = '...'` would fail with `UNKNOWN_IDENTIFIER`
because virtual columns are not physical, and with
`optimize_mutations_with_partition_pruning` enabled by default this would break
previously working queries. Include virtual columns in the analysis and treat
any analysis error as "cannot prune" (mutate all partitions, the historical
behavior), since pruning is only an optimization and the mutation analyzes the
predicate later with more context. Addresses the AI review on
ClickHouse#99933.

Co-Authored-By: Claude Fable 5 <[email protected]>
pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Aug 30, 2026
…ations

For explicit `IN PARTITION` the target partition set is exact and does not
depend on the observed partition list, so a partition appearing concurrently
is out of scope by definition and the `ZBADVERSION` retry loop is not needed.
Addresses the review thread on `StorageReplicatedMergeTree.cpp` in
ClickHouse#99933.

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Some authors don't want this kind of automated help on their PRs. Pre-
filter the involves set on `author.login` against a configurable
`SKIP_AUTHORS` array (initially just `alesapin`), applied right after
the backport filter so all three downstream filters (authored, assigned,
taken-over) honour it.

NB: the jq predicate binds `.author.login as $a` first, otherwise the
subsequent `$skip | index(.author.login)` would evaluate `.author.login`
against `$skip` (an array) and fail with "Cannot index array with
string".

Verified live: 426 involves -> 415 after both filters, with the two
alesapin PRs (`ClickHouse#100950 Follow up changes for setting table_readonly`,
`ClickHouse#99933 Do automatic partitions pruning for mutations when it's
possible`) correctly identified for skipping.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
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

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)))

3 participants