Skip to content

Combine I/O cost with selectivity in PREWHERE condition ordering - #110695

Merged
Avogar merged 6 commits into
masterfrom
prewhere-cost-with-selectivity
Aug 11, 2026
Merged

Avogar merged 6 commits into
masterfrom
prewhere-cost-with-selectivity

Conversation

@Avogar

@Avogar Avogar commented Jul 16, 2026 •

Copy link
Copy Markdown
Member

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.

Changelog category (leave one):

  • Performance Improvement

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

  • Merged into: 26.8.1.1177-master (included in 26.8 and later)
  • Backported to: 26.7.35.15, 26.3.59.9

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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [583ac08]

Summary: ❌

job_name test_name status info comment
Stress test (amd_asan_ubsan) FAIL
Sanitizer (STID: 1367-26c6) FAIL cidb, issue ISSUE EXISTS
Stress test (amd_tsan) FAIL
Logical error: Sizes of nested column and null map of Nullable column are not equal after deserialization (null map size = A, nested column size = B) (STID: 6726-6444) FAIL cidb, issue ISSUE EXISTS

AI Review

Summary

This 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

  • [src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp:524] The new cost_with_selectivity score assumes columns_size is a complete read-cost estimate, but MergeTreeData::getColumnSizes aggregates zeros from compact parts while ConditionSelectivityEstimatorBuilder::markDataPart still counts their rows in total_rows. On a mixed wide/compact table this turns the score into "wide-part bytes / all rejected rows", which systematically underprices predicates on columns that are mostly stored in compact parts and can still move an expensive Map/String filter ahead of a cheap selective scalar predicate.
    Suggested fix: carry an explicit "size unavailable" signal whenever any contributing part is compact and fall back to pure selectivity in that case, or feed a compact-part approximation like MergeTreeReadPoolBase::getSizeOfColumns into the cost term instead of treating missing bytes as zero.
Tests
  • ⚠️ Add a regression with both wide and compact parts in the same table. The new tests cover all-wide and all-compact layouts, but the partial-zero-size case above is the one that still slips through.
Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.00% 79.00% +0.00%

Changed lines: Changed C/C++ lines covered: 34/34 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 16, 2026
@hanfei1991 hanfei1991 self-assigned this Jul 16, 2026
@@ -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.

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.

Sorry, I didn't understand why we order by cost per rejected row. Any reference?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 pay c_A; pay c_B only for the s_A fraction 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

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.

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.

@Avogar

Avogar commented Jul 16, 2026

Copy link
Copy Markdown
Member Author

Tests with statistics failed, need to investigate. Maybe this approach doesn't work

Avogar and others added 2 commits August 5, 2026 16:08
…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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 5 not_sure 246 218 -11.4% <0.0001 This PR only reworks PREWHERE condition ordering, which engages with column statistics and a multi-condition PREWHERE. Q5 has no such filter, so the -11.4% cannot come from this change and reads as run-to-run variance.
⚠️ 14 not_sure 362 319 -11.9% <0.0001 The PREWHERE cost/selectivity reordering needs two or more conjunctive conditions plus statistics to reorder; Q14 filters on a single condition, so the -11.9% is unrelated to this PR and looks like variance across the 6 source builds.
⚠️ 17 not_sure 556 498 -10.5% <0.0001 Q17 has no WHERE/PREWHERE, so the condition-ordering change this PR makes cannot touch it. The -10.5% and ×N wall-clock gap over the smaller CPU drop point to environment variance, 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.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: d87c52be-82f3-4d28-aadf-f33a8496f991
  • MIRAI run: fa1ff4aa-42d1-445b-9a01-4c8fe12bfda2
  • PR check IDs:
    • clickbench_661368_1786405923
    • clickbench_661374_1786405923
    • clickbench_661385_1786405923
    • tpch_adapted_1_official_661397_1786405923
    • tpch_adapted_1_official_661410_1786405923
    • tpch_adapted_1_official_661441_1786405923

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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 583ac08b6 with master 5e52a0f26 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 8cc8d5031; 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 690.92 MiB 688.02 MiB -2.91 MiB (-0.42%)

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

90 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.
The matched translation units cost +211.0 s (+21%) in total before that adjustment.

