Repository navigation
Let TopN dynamic filtering share PREWHERE, with __topKFilter first - #117968
Conversation
With use_top_k_dynamic_filtering = 1 (default), a query of the shape SELECT ... WHERE <predicate> ORDER BY <col> LIMIT n read MORE data than with the feature off: 16.1% more compressed bytes on a 2M-row table, and the main reader went from reading 0 rows to reading all 2,000,000. tryOptimizeTopK built a fresh PrewhereInfo holding only __topKFilter and installed it wholesale in the first optimization pass. That changed the read's output header, so a converting ExpressionStep was spliced between the FilterStep and the read. optimizePrewhere requires the filter's child to be the source step itself, so with that step in between the cast failed and the user's predicate was never promoted to PREWHERE: it stayed a Filter above the read, where it prunes nothing. The analysis stays in the first pass, where index analysis and the query condition cache setup depend on it. Only the PrewhereInfo mutation moves to a new pass that runs right after optimizePrewhere, so the filter is merged into whatever PREWHERE promotion produced instead of displacing it. The conjunction is kept flat because MergeTreeSplitPrewhereIntoReadSteps splits on the direct children of the root, and a nested and() would collapse a multi-condition PREWHERE into a single read step. This also removes the !getPrewhereInfo() gate, so an explicit user PREWHERE no longer disables dynamic filtering outright. getTopKReusePredicateOnlyConditionHash now returns the whole and() root hash when no TopK child was stripped. The filter DAG is built after index analysis, so a plain multi-conjunct WHERE reaches the helper with nothing to strip and would otherwise hit the >1-child bail and lose cross-query cache reuse. Correctness verified across 11 shapes (selective WHERE, ClickBench-like WHERE, explicit PREWHERE, multi-condition PREWHERE, no filter, optimize_move_to_prewhere = 0): results are byte-identical with the setting on and off for a total ORDER BY. Co-Authored-By: Claude Fable 5 <[email protected]>
…amic-filter-coexist-prewhere
Follow-up to the coexistence change earlier on this branch, which merged the dynamic TopN threshold filter into the read's existing PREWHERE but appended it as the last conjunct. Conjunct order is read-step order, so the last slot made the ClickBench-shaped query read 56.1% more compressed bytes than master (27,934,717 vs 17,898,967 on a 2M-row table, deterministic across repeats): the filter only ran after the user's condition had already read its own column. __topKFilter is the cheapest condition available: it reads one column, the sort key, which the query has to read anyway. Putting it first is what the feature owner asked for on the issue, and it is what the measurements support. Measured on 2M rows, max_threads = 1, compressed bytes read: shape dyn=0 master this change WHERE url LIKE (0 rows match) 49,816,933 57,843,021 57,822,861 WHERE sp != '' (ClickBench) 27,934,717 17,898,967 18,140,951 PREWHERE url LIKE 49,816,933 49,816,933 57,822,861 PREWHERE sp != '' 27,934,717 27,934,717 18,140,951 The explicit-PREWHERE row is the reported regression: master cannot use dynamic filtering at all when a PREWHERE already exists, so it reads 27,934,717 bytes either way, and sharing the slot brings that down 35%. The two url LIKE rows are not improved, and the second regresses. That shape matches almost no rows, so PartialSortingTransform never sets a threshold and __topKFilter stays constant-true: it reads the sort column and rejects nothing. That is a property of the threshold, not of the placement, and it is unchanged from the previous behaviour of this branch. 03711_top_k_by_skip_index pinned the old shape, in which a query carrying WHERE v2 > 0 ended up with a PREWHERE holding only __topKFilter. Its reference now shows the merged conjunction, which is the point of the change. The test gained pins for optimize_move_to_prewhere, query_plan_optimize_prewhere and query_plan_remove_unused_columns, because the printed filter column now depends on the WHERE being promoted and on the action positions being stable; without them the test failed 9 of 100 randomized runs. Correctness is unchanged: 18 query shapes (selective and ClickBench-like WHERE, explicit PREWHERE, two- and three-condition PREWHERE, no filter, LowCardinality and Nullable predicates, DESC and multi-key ORDER BY, row policy, view, Distributed, IN subquery, JOIN, parallel replicas, FINAL, and with optimize_move_to_prewhere, query_plan_optimize_prewhere and enable_multiple_prewhere_read_steps individually disabled) return byte-identical rows with use_top_k_dynamic_filtering on and off under a tie-free total ORDER BY. One trade-off worth stating: merging __topKFilter into the root conjunction makes the whole root non-deterministic for VirtualColumnUtils::isDeterministic, so the PREWHERE query-condition-cache entry is no longer written for a TopK read whose skip-index arm is inactive. Measured with positive controls: 1 entry before, 0 after, for that shape only; non-TopK reads, the skip-index arm, the index-analysis path and the plain-WHERE shape are all unchanged. ClickHouse#114659 adds the salted write that restores it and composes with this change. Co-Authored-By: Claude Opus 5 <[email protected]>
`getTopKReusePredicateOnlyConditionHash` returns the whole root's hash when no internal `__topKFilter` child was stripped from it. That is the branch that keeps cross-query query-condition-cache reuse alive for a `WHERE a AND b` predicate now that the filter `ActionsDAG` is built before the filter is installed, so the root arrives as a plain `and(a, b)` with nothing to strip; before the reordering it arrived as `and(__topKFilter, and(a, b))` and the reuse key came out of the strip instead. Nothing in the tree covered it. Every existing section of `04539_query_condition_cache_topk_reuse_where` primes `v2 = 10000`, whose filter root is a single `equals`, so they all exercise the fallthrough at the end of the function. The new section primes `v2 = 10000 AND id < 4294967295` with a plain `WHERE`, then reads the same predicate through a TopK query, and asserts `QueryConditionCacheHits` together with `SelectedMarks` < `SelectedMarksTotal` out of `system.query_log`, which are the two columns the file already asserts. The primary-key conjunct prunes nothing, so the priming row reads `0 0` exactly like the existing one. `optimize_move_to_prewhere = 0` is already pinned at the top of the file, which is what keeps the read on the `WHERE` path where the consulted key is salted with the TopK parameters; a salted key cannot match the entry the plain `WHERE` wrote, so the predicate-only probe is the only route to a hit and the assertion cannot pass for another reason. Proven live rather than assumed: reverting those four lines and rebuilding turns the new row from `1 1` to `0 0` while leaving every other row in the file unchanged, and restoring them rebuilds a byte-identical binary. The section also passes on the base revision, where the reuse is reached by stripping, so it guards a preserved invariant rather than new behaviour. Clean at `--test-runs 50 --long-test-runs-ratio 1`. The ratio flag is needed because the test is tagged `long`, and `clickhouse-test` otherwise multiplies the run count by 0.1. Co-Authored-By: Claude Opus 5 <[email protected]>
`05059` asserted the shared-`PREWHERE` behaviour only for base-table reads, so the normal-projection path had no coverage at all: no test in the tree combined a `PROJECTION` with `use_top_k_dynamic_filtering = 1`. The existing `04658_query_condition_cache_topk_normal_projection` deliberately runs with dynamic filtering off, because a `__topKFilter` node would suppress the reader-level write it measures, so it pins the query condition cache gate rather than this path. The new section pins the durable invariant instead: a projection-backed TopK read still carries the threshold filter, and returns the same rows with the feature off and on. It does not assert the read-step count or the `_projection_filter` root, so a later change that restores the split does not have to invert it. Two negative controls (`optimize_use_projections = 0`, `use_top_k_dynamic_filtering = 0`) show the two presence rows can go dark. `optimize_use_projections` is pinned at the top of the file because the settings randomizer turns it off in one run in twenty. `04539` filled its second conjunct from `id`, which `rand` can set to the maximum `UInt32`, so `id < 4294967295` could drop the planted row once in 2^32 runs. `v1` is `number` over `numbers(1_000_000)`, so `v1 < 1000000` holds for every row by construction, and `v1` is not part of the primary key, so it cannot prune a mark and the prime row stays `0 0` structurally rather than probabilistically. Reference values are unchanged. Two comments were falsified by the shared-`PREWHERE` change and are corrected. In `04628` an explicit `PREWHERE` now does take dynamic filtering, so that section's read is stamped as TopK by both arms rather than by the minmax skip index alone; measured with the gate on, its reuse row still flips to `1`, so the read-side gate is still what suppresses the reuse and the section still discriminates. In `ReadFromMergeTree` the clone no longer always carries `__topKFilter`: `installTopKDynamicFilter` runs in the second optimization pass, so a clone taken before it carries only `dynamic_filter_pending`, and dropping `top_k_filter_info` loses either state. Co-Authored-By: Claude Opus 5 <[email protected]>
…ave chosen the read `installTopKDynamicFilter` merges the `__topKFilter` threshold condition into whatever `PREWHERE` the read already has, so it has to see the read that will actually run. It ran right after `optimizePrewhere`, which is too early: `optimizeUseNormalProjections` can replace the read and rebuild its `PREWHERE` afterwards, and `optimizeReadInOrder` decides afterwards whether the read delivers rows in sort order at all. Moving the traversal to the end of the second pass addresses both. On a read served by a normal projection, `QueryDAG::buildImpl` folds the read's own `prewhere_actions` into `query.dag` as a single filter node, and `QueryDAG::build` wraps a single filter node in a `_projection_filter` alias. `MergeTreeSplitPrewhereIntoReadSteps` requires a root `and`, so a conjunction merged before the replacement collapsed the projection read into one step that reads the sort column and the predicate column together: 16,187,392 compressed bytes against 8,650,752 for the same query without the merge, on a 2M-row fixture with a selective first condition. Merging after the replacement puts an `and` back at the root, and the two read steps return by construction. Reading in sort order and filtering by a running threshold are mutually exclusive: once the threshold is established the condition rejects every remaining row, the `LIMIT` never cancels the pipeline early, and the read degenerates into a full scan. The first pass predicts that state from the base table's sorting key, which cannot see the order a projection provides. Asking the read for its `getInputOrder` once `optimizeReadInOrder` has decided is exact and covers the projection case: a query ordered by a column that a normal projection is sorted by read all 2,000,000 rows and 32,065,536 bytes instead of 49,152 rows and 1,179,648. The first-pass heuristic is kept, so either test suppresses and nothing is newly enabled. The TopK stamp and the threshold tracker stay in place, because they still salt the query condition cache key and select skip-index marks. `need_filter` is now inherited from the `PREWHERE` being merged into rather than forced, which is what the sibling merge in `optimizePrewhere` does. Every `PrewhereInfo` that can reach here sets it at construction, so that part is robustness only. Co-Authored-By: Claude Opus 5 <[email protected]>
…n `05059` Two new assertions, both in the `SELECT count() > 0 FROM (EXPLAIN ...) WHERE explain ILIKE` form the file already uses. The first pins the printed `PREWHERE` filter column of a projection-served read as `and(__topKFilter(s), _projection_filter)`. That root node type is what `tryBuildPrewhereSteps` gates on, so the assertion is the cheapest observable proxy for the read-step count: with an alias root the projection read collapses to a single step. It is the coverage the existing projection section deliberately left out, and it goes red on a build whose merge still runs before projection replacement. The second pins the absence of `__topKFilter` on a read that a projection sorted by the `ORDER BY` column serves in order. It carries a positive control on the same table (`optimize_use_projections = 0` reads the base table, which is not ordered by that column, and still installs the filter) so that an empty match cannot be misread as the fixture failing to qualify, and a negative control on a projection sorted by another column, which must still carry the filter. The `ORDER BY` there needs a second key. With a single key the projection supplies the whole order, `SortingStep` takes its `need_finish_sorting == false` path, no `PartialSortingTransform` is created and no threshold is ever published, so a leftover filter is inert and the shape does not exercise the state the suppression exists for. `optimize_read_in_order` is pinned at the top of the file because the settings randomizer turns it off half the time and the suppression is decided from the read's chosen order. Co-Authored-By: Claude Opus 5 <[email protected]>
`installTopKDynamicFilter` built `__topKFilter` in a separate `ActionsDAG` and folded it into the read's existing `PREWHERE` with `ActionsDAG::mergeNodes`, which identifies nodes by result name alone: it indexes every node already in the first DAG by `result_name`, discards any node reachable from the second DAG's outputs whose name is already taken, and returns the pre-existing node instead (`ActionsDAG.cpp:2565-2567`, `:2591-2596`, `:2619-2623`). A stored column named exactly `__topKFilter(<sort column>)` therefore captured the generated node and the read filtered on that column's own values. On a table holding such a column filled with zeros, a query filtering on both `pred` and that column, ordered by `k` with `LIMIT 5`, returned five rows with `use_top_k_dynamic_filtering = 0` and none with it on. The condition is now added directly to the cloned PREWHERE DAG, where `addFunction` allocates a fresh node unconditionally. The sort column is resolved among that DAG's own inputs and added as an input only when absent; a name that resolves to something else, or to an input of another type, refuses the install rather than guessing. Repairing the plan is not sufficient, because the reader chain resolves by name as well. `MergeTreeSplitPrewhereIntoReadSteps` re-declares a value computed by an earlier read step as an input of the later step's DAG (`MergeTreeSplitPrewhereIntoReadSteps.cpp:106`, `:119`) and collects each step's required columns into a `NameSet` (`:56-57`), so two nodes under one name are indistinguishable to it: with the plan corrected, the same query still returned no rows whenever the PREWHERE was split. The install therefore refuses when the node it built, or the merged root, would share a result name with any other node in the DAG. Refusing is safe: the pending bit is cleared first, so the read simply runs without the threshold filter. This also corrects two claims in the message of 3c50ba7, whose code was and remains right. `need_filter` inheritance is not "what the sibling merge in `optimizePrewhere` does": `optimizePrewhere.cpp:319` reads `existing->need_filter || prewhere_info->need_filter`, and `splitAndFillPrewhereInfo` has already forced the second operand true at `:102`, so that line always yields true - it forces the flag, it does not inherit it. And not "every `PrewhereInfo` that can reach here sets it at construction": `ExpressionAnalyzer.cpp:2071` uses the two-argument constructor, which leaves `need_filter` false (`SelectQueryInfo.h:49`), and `InterpreterSelectQuery.cpp:1122-1124` forces it true only when the query has no `WHERE`, so an old-analyzer `PREWHERE p WHERE q` with a non-promotable `q` arrives with the flag false. Inheriting either value is correct because `MergeTreeReadersChain::executePrewhereActions` applies the accumulated final filter at the last reader when no step applied it (`MergeTreeReadersChain.cpp:536-544`). `05059` gains the collision case and a second section where a projection covers only some parts, so the plan is a union of the projection read and the base-table read, asserting that both reads carry the threshold filter. That section needs no code change - the union's children are the topmost expression step of each branch, never the reads, so each read is still the only child of its own parent - and it is added because neither existing projection fixture could reach the partial-coverage shape. One stale comment in `optimizeDirectReadFromTextIndex.cpp` is dropped with it: it named a first-pass converting step of `tryOptimizeTopK`, which no longer creates one. The file is now tagged `no-parallel-replicas`, as its sibling `03711_top_k_by_skip_index` already is: it pins exact read-step shapes, and both the settings randomizer and the `ParallelReplicas` CI flavour would replace the read step. Co-Authored-By: Claude Opus 5 <[email protected]>
Without an existing `PREWHERE`, `installTopKDynamicFilter` named the prewhere column after the generated node alone and set `remove_prewhere_column`, so a table carrying a stored column of that exact name lost it. The reader resolves the prewhere column by name in `MergeTreeSelectProcessor::readCurrentTask`, so a plain `SELECT` of the sort column and the stored one, with `query_plan_optimize_lazy_materialization = 0`, was rejected with `NOT_FOUND_COLUMN_IN_BLOCK` at the setting's default. The existing-`PREWHERE` branch was already fail-closed on the same hazard; the check now covers both by comparing the final prewhere column name against the read's pre-install header. A refused install leaves the read runnable and unfiltered, which is what `use_top_k_dynamic_filtering = 0` produces. The header is the surface rather than the table's columns because a column that exists in the table but is not read cannot collide, and declining there would lose the optimization for nothing. Generating a collision-free name instead was rejected: every name-based scheme is name-matched again downstream, by the reader and by `MergeTreeSplitPrewhereIntoReadSteps`. `installTopKDynamicFilter` runs before `optimizeLazyMaterialization2` (`optimizeTree.cpp:559` and `:727`), so a stored column that lazy materialization would later move into its own read step is still in the header at install time and the filter is refused there too. That costs the optimization only for a table whose column is named `__topKFilter(<sort column>)`, the rows are identical either way, and `05059` now pins both arms. `05059` also gets a tighter fixture control for the existing-`PREWHERE` case. The previous pattern matched an `INPUT` line anywhere in the plan, which the steps above the read print too; on the pre-fix binary it stayed `1` even for a query where the stored column is read outside the `PREWHERE`. Matching the `Prewhere filter column:` line scopes it to the read. The partial-projection section needs no code change, and its `count() = 2` row is the tripwire for why. `optimizeUseNormalProjection` unions `iter->node->children[iter->next_child - 1]`, where `iter` comes from a walk-up that stops at the first step that is neither a `FilterStep` nor an `ExpressionStep` (`optimizeUseNormalProjection.cpp:359-366` and `:812`), so with nothing between the sort and the read the base-side `Union` child would be the read itself, and `tryOptimizeTopK` tolerates that shape: both the `ExpressionStep` and the `FilterStep` hops are optional. What rules it out is the planner, not this optimizer. `addExpressionStep` (`Planner.cpp:575`) has no triviality check and runs whenever the query sorts (`:2824`, the "Before ORDER BY" step).
Prepending `__topKFilter` to the user's own conditions changes what a stateful
predicate sees. `enable_multiple_prewhere_read_steps` defaults to true
(`src/Core/Settings.cpp:985`), so the merged root is split into read steps, and
`MergeTreeSplitPrewhereIntoReadSteps.cpp:255-262` merges only adjacent
conditions specifically to preserve the order the user wrote. Each step
filters the block the next one sees, so a condition that depends on its
position within a block observes a different block than it does alone.
Measured on a 200,000-row table keyed by `intHash32(number)`, three
repetitions per cell with `max_threads = 1` and zero spread:
SELECT groupArray(k) FROM (
SELECT k FROM t PREWHERE rowNumberInBlock() < 100 ORDER BY k LIMIT 3)
read [470574,1032774,2727291] at `use_top_k_dynamic_filtering = 0` and
[8612,23139,25905] at 1 before this change, and the same rows at both values
after it. The two arms hold byte-identical data (`sum(cityHash64(k))` equal)
and the same part layout, so only the install differs. The divergence needs
the threshold to cut inside a block: it does not appear with a key that is
monotone in row order, nor with a predicate tight enough to leave the top-K
heap below capacity, nor with `enable_multiple_prewhere_read_steps = 0`.
Two existing sites treat a stateful condition the same way. `FilterStep.cpp:292`
refuses to split an AND chain into multiple filter transforms when
`hasStatefulFunctions()`, and `filterPushDown.cpp:1137` refuses to push a
stateful filter down at all.
A stateful predicate that stays in the `WHERE` above the read is not affected
by this check and is unchanged from master: dynamic filtering installs its own
PREWHERE beneath the filter, so both arms produce
`Filter column: less(rowNumberInBlock(), 100_UInt8)` over
`Prewhere filter column: __topKFilter(k)` and both diverge the same way.
`rowNumberInBlock` is documented non-deterministic, and `max_block_size` alone
already changes that query's answer, so what the optimization should promise
for such a predicate is a semantics question rather than a defect here.
Three comments are corrected in the same commit. `installTopKDynamicFilter`
runs at `optimizeTree.cpp:559`, after the only pass that builds
`query_info.filter_actions_dag` for a non-FINAL MergeTree read
(`optimizePrimaryKeyConditionAndLimit` adds the storage PREWHERE and calls
`applyFilters` at `optimizePrimaryKeyConditionAndLimit.cpp:24,83`, run at
`optimizeTree.cpp:247`); the other `applyFilters` callers are FINAL-only and
`tryOptimizeTopK` returns 0 on FINAL. So `__topKFilter` can no longer reach
that DAG, and the docs claiming otherwise were stale. `isTopKFilterFunction`,
the strip branch and both copies of `isDeterministicAllowingTopKFilter` are
deliberately kept, because ClickHouse#114659 works in this area.
Also drops a dead `std::erase(outputs, filter_node)`: `addFunction` reaches
`addNode`, which appends only to `inputs` and only for INPUT nodes, so a
freshly built node cannot be among the cloned DAG's outputs.
Internal second-model reviewReviewed cold against the resulting code, then adjudicated with the measurements. Six rounds; the last ❌ Blocker, fixed. A stateful predicate sharing the conjunction saw a block the threshold filter ❌ Blocker, fixed.
💡 Noted, not changed. The stateful guard is unconditional, so it also declines when Category is |
|
Workflow [PR], commit [1fa6480] Summary: ❌
AI ReviewSummaryThis PR moves dynamic TopN filter installation into a later pass so Findings
Tests
Final Verdict
LLVM Coverage ReportMeasured on commit 1fa6480.
Changed lines: Changed C/C++ lines covered: 129/134 (96.27%) · Uncovered code |
|
cc @antaljanosbenjamin @davenger, could you review this? |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes24 object files changed (+105.37 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units151 translation units recompiled, 1527 s compile time in total, 151 of them have a recent master baseline. |
`03711_top_k_by_skip_index` compared the whole `EXPLAIN actions = 1` text of the merged PREWHERE root against its reference. That text is analyzer-specific: the analyzer qualifies the promoted column as `__table1.v2` and types the constant as `0_UInt8`, where the old analyzer prints `v2` and `0`. The reference could therefore never pass on the `old analyzer` lane, and it failed 3 of 3 reruns there. The optimization itself works under both analyzers, both producing `and(__topKFilter(v1), greater(...))`, so rather than pinning the analyzer the assertion now counts the two plan lines with patterns that stop before the predicate's operands. Both analyzers find the merged root and the `__topKFilter` function once each. With `use_top_k_dynamic_filtering = 0` neither is found, and with prewhere promotion off only the function is, so the pattern discriminates the sharing rather than the filter's mere presence. `query_plan_remove_unused_columns` is no longer pinned. It was pinned only to keep the printed action positions stable, and no position is asserted any more. The test runner randomizes it, and both of its values pass on both analyzers.
…-deterministic
The stateful check alone was too narrow. `blockSize` reports the row count of the block it
is evaluated on and `rand` draws per call, yet neither is stateful, so both passed the guard
and were merged behind `__topKFilter`. The split reader then evaluated them on the block the
threshold filter had already reduced, which is the same reordering the stateful check exists
to prevent, and it changes the rows the query returns.
Measured on a 2,000,245-row table keyed by `intHash32(k)`, `max_threads = 1`, repeated with
no spread:
SELECT k FROM t PREWHERE blockSize() > 100 ORDER BY k DESC LIMIT 10
returned the true top 10 at `use_top_k_dynamic_filtering = 0` and dropped the largest key at
1 before this change, and the same rows at both values after it. Setting
`enable_multiple_prewhere_read_steps = 0` restored the setting-off result on the old binary,
which locates the divergence in the read-step split rather than in the threshold itself. The
divergence needs a read order unrelated to the sort column and enough rows for the threshold
to cut inside a block: 100,000 rows reproduce it, a single block does not.
`hasNonDeterministic` is the predicate three existing sites pair with `hasStatefulFunctions`
for the same reason (`useDataParallelAggregation.cpp:85`, `StorageDistributed.cpp:636`,
`KeyCondition.cpp:2090`). It does not cost the common `PREWHERE ts > now() - 3600` shape: the
plan carries a folded literal there, so no non-deterministic node reaches the read's actions.
`05059` gains the plan assertion and a row comparison for the new case. Both discriminate: on
the previous binary the filter is installed and the rows differ.
…ed on Sharing an existing PREWHERE with the threshold filter moved the "no dynamic filtering here" decision from `tryOptimizeTopK` to `installTopKDynamicFilter`, which runs last. `applyParallelReplicas` runs in between and keeps every read carrying a TopK stamp local, because `__topKFilter` cannot be serialized into a shipped fragment. A read whose PREWHERE the installer then refuses - a stateful or otherwise block-dependent condition - therefore ended up with neither the threshold filter nor plan-based parallel replicas. `PREWHERE rand() % 4 = 0 ORDER BY k LIMIT 10` on a 200k-row table, plan-based parallel replicas enabled: the plan lost `ReadFromParallelReplicas` and gained no `__topKFilter`, while the same query with `use_top_k_dynamic_filtering = 0` (what master does for this shape) kept the distributed read. An explicit PREWHERE is already visible in the first pass, so the check runs there as well and the read is not stamped at all. The one in the installer stays for a PREWHERE promoted after the stamp; `MergeTreeWhereOptimizer` does not move stateful or non-deterministic conditions today, which is why the early check covers every reachable case. A PREWHERE the filter does share still keeps its read local, which is the existing trade.
`optimize_prewhere_after_pushdown` is off by default, so when a read already has a PREWHERE the `WHERE` is left as a filter step above it. Sharing the PREWHERE with the threshold filter therefore put the filter underneath that step, and a condition there whose value depends on the block it is evaluated on - such as `blockSize` or `rowNumberInBlock` - is handed the blocks the read already shrank. `PREWHERE pred < 9 WHERE blockSize() > 100 ORDER BY k LIMIT 20` over 100k rows: with `use_top_k_dynamic_filtering = 0` the query returns `[0,1,2,3,4,5,6,7,8,10,...]`, with 1 it returned `[1,2,3,5,6,8,11,...]`. Master returns the first list either way, because it never installs the filter when a PREWHERE is present. The check covers the filter step for the same reason it covers the PREWHERE, so a block-dependent `WHERE` without a PREWHERE - which master does filter underneath, with the same row difference - is now refused too. A deterministic `WHERE` still gets the filter, and a non-deterministic expression above the read is unaffected: `query_plan_execute_functions_after_sorting` evaluates it after the sort, on the LIMIT's own block.
`hasNonDeterministic` means non-deterministic across queries, which is not the property that matters here: `today` and `currentUser` return one value for the whole query, so filtering underneath them changes nothing, yet the guard refused them and `PREWHERE d >= today() - 7 ORDER BY k LIMIT 10` lost the optimization this pull request is about. `isDeterministicInScopeOfQuery` is the existing distinction - filter pushdown already uses it to decide whether a condition may be moved relative to other filters - and it still classifies `rand` and `blockSize` as block-dependent. The sort expression below the sort is handed the read's blocks as well, so it gets the same check. A stateful function there decides the order inside the tie group the LIMIT cuts through: with `ORDER BY grp, rowNumberInBlock() LIMIT 20` over 100k rows both settings returned a stable but different row set. A non-deterministic one cannot be pinned that way - with `blockSize` in the sort key all five repeats differ at either setting - so only the stateful case is a result change, and both are refused by one predicate.
The pre-push gate flagged it as restating the commit message: the cross-file note about filter pushdown using the same distinction belongs there, not next to the predicate.
|
Pushed
Two residuals I left alone and would rather have visible:
|
5b75678
|
@fm4v, as requested above, could you add |
|
@groeneai @shankar-iyer @fm4v — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
…EWHERE it will execute Since #117968, `installTopKDynamicFilter` merges `__topKFilter` into the read's PREWHERE at the end of the second optimization pass. Projection candidate analysis runs before that, so it probed the cache under the PREWHERE without the filter, while the executed read writes its TopK-salted entries under `and(__topKFilter, ...)`. The keys never met and a warm projection-backed TopK query never reused the granules, which `05053_query_condition_cache_topk_projection_warm_reuse` caught on every job. Extract the construction of that PREWHERE into `buildTopKDynamicFilterPrewhere` and use it both in `installTopKDynamicFilter` and in `filterPartsByQueryConditionCache` for a read whose dynamic filter is still pending, so both sides derive the same condition hash. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114659&sha=0be6c373974069050a6655298ed4d33ee9cd02e2&name_0=PR
`Targeting.get_changed_tests()` appended a bare `.` to a test's base name, commented "precisely match this test only", and that value became a positional argument of `clickhouse-test`. Those arguments are regexes and `TestSuite.get_selected_tests` searches them against the suite file name including its extension, so the unescaped, unanchored `.` also matched `<name>_<anything>`: every test whose name is a prefix of a sibling's dragged its siblings into the job. A flaky check then spent its 50 repetitions, its `--jobs nproc-1` workers and its `--max-failures 5` budget on tests the pull request never touched, and could report the PR red for one of them (`03711_top_k_by_skip_index_handle_ties`, killed at 600 s on ClickHouse#117968, which had changed only `03711_top_k_by_skip_index.sql`). Over the suite, 320 of 15,646 base names selected more than one test, worst case 22. The conversion to an exact-filename selector happens at the one boundary where the value becomes a `clickhouse-test` argv word, not in the producers, because `get_changed_tests()`'s output is also consumed as a *name*: the targeted AST fuzzer's `Path(test).stem` lookup would miss every changed query, and the coverage dedup key and selection manifest would record one test twice. One site also covers the targeted check's previously-failed and coverage arms. `run_tests` hands one bash command string to `Shell.run`, so the selectors are `shlex.quote`d there. That half is load-bearing, not decoration: bash quote removal deletes the backslash of an unquoted word, so escaping alone produces a pattern byte-identical to the old one at the point of use. With the anchored form the two halves are welded, since `(` and `)` make an unquoted join a bash syntax error rather than a silent reversion. The extension alternation is built from `_TEST_FILE_EXTENSIONS` instead of spelling `.sql`, which would select nothing for `.sh`, `.sql.j2`, `.py` and `.expect` tests, and `$` keeps `.sql` from shadowing `.sql.j2`. Measured over the whole suite: 320 over-selecting names become 0, no name selects 0 (a selector matching nothing makes the job exit 1), and all five extensions still select their own test. A hand-written `--test` keeps loose matching. Co-Authored-By: Claude Opus 5 <[email protected]>
|
@fm4v @shankar-iyer There is a lot of slop in this PR, making the codebase less maintainable in future. Did anyone truly review this? |
|
That slop is mine. I will open one follow-up PR with no behavior change that cuts the comments to local invariants, deletes the code this PR left unreachable, and shrinks the tests and removes their references to C++ internals. |
|
The follow-up is #122671: it cuts the comments to local invariants and shrinks the tests, but deletes no code, because I could not prove any of it unreachable. |
Master's ClickHouse#114659 and ClickHouse#117968 added the `allow_top_k_prewhere_query_condition_cache` parameter and the pending-TopK `prewhere_info_for_cache` to `filterPartsByQueryConditionCache`, which the textual merge spliced into the extracted `canFilterPartsByQueryConditionCache`, so it did not compile. Resolved by keeping master's `filterPartsByQueryConditionCache` behind the eligibility helper, which now counts a pending TopK filter as a PREWHERE, and by keeping TopK reads out of the refresh in `updatePrewhereInfo`, whose probe does not carry the post-PREWHERE filter that a TopK PREWHERE entry is keyed on. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A follow-up to ClickHouse#117968 with no behavior change, asked for in ClickHouse#117968 (comment) The `src/` diff is comment-only: with comments stripped, all six files are token-for-token identical to master. The comments ClickHouse#117968 added are cut to local invariants (60 lines to 24). The design notes they carried: - `installTopKDynamicFilter` runs after `optimizePrewhere`, after projection replacement and after `optimizeReadInOrder`: each changes the PREWHERE the filter joins, and reading in order decides whether it is added at all. - A block-dependent PREWHERE is refused in `tryOptimizeTopK`, before the read is stamped: `applyParallelReplicas` runs before the install and keeps a stamped read local, so a refusal only at install time lost plan-based parallel replicas and added no filter (81a8069). - The conjunction is built inside the cloned PREWHERE DAG. Building it apart and folding it in with `ActionsDAG::mergeNodes` binds it to any existing node under the generated column's name, which returned wrong results for a stored `__topKFilter(k)` column (73ecf4a). - The conjunction stays flat with the threshold filter first: `MergeTreeSplitPrewhereIntoReadSteps` turns the direct children of the root `and` into read steps, in order, so a nested `and` would collapse a multi-condition PREWHERE into one step, and the threshold filter reads only the sort column. - `dynamic_filter_pending` lives in `TopKFilterInfo`, not in `ReadFromMergeTree`, because a plan can be cloned between the pass that sets it and the pass that installs, and the clone carries `top_k_filter_info` over. The clone copies it instead of calling `setTopKColumn` because `condition_hash` already has the part-set salt folded in. - The re-entrancy check in `tryOptimizeTopK` exists because a second run would install a second `__topKFilter` and fold the salt into `condition_hash` twice. - `createInternalFunctionTopKFilterResolver` is used instead of `FunctionFactory::get` because the resolver needs the threshold tracker, and `updatePrewhereInfo` rebuilds the read's header, hence the converting step after the install. No code is deleted. Two comments claimed that `__topKFilter` cannot reach the WHERE `filter_actions_dag` (the stripping in `getTopKReusePredicateOnlyConditionHash`, and `isDeterministicAllowingTopKFilter` in `selectRangesToRead`). That is not shown: projection candidates build a new `filter_actions_dag` from the read's current PREWHERE (`QueryDAG::build`), and a plan optimized twice (`StorageMerge` child plans, set subplans) re-runs projection analysis over a PREWHERE that already holds `__topKFilter`. So both stay, and only the two comments are removed. The second `dependsOnItsBlock` check in `buildTopKDynamicFilterPrewhere` stays too: it covers a PREWHERE promoted after the read was stamped. Tests: `05059_top_k_dynamic_filter_shares_prewhere` goes from 365 to 155 lines and its reference from 43 to 28 lines (old lines 4 7 8 9 12-21 23-25 29-34 36 37 40 42 43, in order). Every kept query is unchanged up to whitespace. Dropped: EXPLAIN checks implied by a kept one (explicit PREWHERE, single condition, promoted WHERE, projection has the filter, unsorted projection with PREWHERE, the two partial-projection fixtures and the full-coverage count), sensitivity controls whose job a kept positive control does (`pred < 1`, `optimize_use_projections = 0` and filter-off on the unsorted projection), and result pairs covered by kept ones (`PREWHERE pred = 3`, `rowNumberInBlock`, lazy materialization with the filter off). Every refusal keeps a positive control on the same table. In 03711, 04539, 04628 and 04838 only the comment lines ClickHouse#117968 wrote change, and none of the test comments ClickHouse#117968 wrote names C++ internals any more. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #115573
Closes: #122435
Related: #114639
Related: #110862
Related: #110883
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
With
use_top_k_dynamic_filtering = 1(the default), aSELECT ... ORDER BY ... LIMIT ncould read far more data than with the setting off: the internal__topKFiltertook over the read's PREWHERE slot and displaced the query's own condition, and an explicitPREWHEREdisabled the feature outright. The threshold filter now shares PREWHERE with the other conditions and takes the first slot. It is also no longer installed on a read that a sorting projection already delivers inORDER BYorder, where it forced a full scan.Description
tryOptimizeTopKbuilt aPrewhereInfoholding only__topKFilterand installed it in the firstpass, so an explicit
PREWHEREdisabled the feature and a plainWHEREhad nowhere to go:optimizePrewhereruns in the second pass and needs the filter's child to be the source step, so thepredicate stayed in a
Filterabove the read.Analysis and the TopK stamp stay in the first pass, which index analysis and the
query-condition-cache gate need. The install becomes a second-pass step that merges
__topKFilterinto the existing conjunction instead of replacing it. Conjunct order is read-steporder and the threshold filter reads only the sort key, so it takes the first slot. Running last also
means the read is final, so the suppression guard can ask the read for the order it chose instead of
predicting it from the base table's sorting key, which cannot see a sorting projection. That repairs the
linked pre-existing full scan; my linked open PR sharpens the prediction instead and is now
redundant, left open for you.
Three things I did not fix, all measured. The first slot costs where the predicate matches almost
nothing: the threshold never gets set,
__topKFilterstays constant-true, and the extra read stepreads 16% more than master on an explicit
PREWHERE. A plainWHEREis not improved either:master already got that benefit by accident, leaving the predicate above the read; the two now plan
alike, which is the point. The sorting-key prediction is still consulted first, so a read served by a
differently sorted projection stays suppressed even when it is not in order, as before. And the merged root is non-deterministic, so the PREWHERE query-condition-cache entry is no
longer written when the skip-index arm is inactive; #114659 adds the salted write.
Compressed bytes read, 2M ClickBench-shaped rows,
max_threads = 1, 3 repeats per cell, zero spreadOne binary pair: pristine master at this PR's own base, and this PR. Absolute bytes depend on the
fixture seeding, so compare the ratios; a deterministic reseeding reproduced the
PREWHERE sp != ''gain as -39.2% against the -35.0% here.
ORDER BY et LIMIT 10PREWHERE sp != ''WHERE sp != ''PREWHERE url LIKE, 0 rows matchWHERE url LIKE, 0 rows matchRead served by a projection sorted by the
ORDER BYcolumn,ORDER BY s ASC, id ASC LIMIT 10:WHERE a < 1000000PREWHERE a < 1000000A read served by an unsorted normal projection is byte-identical on both arms and still splits into
two PREWHERE read steps.
03711_top_k_by_skip_indexpinned the displaced shape, so its reference nowshows the merged conjunction.
Workflow [PR]
Sync PR [sync-upstream/pr/117968]
Version info
26.10.1.760-master(included in26.10and later)