Skip to content

Move a condition on the ORDER BY ... LIMIT column to PREWHERE next to the top-K filter - #129882

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:top-k-filter-same-column-prewhere
Nov 7, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:top-k-filter-same-column-prewhere

Conversation

@groeneai

@groeneai groeneai commented Nov 7, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #129843
Related: #128582

Changelog category (leave one):

  • Performance Improvement

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

A WHERE condition on the only column of ORDER BY ... LIMIT, like in SELECT s FROM t WHERE s != '' ORDER BY s LIMIT 10, is now moved to PREWHERE next to the top-K filter, which reads that column anyway, so the query condition cache remembers the granules the condition rejects. Repeated runs of ClickBench Q25 are about 2x faster.

Description

MergeTreeWhereOptimizer does not move a condition that reads all queried columns, as that saves no reads. With a pending top-K dynamic filter this does not hold for the sort column: __topKFilter(s) is prepended to PREWHERE and reads s anyway. In WHERE, FilterTransform records in the query condition cache only the blocks it empties entirely, while PREWHERE records every granule it empties.

Change:

  • A conjunct whose only column is the pending top-K column is moved to PREWHERE if it canBeMovedToTheFrontOfAndChain (deterministic, stateless, cannot throw, not lazily executed), and only when it can get its own read step: enable_multiple_prewhere_read_steps is on and the reader can read the column ahead for all parts. The result is the plan master already builds for the explicit PREWHERE spelling.
  • tryBuildPrewhereSteps gives such a conjunct its own step after __topKFilter, so the threshold step's filter stays optional (Combine the filters of PREWHERE steps when the later conditions cannot throw #128582) and the conjunct runs only on the rows the threshold passes once it is selective. Without this, SearchPhrase <> 'zzzz' (passes every row) was 6-9% slower.

Conditions that may throw or are lazily executed (LIKE, conversions) stay in WHERE, after their guards. GROUP BY ... LIMIT attaches its top-K filter after PREWHERE is chosen, so the same shape there is unchanged.

Measured locally (release, one-part hits, 6 alternating rounds, max_threads = 4, new/old): Q25 repeated 0.51, first 0.91; LIMIT 1000 0.56 / 0.92; ClientIP > 0 repeated 0.78; SearchPhrase <> 'zzzz' 1.02; DESC, LIKE and ORDER BY EventTime controls within noise; peak memory of the first URL <> '' run 31.8 -> 39.9 MiB. The losing shape joins top_k_dynamic_filtering_single_string_column.xml. The new test 05566 checks the plan (a String and a number column), the results, the cache gain and a guard; 04631 now also counts the read steps.

Analysis and the original patch by snelheidai.


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

Version info

  • Merged into: 26.11.1.1608-master (included in 26.11 and later)

