Repository navigation
Don't build a set to estimate its selectivity - #114389
Conversation
`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.
|
Workflow [PR], commit [fec6144] Summary: ✅
AI ReviewSummaryThis PR bounds the planning cost of Missing context / blind spots
Final Verdict✅ No remaining review findings in the current diff. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 71/74 (95.95%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units416 translation units recompiled, 3465 s compile time in total, 416 of them have a recent master baseline. |
|
📊 Cloud Performance Report ✅ AI verdict: This PR bounds the cost of the clickbench🟢 No significant changes tpch_adapted_1_officialFlagged queries (2 of 22)
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
|
Cherry pick #114389 to 26.6: Don't build a set to estimate its selectivity
Cherry pick #114389 to 26.7: Don't build a set to estimate its selectivity
Backport #114389 to 26.6: Don't build a set to estimate its selectivity
Backport #114389 to 26.7: Don't build a set to estimate its selectivity
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
Changelog category (leave one):
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 behindcol 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 newstatistics_max_set_size_for_exact_selectivity_estimationsetting (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
26.7.6.16,26.6.4.25