Skip to content

Introduce Partition Constants Substitution During Index Analysis - #104582

Merged
Michicosun merged 49 commits into
masterfrom
skip_indices_part_constants_folding
Jul 7, 2026
Merged

Michicosun merged 49 commits into
masterfrom
skip_indices_part_constants_folding

Conversation

@Michicosun

@Michicosun Michicosun commented May 11, 2026 •

Copy link
Copy Markdown
Member

This PR introduces partition-level constant substitution during index analysis.

When a filter references the partition key together with primary-key or skip-index columns, the partition value is folded into the predicate separately for each part. This lets MergeTree primary-key, MinMax, and skip-index analysis prune more parts and granules without weakening the filter (the original, unsubstituted filter is still applied during execution).

The behavior is controlled by the new setting use_constant_folding_in_index_analysis, which is disabled by default.

Changelog category (leave one):

  • Performance Improvement

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

Added the use_constant_folding_in_index_analysis setting (disabled by default). When enabled, MergeTree primary-key, MinMax, and skip-index analysis fold partition-level constants into the filter predicate separately for each part, improving pruning for filters whose branches depend on partition values, e.g. (a = 1 AND b >= 1) OR (a = 2 AND b > 10) with PARTITION BY a.

Version info

  • Merged into: 26.7.1.598 (included in 26.7 and later)

@clickhouse-gh

clickhouse-gh Bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d8e4c29]

Summary: ❌

job_name test_name status info comment
Stress test (amd_debug) FAIL
Logical error: 'Inconsistent AST formatting: the original AST: (STID: 1941-26fa) FAIL cidb, issue
AST fuzzer (amd_debug) FAIL
Logical error: Block structure mismatch in A stream: different columns: (STID: 0993-27f0) FAIL cidb, issue

AI Review

Summary

This PR adds ConditionTemplate-based per-part partition constant substitution so MergeTree PK, MinMax, and skip-index analysis can specialize predicates by partition. The main mechanism looks sound, but several user-visible contracts still consult the unsubstituted predicate, so enabling the setting can still throw false INDEX_NOT_USED exceptions, under-read SAMPLE n, or silently downgrade real failures into weaker pruning.

Findings
  • ❌ [src/Storages/MergeTree/ConditionTemplate.cpp:202-214], [src/Interpreters/ActionsDAG.cpp:124-140, 827-832] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/104582#discussion_r3415288655] The best-effort folding path still swallows every DB::Exception raised while evaluating newly-constant subexpressions, then falls back to generateUnsubstituted. That means resource / cancellation / internal failures during per-part specialization are converted into weaker pruning instead of propagating. Suggested fix: restrict the fallback to expected semantic evaluation errors, or explicitly rethrow fatal/resource/cancellation error codes before returning the unsubstituted condition.
  • ⚠️ [src/Processors/QueryPlan/ReadFromMergeTree.cpp:2722-2728], [src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp:700-706] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/104582#discussion_r3224199704, https://github.com/ClickHouse/ClickHouse/pull/104582#discussion_r3218807246] force_primary_key and force_index_by_date are still decided from generateUnsubstituted() before the per-part specialized condition is used. With use_constant_folding_in_index_analysis = 1, queries like the new 04417_partition_constants_folding_force_settings.sql can prune by PK / MinMax later in analysis and still throw INDEX_NOT_USED up front. Suggested fix: base the force_* checks on the partition-specialized condition or on the actual pruning counters after part filtering.
  • ⚠️ [src/Processors/QueryPlan/ReadFromMergeTree.cpp:2320-2322] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/104582#discussion_r3249339017] Skip-index usefulness is still filtered by condition_template->generateUnsubstituted()->alwaysUnknownOrTrue(), so branch-per-partition predicates can discard an index before specialization ever runs. That leaves real per-part skip-index pruning on the table and can also trigger false INDEX_NOT_USED from force_data_skipping_indices. Suggested fix: keep the template when partition constant folding is enabled and decide usefulness after per-part specialization (or after observing actual per-part pruning).
  • ⚠️ [src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp:303-307] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/104582#discussion_r3325547241] Absolute SAMPLE n still estimates approx_total_rows from key_condition->generateUnsubstituted(), while the real PK scan below uses generateForPartition(partition). When specialization removes whole OR branches per partition, the estimate is too large and the converted relative sample becomes too small, so the query can read substantially fewer rows than requested. Suggested fix: estimate from the same partition-specialized KeyCondition that the PK scan will use.
Final Verdict

Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label May 11, 2026
@nihalzp nihalzp self-assigned this May 11, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

alexey-milovidov and others added 3 commits July 3, 2026 01:35
…t folding

Address review feedback:

- `04417_partition_constants_folding_force_settings` documents that
  `force_primary_key` / `force_index_by_date` still throw `INDEX_NOT_USED`
  when pruning becomes effective only after per-part constant folding,
  because the force checks are evaluated against the unsubstituted
  condition. This locks in the current (data-dependent) behavior.

- `04418_partition_constants_folding_minmax_count_projection` covers the
  implicit MinMax-count projection path in
  `MergeTreeData::getMinMaxCountProjectionBlock`, where the partition
  predicate is folded per part before checking the part's MinMax
  hyperrectangle.

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

