Skip to content

WHATIF projections scan budget - #121766

Merged
yariks5s merged 20 commits into
masterfrom
yarik/whatif-projection-scan-budget
Oct 1, 2026
Merged

yariks5s merged 20 commits into
masterfrom
yarik/whatif-projection-scan-budget

Conversation

@yariks5s

@yariks5s yariks5s commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

Related: #118233

Changelog category (leave one):

  • Improvement

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

EXPLAIN WHATIF no longer reads the whole table to estimate a hypothetical projection: past max_rows_to_scan rows (10 million by default) it estimates from a sample of granules (at least about 30, and one per part) and reports the resulting range in marks_span, and a max_rows_to_read limit now lowers that budget instead of leaving the projection without an estimate.


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

Version info

  • Merged into: 26.10.1.1170-master (included in 26.10 and later)

@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8650448]

Summary: ✅


AI Review

Summary

This PR adds sampling to EXPLAIN WHATIF projection estimation once the scan grows past projection_scan_budget_rows, updates the sequential merge-tree reader so sparse one-mark samples can be read safely, and adds coverage for the new unsupported/error-bound cases. The scan-budget work itself looks solid after the follow-up fixes, but there is still one contract mismatch with the real projection chooser: EXPLAIN WHATIF continues to ignore prefer_optimize_projection, so it can still report not_applicable / not chosen for a query where the optimizer would in fact take the projection.

PR Metadata

Changelog category = Improvement is correct for this change. A Changelog entry is required here and the current one is almost fine, but it still refers to the removed setting name max_rows_to_scan, so it is now inaccurate. Exact replacement text:

EXPLAIN WHATIF no longer reads the whole table to estimate a hypothetical projection: past projection_scan_budget_rows rows (10 million by default) it estimates from a sample of granules (at least about 30, and one per part) and reports the resulting range in marks_span, and a max_rows_to_read limit now lowers that budget instead of leaving the projection without an estimate.