Translation unit Master PR Δ vs median
src/Storages/StorageReplicatedMergeTree.cpp 37.7 s 36.4 s -13.1 s (-27%)
src/Interpreters/InterpreterSelectQuery.cpp 20.9 s 19.7 s -7.9 s (-29%)
src/Storages/StorageDistributed.cpp 17.9 s 16.9 s -6.7 s (-28%)
src/Planner/PlannerJoinTree.cpp 18.7 s 18.1 s -6.5 s (-27%)
src/Databases/DatabaseOrdinary.cpp 17.2 s 16.4 s -6.3 s (-28%)
src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp 17.5 s 17.0 s -5.9 s (-26%)
src/Interpreters/ClusterProxy/executeQuery.cpp 16.5 s 15.9 s -5.8 s (-27%)
src/Processors/QueryPlan/Optimizations/projectionsCommon.cpp 15.9 s 15.3 s -5.6 s (-27%)
src/Storages/MergeTree/Compaction/MergePredicates/ReplicatedMergeTreeMergePredicate.cpp 14.5 s 13.6 s -5.4 s (-28%)
src/Storages/Freeze.cpp 14.2 s 13.5 s -5.2 s (-28%)
Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse ProfileEvents::global_counters_storage 11.00 MiB 11.06 MiB +64.00 KiB (+0.57%)
programs/clickhouse-keeper ProfileEvents::global_counters_storage 11.00 MiB 11.06 MiB +64.00 KiB (+0.57%)

Job report

Avogar and others added 2 commits August 7, 2026 18:43
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
Avogar added this pull request to the merge queue Aug 11, 2026
Merged via the queue into master with commit 81a084f Aug 11, 2026
178 of 181 checks passed
@Avogar
Avogar deleted the prewhere-cost-with-selectivity branch August 11, 2026 19:18
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 11, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@Avogar @hanfei1991 — title/description suggestions:

Description (currently misleading):

  • Why: The body states the score "is computed as columns_size / max(1, total_rows - estimated_row_count)", but MergeTreeWhereOptimizer.cpp:515-529 implements no max(1, ...). A condition that rejects no rows gets +inf (scheduled LAST) -- the opposite of what max(1, ...) would give it (columns_size, i.e. possibly FIRST if the column is cheap); the PR's own 04812 test asserts the +inf behaviour. The body also omits the third branch entirely: when columns_size == 0 (compact parts) the score falls back to estimated_row_count, which is what the PR's 04811 test asserts and what the four pinned pre-existing tests now exercise.

  • Suggested addition:

    The score is not a single expression; analyzeImpl has four branches:

    • total_rows == 0 (no statistics) -> columns_size (pre-PR ordering, unchanged).
    • total_rows - estimated_row_count <= 0 (rejects no rows) -> +inf, so a useless condition is scheduled last regardless of how cheap it is.
    • columns_size == 0 (compact parts do not track per-column compressed sizes) -> estimated_row_count, i.e. pure selectivity ordering.
    • otherwise -> columns_size / rejected_rows.

    Note that the second and third branches make the score's unit depend on the branch (bytes-per-rejected-row vs. rows), and the two are compared in the same Condition::tuple. Also worth stating explicitly that 03580 / 04053 / 04266 / 04304 were pinned to compact parts, so they now cover only the third branch.

Ignore if intentional.

@alexbakharew

Copy link
Copy Markdown
Contributor

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 __text_index_ virtual column is empty (it is not a physical column) and this PR doesn't take it into account.

Could you please take a look?

@zlareb1 zlareb1 added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Oct 20, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 20, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 20, 2026
Backport #110695 to 26.7: Combine I/O cost with selectivity in PREWHERE condition ordering
Avogar added a commit that referenced this pull request Oct 21, 2026
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]>
robot-ch-test-poll4 added a commit that referenced this pull request Oct 21, 2026
Cherry pick #110695 to 26.3: Combine I/O cost with selectivity in PREWHERE condition ordering
robot-clickhouse added a commit that referenced this pull request Oct 21, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 21, 2026
alexey-milovidov added a commit that referenced this pull request Oct 22, 2026
Backport #110695 to 26.3: Combine I/O cost with selectivity in PREWHERE condition ordering
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 Pull request should be backported intentionally. Use this label with great care! 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants