Skip to content

Don't build a set to estimate its selectivity - #114389

Merged
nickitat merged 9 commits into
masterfrom
statistics-bound-in-set-estimation
Aug 21, 2026
Merged

nickitat merged 9 commits into
masterfrom
statistics-bound-in-set-estimation

Conversation

@nickitat

@nickitat nickitat commented Aug 11, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Bounded the cost of estimating the selectivity of col IN (...) from column statistics, which could add hundreds of milliseconds to the planning of a single query. The estimator no longer runs the subquery behind col IN (subquery) to fill a set it only needs one selectivity number from — an unbuilt set is skipped instead. For a set larger than the new statistics_max_set_size_for_exact_selectivity_estimation setting (default 10000), the selectivity is now derived from the size of the set and its bounding range.


Some measurements on sf=100 could be found here.


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

Version info

  • Backported to: 26.7.6.16, 26.6.4.25

`ConditionSelectivityEstimator` is advisory: its only job is to rank PREWHERE
candidates. It reached that answer by calling `buildOrderedSetInplace`, which
runs the subquery behind `col IN (subquery)` if nobody has built it yet. A cost
model that executes a subquery gives query planning a side effect of unbounded
cost, for a result the plan may end up not needing at all.

Add `FutureSet::getOrderedSetIfAlreadyBuilt`, which gives up instead of filling
the set, and use it from the estimator. Only `FutureSetFromSubquery` can be
unbuilt at that point, and its `buildOrderedSetInplace` returns immediately once
`get` is non-null, so the new method provably executes nothing.

This removes a side effect rather than work. The set is still built during
execution, so no data is read twice either way - what disappears is the
estimation that followed the build, the `Field` per element, the sort and the
per-element statistics probes, and only when nothing else has built the set
already.

It therefore pays off exactly when the `IN` column is not indexed. On such a
table, a query with two 300k-element `IN (subquery)` conditions goes from 609ms
to 152ms, which is what it costs with `use_statistics = 0`. When the column is
indexed, primary key analysis has already built the set by then, this commit
changes nothing, and the estimation is bounded by the next one instead.
For `col IN (set)` the selectivity estimator copies every element into a `Field`,
turns each into a point `Range`, sorts them, and then probes the column
statistics once per element. For a 300k-element set that is hundreds of
milliseconds of query planning to produce a single number used only to rank
PREWHERE candidates. `KeyCondition` bounds the equivalent conversion with
`use_index_for_in_with_subqueries_max_values`; the estimator had no such bound.

Above `statistics_max_set_size_for_exact_selectivity_estimation` (default
100000), derive the selectivity from two upper bounds instead, both measured and
neither depending on the number of elements:

- no row outside the set's bounding range can be in the set, which is one
  `getExtremes` pass plus one statistics probe;
- no more distinct values can match than the set holds, which is the set size
  over the column cardinality. Taken only when the cardinality is measured -
  without a uniq sketch `estimateCardinality` returns a fixed fraction of the row
  count, and dividing by that guess would make the condition look arbitrarily
  selective. `ColumnStatistics::hasCardinality` is added to tell the two apart.

Such an atom is finalized rather than turned into ranges, so it multiplies with
other predicates on the same column instead of intersecting with them. That is
the accuracy traded for the bound, and it is what happened before every subquery
set started reaching this code.

On TPC-H sf1 this takes query planning from 395ms to 58ms on q05, 164ms to 25ms
on q03 and 135ms to 29ms on q07, while all 42 PREWHERE decisions across the 22
queries stay identical to those the exact ranges produce.
100000 was a placeholder. Measuring the adapted TPC-H queries at sf1 on a single
node, lowering it to 10000 takes another 10% off the suite (867ms -> 777ms
total) - q04 57ms -> 20ms, q12 66 -> 48, q14 32 -> 13, q09 68 -> 63 - and all 42
PREWHERE decisions across the 22 queries still match the ones the exact ranges
produce, as they do at 100000. 1000 buys nothing further: the residual planning
time on those queries is not spent on `IN` sets.
Neither half of this behaviour was observable from SQL, so add two profile
events for the paths that were introduced: `SelectivityEstimatorInSetNotBuilt`
when a set cannot be analysed because filling it would mean running a subquery
during planning, and `SelectivityEstimatorInSetEstimatedFromSize` when the
selectivity comes from the size and bounds of the set rather than its ranges.
Both are also useful on their own, to see when the cheap path engages.

The test asserts that the size-based estimate is used above the limit and never
below it, that an unbuilt set is skipped rather than filled, that the estimate
never changes the answer, and that it picks the same PREWHERE as the exact
ranges. Statistics are materialized only by a merge, so the table needs two
parts and an OPTIMIZE - a single level-0 part exercises none of this.