Findings
  • ⚠️ Major [src/Storages/MergeTree/WhatIfProjectionEstimator.cpp:1050] [dismissed by author -- https://github.com/WHATIF projections scan budget #121766#discussion_r4106212046] EXPLAIN WHATIF still ignores prefer_optimize_projection. The real optimizer relaxes both the “must have a filter or useful ORDER BY” gate and the cost-based rejection when prefer_optimize_projection = 1 (src/Processors/QueryPlan/Optimizations/optimizeUseNormalProjection.cpp:448 and src/Processors/QueryPlan/Optimizations/optimizeUseNormalProjection.cpp:653), but evaluateProjection still decides purely from the unrelaxed gates and marks < baseline_marks. That means the verdict can still disagree with the query being explained, and this PR’s updated docs make that user-visible because src/Parsers/ParserExplainQuery.cpp:1263 no longer lists prefer_optimize_projection among the ignored settings.
    Suggested fix: either land the prefer_optimize_projection handling in this PR as well, or keep documenting that setting as ignored until the follow-up ships.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  • Make EXPLAIN WHATIF honor prefer_optimize_projection in the same places as optimizeUseNormalProjections, or explicitly keep documenting it as ignored until that logic lands.
  • Update the PR changelog entry to use projection_scan_budget_rows instead of max_rows_to_scan.

LLVM Coverage Report

Measured on commit 8650448.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 359/374 (95.99%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Sep 23, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-projections Projections: precomputed layouts for accelerating queries (projection parts, maintenance). label Sep 23, 2026
@yariks5s
yariks5s requested a review from nihalzp September 23, 2026 13:29
@nihalzp nihalzp self-assigned this Sep 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 865044880 with master 60cba6ce6 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 484e8f0b4; 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

8 object files changed (+26.96 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/WhatIfProjectionEstimator.cpp.o 270.78 KiB 297.36 KiB +26.59 KiB (+9.82%)

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

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

Median compile-time ratio to the baselines is ×1.05 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +3.7 s (+10%) in total before that adjustment.

Job report

@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.

If I understand correctly, the proposed estimation algorithm after sampling is the following:

After we sample granules across parts within the budget, the sampled rows of each part are treated as a small copy of the part. They are sorted by the projection key and cut into granules whose size is shrunk by the sampling ratio, so that the copy has as many granules as the real part. If the part (100,000 rows) has 10,000 granules and the sample has 1,000 rows, each granule would hold 0.1 rows, but the code rounds the size to whole rows and clamps it to at least one row. So the copy ends up with 1,000 granules instead of desired 10,000, and each of them stands for 10 real granules. The copy's index is then pruned with the query's condition and the surviving granules are counted as the projection's marks, so the count comes out 10 times too low.

CREATE TABLE t (a UInt64, b UInt64, c UInt64) ENGINE = MergeTree ORDER BY a
SETTINGS index_granularity = 100, index_granularity_bytes = 0, min_bytes_for_wide_part = 0;
INSERT INTO t SELECT number, cityHash64(number) % 1000, number FROM numbers(2000000)
SETTINGS max_insert_block_size = 2000000, min_insert_block_size_rows = 2000000;

-- The same data with the projection materialized, to get the real numbers.
CREATE TABLE t_real AS t;
ALTER TABLE t_real ADD PROJECTION p_b (SELECT a, b, c ORDER BY b);
INSERT INTO t_real SELECT * FROM t SETTINGS max_insert_block_size = 2000000, min_insert_block_size_rows = 2000000;

CREATE HYPOTHETICAL PROJECTION p_b ON t (SELECT a, b, c ORDER BY b);

EXPLAIN WHATIF max_rows_to_scan = 0 SELECT sum(c) FROM t WHERE a < 100000 AND b < 100;
-- marks: 2011, verdict: not chosen, sampled_marks: 20000 / 20000
-- Correct, this is the full scan.

EXPLAIN WHATIF max_rows_to_scan = 1000 SELECT sum(c) FROM t WHERE a < 100000 AND b < 100;
-- marks: 307, marks_span: 0 to 736, verdict: chosen, sampled_marks: 30 / 20000
-- Expected: about 2011 with the span containing it, and verdict: not chosen.
-- sample_step = 689, so a scaled granule is 100 / 689 = 0.15 rows and is clamped to 1 row.

EXPLAIN WHATIF max_rows_to_scan = 20000 SELECT sum(c) FROM t WHERE a < 100000 AND b < 100;
-- marks: 1954, marks_span: 0 to 4004, verdict: too close to call, sampled_marks: 200 / 20000
-- Expected: verdict: not chosen. The scaled granule is exactly 1 row here and nothing is rounded,
-- but the rounding term still widens the span by the whole estimate on each side.

-- What the optimizer does on the materialized table:
EXPLAIN indexes = 1 SELECT sum(c) FROM t_real WHERE a < 100000 AND b < 100;
-- ReadFromMergeTree (default.t_real), Granules: 1000/20000. The projection is not chosen.

EXPLAIN indexes = 1 SELECT sum(c) FROM t_real WHERE a < 100000 AND b < 100 SETTINGS prefer_optimize_projection = 1;
-- ReadFromMergeTree (p_b), Granules: 2011/20000. The projection read is 2011 marks.

One way to fix the problem is to scale the sample up instead of shrinking the copy. Continuing the example above, we have a sample of 1,000 rows from a part of 100,000 rows. We sort the sample by the projection key as usual, and since the sample is 1% of the part, each sampled row stands for 100 real rows. The real projection part would have 10,000 granules of 10 rows, so instead of cutting the sample into granules, we build the index of those 10,000 granules directly and take each granule's key from the sample. Granule k starts at real row 10 * k, and that row falls into sampled row k / 10. As a result, granules 0 to 9 all take the key of the first sampled row, granules 10 to 19 take the key of the second, and so on. The index therefore has 10,000 entries, the same number as the real one, in runs of 10 equal keys. Then we continue as usual: we prune this index with the query's condition exactly as the code does today and count the granules that survive.

Comment thread src/Parsers/ParserExplainQuery.cpp Outdated

**Settings**

- `max_rows_to_scan` — how many rows a projection estimate may read before it switches to a sample of granules. Default: `10000000`. `0` means no limit; `max_rows_to_read` can lower it. A sample reads at least about 30 granules and one per part, and when `max_rows_to_read` does not allow that the estimate is `unsupported`.

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 feel max_rows_to_scan is overly broad even though it's only applicable to projection. Unless we plan to expand this setting later to cover other things as well, I would propose using projection_scan_budget_rows or something similar.

Comment thread src/Parsers/ParserExplainQuery.cpp Resolved
@yariks5s
yariks5s added this pull request to the merge queue Oct 1, 2026
Merged via the queue into master with commit 882f419 Oct 1, 2026
294 of 295 checks passed
@yariks5s
yariks5s deleted the yarik/whatif-projection-scan-budget branch October 1, 2026 13:38
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 1, 2026
@clickhouse-gh clickhouse-gh Bot added comp-what-if What-if analysis: hypothetical indexes and projections that exist only in the catalog, and the es... and removed comp-projections Projections: precomputed layouts for accelerating queries (projection parts, maintenance). labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-what-if What-if analysis: hypothetical indexes and projections that exist only in the catalog, and the es... 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.

3 participants