# Conflicts:
#	src/Storages/MergeTree/MergeTreeReaderTextIndex.cpp
…ory bucket

The setting was recorded under the 26.6 bucket, but 26.6 has been
released (baseline for `02995_new_settings_history` is v26.6.1) and the
current development version is 26.7. The test requires new settings that
are absent from the released baseline to be registered under a version
greater than 26.6, so move the entry to the 26.7 bucket.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged the latest master (resolved one conflict in MergeTreeReaderTextIndex.cpp: kept master's reworded comment together with this PR's condition_template->generateUnsubstituted() code) and addressed the outstanding review feedback from @nihalzp:

  • ConditionTemplate::generateForPartition: narrowed the best-effort fallback from catch (...) to catch (const Exception &), so only expected query-evaluation failures (e.g. division by zero while folding a partition constant) fall back to the unsubstituted condition.
  • Setting documentation: restored a concrete example — a disjunctive filter whose branches target different partitions ((a = 1 AND b >= 1) OR (a = 2 AND b > 10) with PARTITION BY a).
  • Tests:
    • 04417_partition_constants_folding_force_settings documents that force_primary_key / force_index_by_date still throw INDEX_NOT_USED when pruning becomes effective only after per-part constant folding (the force_* checks run against the unsubstituted condition). This locks in the current, data-dependent behavior.
    • 04418_partition_constants_folding_minmax_count_projection covers the implicit MinMax-count projection path in MergeTreeData::getMinMaxCountProjectionBlock.
  • Settings history: moved the use_constant_folding_in_index_analysis entry from the 26.6 bucket to 26.7 (26.6 is released; the 02995_new_settings_history baseline is v26.6.1), otherwise the settings-history test would fail.

The changelog category is already Performance Improvement and the entry mentions the setting. The force_*-vs-unsubstituted findings raised by the AI reviewer are the previously-noted design decision and are now documented by 04417 rather than changed.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements and removed pr-not-for-changelog This PR should not be mentioned in the changelog labels Jul 3, 2026
The recent master merge brought in `explain_query_plan_default = 'pretty'`
(the new default since 26.7, introduced in #105036), which changes the
default `EXPLAIN PLAN` output format. The five constant-folding tests that
assert on `EXPLAIN indexes = 1` output started failing in Fast test with
"result differs with reference":
`04218_partition_pk_pruning_constants_folding`,
`04219_partition_minmax_skip_index_constants_folding`,
`04220_partition_id_constants_folding`,
`04221_partition_id_with_minmax_constants_folding`,
`04314_partition_constants_folding_derived_key`.

Add `SET explain_query_plan_default = 'legacy';` to each of them so their
existing (already reviewed) references stay valid. This mirrors how #105036
handled the ~414 existing `EXPLAIN` tests when it changed the default, and
keeps the references demonstrating per-part constant folding unchanged.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104582&sha=ebf528aa38a90f8bc69735ead2da02540b2d479b&name_0=PR&name_1=Fast%20test

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Fixed the Fast test failures in ec167eec424. After the latest master merge, explain_query_plan_default now defaults to pretty (new default since 26.7, from #105036), which changed the default EXPLAIN PLAN output format. The five constant-folding tests that assert on EXPLAIN indexes = 1 output (04218, 04219, 04220, 04221, 04314) were written against the legacy format and started failing with "result differs with reference".

I added SET explain_query_plan_default = 'legacy'; to each of them so their existing (already reviewed) references — which demonstrate the per-part constant folding — stay valid. This mirrors how #105036 pinned the ~414 existing EXPLAIN tests when it changed the default. No reference files were touched.

@nihalzp nihalzp left a comment

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.

Image

It looks related. It would be good to investigate why this performance test slowed down even though we have the setting is by default false.

@ClickHouse ClickHouse deleted a comment from UnamedRus Jul 5, 2026
@ClickHouse ClickHouse deleted a comment from UnamedRus Jul 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.60% 85.60% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.80% 77.80% +0.00%

Changed lines: Changed C/C++ lines covered: 476/486 (97.94%) · Uncovered code

Full report · Diff report

@Michicosun
Michicosun added this pull request to the merge queue Jul 7, 2026
Merged via the queue into master with commit a13971d Jul 7, 2026
172 of 175 checks passed
@Michicosun
Michicosun deleted the skip_indices_part_constants_folding branch July 7, 2026 13:35
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 7, 2026

DROP TABLE IF EXISTS t_derived_key;
CREATE TABLE t_derived_key (d Date, b UInt64)
ENGINE = MergeTree ORDER BY b PARTITION BY toYYYYMM(d) SETTINGS index_granularity = 1;

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.

@Michicosun Is this going to work with a multiple column partitioned table? Maybe add another test for this case

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 should work for any partitioning scheme.

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…t_constants_folding

Introduce Partition Constants Substitution During Index Analysis
@rschu1ze

Copy link
Copy Markdown
Member

Can we enable the setting by default now?

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

Labels

pr-performance Pull request with some performance 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.

7 participants