Repository navigation
Cherry pick #114389 to 26.6: Don't build a set to estimate its selectivity - #116157
Merged
robot-ch-test-poll4 merged 11 commits intoAug 25, 2026
Merged
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.
…timation Don't build a set to estimate its selectivity
…ts there), use uniq statistics in the test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Original pull-request #114389
Do not merge this PR manually
This pull-request is a first step of an automated backporting.
It contains changes similar to calling
git cherry-picklocally.If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.
The check results does not matter at this step - you can safely ignore them.
Troubleshooting
If the conflicts were resolved in a wrong way
If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:
pr-cherrypicklabel from the PRYou also need to check the Original pull-request for
pr-backports-createdlabel, and delete if it's presented thereThe PR source
The PR is created in the CI job