Repository navigation
Move a condition on the ORDER BY ... LIMIT column to PREWHERE next to the top-K filter - #129882
Conversation
…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]>
Internal second-model review (2 rounds, head ffc598f): 2 findings fixed, nits noted
Round 2 (head ffc598f): no findings. |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20261107-040219 |
|
cc @antaljanosbenjamin @Avogar, could you review this and add the |
|
Workflow [PR], commit [6bd1963] Summary: ✅
AI ReviewSummaryReviewed PR head Missing context / blind spots
Final VerdictStatus: ✅ Approve |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units130 translation units recompiled, 1593 s compile time in total, 130 of them have a recent master baseline. |
5756db2
…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]>
… 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]>
Closes: #129843
Related: #128582
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A
WHEREcondition on the only column ofORDER BY ... LIMIT, like inSELECT s FROM t WHERE s != '' ORDER BY s LIMIT 10, is now moved toPREWHEREnext 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
MergeTreeWhereOptimizerdoes 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 toPREWHEREand readssanyway. InWHERE,FilterTransformrecords in the query condition cache only the blocks it empties entirely, whilePREWHERErecords every granule it empties.Change:
PREWHEREif itcanBeMovedToTheFrontOfAndChain(deterministic, stateless, cannot throw, not lazily executed), and only when it can get its own read step:enable_multiple_prewhere_read_stepsis on and the reader can read the column ahead for all parts. The result is the plan master already builds for the explicitPREWHEREspelling.tryBuildPrewhereStepsgives such a conjunct its own step after__topKFilter, so the threshold step's filter stays optional (Combine the filters ofPREWHEREsteps 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 inWHERE, after their guards.GROUP BY ... LIMITattaches its top-K filter afterPREWHEREis 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 10000.56 / 0.92;ClientIP > 0repeated 0.78;SearchPhrase <> 'zzzz'1.02;DESC,LIKEandORDER BY EventTimecontrols within noise; peak memory of the firstURL <> ''run 31.8 -> 39.9 MiB. The losing shape joinstop_k_dynamic_filtering_single_string_column.xml. The new test05566checks the plan (aStringand a number column), the results, the cache gain and a guard;04631now also counts the read steps.Analysis and the original patch by snelheidai.
Workflow [PR]
Sync PR [sync-upstream/pr/129882]
Version info
26.11.1.1608-master(included in26.11and later)