groeneai and others added 4 commits November 7, 2026 00:01
…opKFilter`

`SELECT s FROM t WHERE s != '' ORDER BY s LIMIT n` kept `notEmpty(s)` in WHERE:
`MergeTreeWhereOptimizer` does not move a condition that reads all queried
columns, because moving it cannot save reading other columns. With a pending
top-K dynamic filter that rationale does not hold for the sort column:
`installTopKDynamicFilter` prepends `__topKFilter(s)` to PREWHERE, which reads
`s` anyway. Staying in WHERE costs the query condition cache: `FilterTransform`
records only blocks it empties entirely, while PREWHERE records every granule it
empties (ClickBench Q25 repeated run).

A conjunct whose only column is the pending top-K column is now viable when it
`canBeMovedToTheFrontOfAndChain` (deterministic, stateless, cannot throw, not
lazily executed): in PREWHERE it can be evaluated on rows that `__topKFilter` and
the preceding conjuncts reject, or ordered before a guard written in front of it,
and only such a conjunct is safe there. Others (`LIKE`, conversions that may
throw) stay in WHERE as before. The resulting plan is the one master already
builds for the explicit `PREWHERE` spelling.

`optimizePrewhere` passes the column only when the conjunct can get its own read
step after `__topKFilter` (next commit): with `enable_multiple_prewhere_read_steps`
and when the reader can read the column ahead for all parts the read may touch
(`canReadColumnsAhead`, split out of `canReadPrewhereColumnsAhead`). Otherwise
the conjunct would share the `__topKFilter` step and run on every row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A conjunct on the top-K column that `canBeMovedToTheFrontOfAndChain` used to
share the `__topKFilter` step, so it ran on every row of the block, while in
WHERE it ran only on the rows the threshold passed: `SearchPhrase != 'zzzz'`
(passes every row) was slower with the previous commit alone. With its own step
the `__topKFilter` step's filter stays optional (ClickHouse#128582), so it is applied only
when it keeps < 60% of a block: while the threshold passes most rows both
conditions run on the whole block as before, once it is selective the condition
runs only on the surviving rows. Its column is read by the `__topKFilter` step.

Only with `read_ahead_columns`: without it ClickHouse#128582 forces the filter, and a
column-free step of a non-adaptive part would read its column again.

The losing shape is added to the performance test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`04631` counts the read steps of a condition on the top-K column, written in
WHERE and in PREWHERE: `__topKFilter` in the first step, the condition in the
second. Both arms read one step on master and with the first commit alone, so
they cover the step split, which the plan arms of `05566` cannot see (the
`Prewhere filter column` line is the same with one step or two).

`05566` gets a plan arm for a number column, resets the fixture's thread and
block settings before reading `system.query_log`, and states why the pinned
settings are there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reword the analyzeImpl comment: the reason to move a condition on the only top-K column is that PREWHERE records each granule it empties in the query condition cache, not that it is evaluated on more rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, head ffc598f): 2 findings fixed, nits noted
Finding Verdict
⚠️ Round 1: no test failed if the separate read step after __topKFilter was reverted AGREE, fixed: 04631 counts the steps (WHERE and PREWHERE spelling)
💡 Round 1: 05566 scanned system.query_log with the fixture's 1 thread / 256-row blocks AGREE, fixed
💡 Round 1: number-column shape untested; pinned settings without a reason AGREE, fixed
💡 The guard arm checks rows only Noted: the LIKE plan arm is the one that fails if the movability check is dropped
💡 Another file-static __topKFilter name check Noted: the local pattern in 4 other files

Round 2 (head ffc598f): no findings.

@groeneai

groeneai commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: 05566 on the old binary prints 0 1 for the plan arm and 0 for the cache arm (repeated run SelectedMarks 100 -> 100) on every run; the new binary prints 1 0 and 1 (100 -> 25).
b Root cause explained? MergeTreeWhereOptimizer refuses a condition that reads all queried columns, but __topKFilter reads the sort column in PREWHERE anyway; in WHERE, FilterTransform records the query condition cache only for fully emptied blocks.
c Fix matches root cause? Yes: the optimizer rule is refined exactly where its rationale does not hold, plus the read-step split that keeps the moved condition off the rows the threshold rejects. No setting, no guard.
d Test intent preserved / new tests added? New test 05566 (plan for a String and a number column, results, cache, guard); 04631 gains two read-step-count arms (additions only); 05332 unchanged and passing; the losing shape is added to the existing perf test.
e Both directions demonstrated? Yes, old and new debug binaries (and change 1 alone) on the same tests and fixtures; the 04631 step-count arms read 1 step on the old binary and on change 1 alone, 2 on the new one.
f Fix is general across code paths? Both viability paths (allow_reorder_prewhere_conditions on and off); the split applies only after __topKFilter with read-ahead, so other tryBuildPrewhereSteps callers are unchanged; GROUP BY ... LIMIT (filter attached after PREWHERE is chosen) is unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? String and numeric conditions, Nullable(String) with a pending alter (stays off), LIKE (stays in WHERE), ASC/DESC, LIMIT 3 to 1000, single- and multi-column queries.
h Backward compatible? (maintainer-approved exception only) Yes: plans only; no setting or format change; without multi-step PREWHERE, read-ahead or a pending top-K filter the plan is unchanged.
i Invariants and contracts preserved? Results equal on all runs; only conditions that cannot throw and are deterministic and stateless move or split, so guards keep working; __topKFilter stays the first step; the query condition cache key is the one of the explicit PREWHERE plan.

Session id: cron:clickhouse-impl-slot-6:20261107-040219

@groeneai

groeneai commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @antaljanosbenjamin @Avogar, could you review this and add the can be tested label so CI runs? With a pending top-K dynamic filter, MergeTreeWhereOptimizer now moves a condition that cannot throw on the sort column to PREWHERE (which __topKFilter reads anyway), and tryBuildPrewhereSteps gives it its own read step after __topKFilter, so the query condition cache records the granules it empties (repeated ClickBench Q25 about 2x faster).

@clickhouse-gh

clickhouse-gh Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6bd1963]

Summary: ✅


AI Review

Summary

Reviewed PR head 6bd1963c87eb34235ee3fb820c3f409af41bab22, the full diff, surrounding implementation, and all prior discussion. The change moves eligible conditions on the top-K sort column into PREWHERE and gives them a separate read step after __topKFilter, improving query condition cache granule attribution. No actionable findings. Focused plan, result, cache, and read-step coverage, together with the supplied before/after measurements, support approval.

Missing context / blind spots
  • ⚠️ No local build or runtime tests were run because this checkout has no ClickHouse binary or configured build directory. Runtime validation relies on the author's reported regression runs and performance measurements; independent confirmation would require running 04631 and 05566 with a binary built from the reviewed commit.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6bd1963c8 with master 6edbb4dd8 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov alexey-milovidov left a comment

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.

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Nov 7, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 7, 2026
Merged via the queue into ClickHouse:master with commit 5756db2 Nov 7, 2026
374 of 375 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 7, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 11, 2026
…p-k-string-decode-bound

Resolve conflicts with ClickHouse#129882 and ClickHouse#126530: `optimize` takes both
`top_k_filter_column` and `top_k_string_sort_column`, the step predicates
keep both conditions, and `get_columns_written_to_cache` returns master's
`VectorWithMemoryTracking<bool>`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 23, 2026
thevar1able pushed a commit to actueleai/ClickHouse that referenced this pull request Nov 24, 2026
… runtime filter in the query condition cache"

This reverts commit 64da8a0, reversing
changes made to be89302.

Conflicts resolved by keeping the later changes in the same lines:
`is_query_prewhere` (ClickHouse#130645), the `last_reader_evaluating_defaults`
argument (ClickHouse#128452), `readsSameColumns` (ClickHouse#124880), `follows_top_k_filter`
(ClickHouse#129882), and the PREWHERE query condition cache write of ClickHouse#115522 in
its own form before it merged ClickHouse#122380.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. 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.10-must-backport

Projects

None yet

5 participants