Repository navigation
Combine I/O cost with selectivity in PREWHERE condition ordering - #110695
Conversation
When `use_statistics=1` (the default since `auto_statistics_types` was introduced), the PREWHERE optimizer sorted conditions by `estimated_row_count` alone, with `columns_size` only as a tiebreaker. This caused expensive conditions (e.g. Map column, ~500KB) to be placed before cheap ones (e.g. scalar column, ~1KB) whenever the expensive condition appeared more selective — ignoring the I/O cost difference. Apply the classic conjunctive filter ordering rule: sort by `cost / (1 - selectivity)`, i.e. the I/O cost per rejected row. This is computed as `columns_size / max(1, total_rows - estimated_row_count)` and replaces the separate `estimated_row_count, columns_size` pair in the condition comparison tuple. When statistics are unavailable (`estimated_row_count=0`, `total_rows=0`), the formula degrades to `columns_size`, preserving the existing behavior. Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
Workflow [PR], commit [583ac08] Summary: ❌
AI ReviewSummaryThis PR switches PREWHERE condition ordering from pure selectivity to a cost-per-rejected-row heuristic and adds regressions for the wide-part, compact-part, and tautology cases. I found one remaining performance bug: mixed wide/compact tables still feed incomplete byte estimates into the new primary sort key, so expensive predicates can be ranked too early even though the fully-compact fallback covers only the all-zero case. Findings❌ Blockers
Tests
Final VerdictChanges requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 34/34 (100.00%) · Uncovered code |
| @@ -494,6 +497,12 @@ void MergeTreeWhereOptimizer::analyzeImpl(Conditions & res, const RPNBuilderTree | |||
| pk_positions.emplace(cond.min_position_in_primary_key); | |||
| } | |||
|
|
|||
| /// Combine I/O cost with selectivity using the classic conjunctive filter ordering rule: | |||
| /// sort by cost / (1 - selectivity), i.e. cost per rejected row. | |||
There was a problem hiding this comment.
Sorry, I didn't understand why we order by cost per rejected row. Any reference?
There was a problem hiding this comment.
This is what Claude told me, and I trusted this (but this is why I asked you to review as well):
This is the classic rank-ordering theorem for conjunctive predicates (sometimes called the KBZ ordering).
Consider two filters A and B with I/O costs c_A, c_B and selectivities s_A, s_B (fraction of rows that pass):
- A then B: total cost =
c_A + s_A * c_B(always payc_A; payc_Bonly for thes_Afraction that passes A) - B then A: total cost =
c_B + s_B * c_A
A-first is cheaper when:
c_A + s_A * c_B < c_B + s_B * c_A
c_A (1 - s_B) < c_B (1 - s_A)
c_A / (1 - s_A) < c_B / (1 - s_B)
So the optimal order is: sort by c_i / (1 - s_i) ascending -- i.e., cost per rejected row. This generalizes to any number of independent conjuncts.
In the code, columns_size / max(1, total_rows - estimated_row_count) is proportional to c / (1 - s) since total_rows - estimated_row_count = total_rows * (1 - s), and the total_rows denominator is a constant across all conditions that doesn't affect the sort order.
References:
- Ibaraki & Kameda, "On the Optimal Nesting Order for Computing N-Relational Joins", ACM TODS 1984
- Krishnamurthy, Boral & Zaniolo, "Optimization of Nonrecursive Queries", VLDB 1986
- Hellerstein & Stonebraker, "Predicate Migration: Optimizing Queries with Expensive Predicates", SIGMOD 1993
There was a problem hiding this comment.
That makes sense. The fast test is flaky because sometimes the column_size is zero. I asked AI and got reply
Compact parts intentionally don't track per-column sizes.
If that's true, maybe we should compare selectivity when column_size is 0.
|
Tests with statistics failed, need to investigate. Maybe this approach doesn't work |
…re-cost-with-selectivity
…ilable The new `cost_with_selectivity` score is `columns_size / max(1, total_rows - estimated_row_count)`. On compact parts per-column compressed sizes are not tracked, so `columns_size` is 0 and the score collapses to 0 for every condition. Since this score is the only selectivity-bearing key in the sort tuple, all conditions tie and the original WHERE order is kept, discarding the selectivity estimate entirely. Fall back to `estimated_row_count` when `columns_size == 0` so ordering by selectivity is preserved. On wide parts (sizes known) the cost formula is unchanged. This fixes the `02864_statistics_usage` and `04266_statistics_basic_prewhere` fast-test failures. Adds `04811_prewhere_statistics_ordering_compact_parts` to cover the compact-part case. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: This PR reworks how the PREWHERE optimizer orders filter conditions, combining per-column I/O cost with selectivity (cost per rejected row) instead of sorting by estimated row count alone. That path only changes behavior for queries with two or more conjunctive conditions and column statistics available; without statistics the ordering is unchanged. The flagged ClickBench improvements (Q5, Q14, Q17) run on queries that either have no WHERE at all or a single condition, so the PR cannot plausibly produce their -10 to -12% deltas, and I downgraded all three to not-sure as run-to-run variance across the 6 source builds. Q18 and Q31 were correctly held as no-change within master's variance band, consistent with an off-path change. clickbenchFlagged queries (3 of 43)
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. tpch_adapted_1_official🟢 No significant changes Debug info
|
The cost-based PREWHERE ordering score divides by columns_size (compressed column size), so the condition order depends on part type and serialization - settings CI randomizes. This made several prewhere-ordering tests flaky. Pin the selectivity-oriented tests (04266, 04304, 03580, 04053) to compact parts, where per-column sizes are 0 and ordering falls back to selectivity alone, independent of size-affecting randomization. For 04513 (which must stay wide to exercise the cost path) split `modality` 50/50 so the reject-count ratio is ~2x while the Map column dwarfs the scalar, keeping cheap-filter-first stable. Verified with clickhouse-test --test-runs 100 -j 10: all affected tests pass 100/100 under randomized settings. Co-Authored-By: Claude Opus 4.8 <[email protected]>
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 units90 translation units recompiled, 1201 s compile time in total, 90 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.31 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
Symbol sizes
|
The cost-per-rejected-row score used max(1, total_rows - estimated_row_count) as the denominator, so a predicate that rejects no rows (estimated_row_count == total_rows) got a finite score equal to columns_size. A cheap tautology could then be scheduled before a genuinely selective but expensive predicate, which regresses the old estimated_row_count ordering. Give such predicates an infinite score so they always sort last, and keep the explicit no-statistics (total_rows == 0) and compact-part (columns_size == 0) fallbacks. Adds 04812_prewhere_statistics_tautology_last. Addresses review comment: #110695 (comment) Co-Authored-By: Claude Opus 4.8 <[email protected]>
countmin statistics are not available in the fast-test build (hence the other countmin tests are tagged no-fasttest). The tautology test does not need it: tdigest on `cheap` drives the tautology detection, and `expensive = 'absent'` stays selective via the default equality selectivity. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
@Avogar @hanfei1991 — title/description suggestions: Description (currently
Ignore if intentional. |
|
Hi @Avogar and @hanfei1991, It seems that this PR has affected Full-Text Index performance. Index is selected after the raw predicate. The reason is that Could you please take a look? |
Backport #110695 to 26.7: Combine I/O cost with selectivity in PREWHERE condition ordering
Resolve the conflicts of backporting #110695 ("Combine I/O cost with selectivity in PREWHERE condition ordering") to 26.3. The release branch has no grouping of PREWHERE conjuncts by column set (#106337), so: - `cost_with_selectivity` is computed per conjunct in `analyzeImpl`, right before the condition is added. - The early return of `analyze` for disabled reordering is not taken: it belongs to the grouping, and every conjunct already gets its cost in `analyzeImpl`. - `Condition::toString` keeps the single `node`. - Tests 04053, 04266 and 04304 cover features absent on 26.3 and stay deleted. - The new tests drop `explain_query_plan_default`, which 26.3 does not have; its `EXPLAIN` output is the legacy one already. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Cherry pick #110695 to 26.3: Combine I/O cost with selectivity in PREWHERE condition ordering
…RE condition ordering
Backport #110695 to 26.3: Combine I/O cost with selectivity in PREWHERE condition ordering
When
use_statistics=1(the default sinceauto_statistics_typeswas introduced), the PREWHERE optimizer sorted conditions byestimated_row_countalone, withcolumns_sizeonly as a tiebreaker. This caused expensive conditions (e.g. Map column, ~500KB) to be placed before cheap ones (e.g. scalar column, ~1KB) whenever the expensive condition appeared more selective — ignoring the I/O cost difference.Apply the classic conjunctive filter ordering rule: sort by
cost / (1 - selectivity), i.e. the I/O cost per rejected row. This is computed ascolumns_size / max(1, total_rows - estimated_row_count)and replaces the separateestimated_row_count, columns_sizepair in the condition comparison tuple.When statistics are unavailable (
estimated_row_count=0,total_rows=0), the formula degrades tocolumns_size, preserving the existing behavior.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Combine I/O cost with selectivity in PREWHERE condition ordering. It fixes performance regression in PREWHERE execution in some cases introduced after #101275. Part of #110462
Version info
26.8.1.1177-master(included in26.8and later)26.7.35.15,26.3.59.9