Skip to content

Trim the comments and tests of TopN dynamic filtering over PREWHERE - #122671

Merged
fm4v merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/topk-prewhere-cleanup
Sep 30, 2026
Merged

fm4v merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/topk-prewhere-cleanup

Conversation

@groeneai

@groeneai groeneai commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117968

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Description

A follow-up to #117968 with no behavior change, as promised in #117968 (comment).

  • src/: the comments Let TopN dynamic filtering share PREWHERE, with __topKFilter first #117968 added are cut to the invariants a reader needs at that spot (60 lines to 24). Design history, refuted alternatives and cross-file explanations are gone. The src/ diff is comment-only: with comments stripped, all six files are token-for-token identical to master.
  • No code is deleted. I could not show that __topKFilter never reaches getTopKReusePredicateOnlyConditionHash or the determinism check in selectRangesToRead (a plan that is optimized twice can re-run projection analysis over a PREWHERE that already holds it), so both stay, and only the comments claiming it are removed.
  • Tests: 05059_top_k_dynamic_filter_shares_prewhere goes from 365 to 155 lines. It keeps one on/off result comparison per behavior and the EXPLAIN checks that show whether the filter is added. Every kept query and reference line is unchanged. The test comments Let TopN dynamic filtering share PREWHERE, with __topKFilter first #117968 wrote in 03711, 04539, 04628, 04838 and 05059 no longer name C++ internals.

Validation: the five tests pass with randomized settings (05059 50 times, the others 10 times each). The old and the new 05059 both pass on this build and on a master build. With use_top_k_dynamic_filtering = 0, exactly the six checks that show the filter is added flip.


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

Version info

  • Merged into: 26.10.1.1069-master (included in 26.10 and later)

groeneai and others added 2 commits September 28, 2026 11:38
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]>
Start the TopK comment in ReadFromMergeTree::clone with "Carry over the TopK marker", so the next comment's "for the same reason" refers to it again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-human PR origin: human review feedback on a groeneai PR labels Sep 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-publication review: no findings from an independent model, two nits from my own review, both fixed
  • 💡 AGREE, fixed @ 841692e: the TopK comment in ReadFromMergeTree::clone no longer gave the next comment's "for the same reason" its premise.
  • 💡 AGREE, fixed: the validation sentence of the description was imprecise.

Session id: cron:clickhouse-review-slot-11:20260928-114100

@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [841692e]

Summary: ✅


AI Review

Summary

This PR trims comments in the TopK/PREWHERE implementation and removes a large amount of test scaffolding from 05059_top_k_dynamic_filter_shares_prewhere. The source changes are comment-only, but I do not think the test reduction preserves all of the original proof surface: the surviving EXPLAIN coverage no longer directly exercises the single-condition explicit-PREWHERE branch, which is still a distinct code path in the optimizer.

Tests
  • ⚠️ [tests/queries/0_stateless/05059_top_k_dynamic_filter_shares_prewhere.sql:23] The trimmed file keeps only the explicit-PREWHERE conjunction case (pred = 3 AND tag = 't2'). buildTopKDynamicFilterPrewhere still handles a lone predicate differently from an existing and, and the removed PREWHERE pred = 3 EXPLAIN was the only direct assertion of that branch. The remaining suite still checks plain WHERE promotion elsewhere and QCC behavior for PREWHERE, but it no longer proves that a single-condition PREWHERE still gets __topKFilter merged in the right shape. Please keep one focused EXPLAIN for the lone-PREWHERE case.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: restore one explicit single-condition PREWHERE shape check in 05059 (or an equivalent focused stateless test) so the reduced suite still covers both buildTopKDynamicFilterPrewhere branches.

LLVM Coverage Report

Measured on commit 841692e.

Metric Baseline Current Δ
Lines 87.90% 87.90% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 46/48 (95.83%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 28, 2026
SELECT count() > 0 FROM (
EXPLAIN actions = 1
SELECT k FROM t_topk_prewhere PREWHERE pred = 3 AND tag = 't2' ORDER BY k LIMIT 10)
SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT k FROM t_topk_prewhere PREWHERE pred = 3 AND tag = 't2' ORDER BY k LIMIT 10)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The reduced test only exercises the explicit-PREWHERE conjunction case (pred = 3 AND tag = 't2'), but buildTopKDynamicFilterPrewhere still has a separate branch for a lone predicate versus an existing and. The removed PREWHERE pred = 3 EXPLAIN was the only direct check of that single-condition path: the surviving WHERE coverage lives in 03711, and the other PREWHERE TopK tests assert QCC behavior rather than __topKFilter placement. If the lone-PREWHERE branch stopped sharing __topKFilter with the existing condition, the rows would still be the same and this trimmed file would stay green. I think we should keep one focused EXPLAIN for PREWHERE pred = 3 ORDER BY k LIMIT 10.

@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 28, 2026
@fm4v
fm4v added this pull request to the merge queue Sep 30, 2026
Merged via the queue into ClickHouse:master with commit 09baa85 Sep 30, 2026
294 of 295 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 30, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

It is not caused by this PR: its src/ changes are comment-only, and the failing comparison (ORDER BY grp, rowNumberInBlock() LIMIT 20, filter off vs on) is unchanged from #117968.

It is a test defect. ORDER BY grp, rowNumberInBlock() is not a total order, and with s3 storage the table is read in 2 streams, so which tied rows survive LIMIT 20 depends on thread timing. The TopK filter is not installed for this query (EXPLAIN), and on an S3-backed table with the thread fuzzer the comparison fails as often with the filter off in both arms (18/150) as off vs on (14/150).

The fix pins that comparison to one stream (max_threads = 1). I'll post the PR here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

I opened the fix in #123123: it adds max_threads = 1 to both arms of that comparison, as described above.

@rschu1ze

rschu1ze commented Nov 9, 2026

Copy link
Copy Markdown
Member

I opened the fix in #123123: it adds max_threads = 1 to both arms of that comparison, as described above.

@groeneai Stop using the term arm "arm". An "arm" either refers to a body part or to military equipment for killing people. Instead of "arm", use terms "variant", "path", "lane" etc. depending on the context. Add this to your memory.

@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

Noted and recorded in my memory; from now on I will say "variant", "path" or "case" instead.

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-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... groeneai-origin-review-human PR origin: human review feedback on a groeneai PR pr-not-for-changelog This PR should not be mentioned in the changelog 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.

5 participants