`auto_statistics_types` is pinned per table and the PREWHERE-related settings
per query: settings randomization otherwise turns off
`allow_reorder_prewhere_conditions`, and the estimator is then never consulted.
Ran 25 times with randomization and 12 times without, all passing.
`estimateSelectivityFromSetSize` looks the left-hand side up in the column
statistics, so for an expression rather than a column - `lower(col) IN (...)` -
it finds nothing and returns the no-statistics estimate, which saturates to 1.0
for any set past a hundred elements. Below the limit the same atom is given a
flat `default_cond_equal_factor` by the "not a real column" branch further down,
which the size-based path returns before ever reaching. So the estimate for such
an atom jumped from 1% to 100% purely by the set growing past an internal cost
limit, and PREWHERE was reordered accordingly:

    capped:  Prewhere filter column: bitXor(k1, 42) IN (...) AND k2 > 5
    exact:   Prewhere filter column: k2 > 5 AND bitXor(k1, 42) IN (...)

Apply that same flat default in the size-based branch and skip the size estimate
entirely for expressions, which is also cheaper - no bounds pass and no `Field`
materialized at all.

The test covers it with a literal list, because a subquery set is never built
for a non-indexed expression and so would not reach this path. Verified that the
new case fails without the fix. Ran 12 times with settings randomization and 6
times without, all passing.
@clickhouse-gh

clickhouse-gh Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fec6144]

Summary: ✅


AI Review

Summary

This PR bounds the planning cost of IN-set selectivity estimation by avoiding subquery execution in the estimator and by switching large ready sets to a size-and-bounds heuristic. After reviewing the current diff and reconciling the existing review threads against the updated code, I did not find a remaining correctness, compatibility, or safety issue in the patch itself.

Missing context / blind spots
  • ⚠️ I could not validate the claimed planning-speed improvement directly because the measurements are linked from Slack rather than written into the PR. Copying the before/after numbers or a minimal benchmark result into the PR body would close that gap.
Final Verdict

✅ No remaining review findings in the current diff.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 71/74 (95.95%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 11, 2026
Comment thread src/Interpreters/PreparedSets.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing fec614419 with master 6481befc2 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 704.43 MiB 701.38 MiB -3.05 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

Comment thread src/Core/Settings.cpp Resolved
@nickitat
nickitat marked this pull request as ready for review August 20, 2026 14:00
@hanfei1991 hanfei1991 self-assigned this Aug 20, 2026
Comment thread src/Core/Settings.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 35 queries analysed

This PR bounds the cost of the col IN (set) selectivity estimator (new setting statistics_max_set_size_for_exact_selectivity_estimation, default 10000) and stops it running a subquery to fill a set during planning. That path only runs with column statistics enabled and a large IN-set present. Neither flagged TPC-H query (Q7, Q17) exercises it — Q7 has no large IN-set on a statistics-bearing column and Q17 uses a scalar-subquery comparison — so both flagged regressions have been downgraded to not_sure as off-path variance (Q17's measurements were also very noisy). No query in these runs plausibly touches the changed code path.

clickbench

🟢 No significant changes

tpch_adapted_1_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 7 not_sure 67 79 +17.9% <0.0001 plan_change: This PR only changes the col IN (set) selectivity estimator, which takes effect only with column statistics enabled and large IN-sets; TPC-H Q7 exercises neither, so the +17.9% cannot come from this diff and reads as run-to-run variance.
⚠️ 17 not_sure 64 103 +60.9% <0.0001 plan_change: Same off-path reasoning: Q17 uses a scalar-subquery comparison, not a large IN-set on a statistics-bearing column, so this estimator change can't touch it, and the underlying measurements were very noisy — the +60.9% is not a real PR effect.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 0db23bf9-b0ed-434a-b378-c3123d8feae1
  • MIRAI run: 18e3abe7-cbc2-48e0-b57f-d909303ebee8
  • PR check IDs:
    • clickbench_424073_1787317196
    • clickbench_424080_1787317196
    • clickbench_424096_1787317196
    • tpch_adapted_1_official_424103_1787317196
    • tpch_adapted_1_official_424129_1787317196
    • tpch_adapted_1_official_424143_1787317196

@nickitat
nickitat added this pull request to the merge queue Aug 21, 2026
Merged via the queue into master with commit add95ca Aug 21, 2026
176 checks passed
@nickitat
nickitat deleted the statistics-bound-in-set-estimation branch August 21, 2026 19:11
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 21, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 24, 2026
robot-ch-test-poll4 added a commit that referenced this pull request Aug 25, 2026
Cherry pick #114389 to 26.6: Don't build a set to estimate its selectivity
robot-ch-test-poll4 added a commit that referenced this pull request Aug 25, 2026
Cherry pick #114389 to 26.7: Don't build a set to estimate its selectivity
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 25, 2026
fm4v added a commit that referenced this pull request Aug 25, 2026
Backport #114389 to 26.6: Don't build a set to estimate its selectivity
PedroTadim added a commit that referenced this pull request Aug 26, 2026
Backport #114389 to 26.7: Don't build a set to estimate its selectivity
pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Sep 6, 2026
The settings changes history entry for `statistics_max_set_size_for_exact_selectivity_estimation` had 0 as the previous value, so `compatibility` with 26.6 or an earlier version restored the uncapped estimation, which can add hundreds of milliseconds to the planning of a single query.

Related: ClickHouse#116137
Related: ClickHouse#114389
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Query planning became ~10x slower in 26.6 when column statistics are present and a filter meets an IN (subquery)

6 participants