Skip to content

Disable TopK dynamic filtering when a sorting projection makes the read in-order - #110883

Open
groeneai wants to merge 27 commits into
ClickHouse:masterfrom
groeneai:topk-dynamic-filter-projection-in-order
Open

groeneai wants to merge 27 commits into
ClickHouse:masterfrom
groeneai:topk-dynamic-filter-projection-in-order

Conversation

@groeneai

@groeneai groeneai commented Jul 17, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed a performance regression where use_top_k_dynamic_filtering installed a redundant __topKFilter prewhere on an ORDER BY ... LIMIT read that a sorting projection already serves in order. The threshold can only reject rows the read order has already delivered, so it was evaluated per row for nothing, and carrying it also suppressed the LIMIT-based read bound, so the read scanned far past the rows the query asked for. Closes #110862.

Description

Closes: #110862

A read already ordered by the top-k sort column delivers the rows the LIMIT wants first, so the threshold prewhere can only reject rows the read order has already delivered: pure overhead, evaluated per row and pulling the sort column through a separate prewhere reader. On the reproducer in #110862 that doubles the rows read, 256 to 512. Master recognised only the base table's sorting key, so a read served in order by a sorting projection kept the filter.

This PR's first version predicted the projection choice from metadata; I withdrew it as unsound. The chooser ranks candidates by sum_marks and a useful sort order only breaks ties at equal cost, so a cheaper non-ordering projection wins and the predictor suppressed the filter on a read that was not in order (measured: 129 marks beat 1929). The decision now happens where the answer is known: ReadFromMergeTree::requestReadingInOrder drops the prewhere when it makes the read in order, if that prewhere computes nothing but the top-k filter on the column the read is now ordered by. The header is compared before committing, so an unexpected plan shape keeps the filter.

Dropping the filter alone does not recover the read, as a review round found: the in-order hard bound is zeroed for any read carrying a filter, before this branch runs, so the read stayed unbounded and stopped only on cancellation. It is rebuilt now from the limit the caller already passes, giving the state an unfiltered read of the same query carries anyway. SELECT id FROM t ORDER BY score, id LIMIT n over a matching sorting projection went from 62528 rows read at every n to 192/448/960/960 for n in {100, 200, 500, 900}, matching the mechanism-off run exactly.

Scope: a prewhere also carrying a user WHERE/PREWHERE or a row policy is an and(...) and is left alone, as on master. Answers are unchanged with dynamic filtering on and off.


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

…ad in-order

optimizeTopK disables use_top_k_dynamic_filtering when the ORDER BY column is a
prefix of the read's sorted order, because the dynamic prewhere filter is
counterproductive there (once the threshold stabilizes it rejects all remaining
rows in sorted order, defeating the early LIMIT cancellation and forcing a full
scan).

The guard only checked the base table's sorting key, so when a sorting
projection whose ORDER BY differs from the base table serves the read in-order,
a redundant __topKFilter prewhere was still installed on top of the projection
read, re-reading the sort column that in-order reading already provides.

tryOptimizeTopK runs in the first plan pass, before projection selection and
read-in-order (both second pass), so the guard is predictive: it now also
disables dynamic filtering when a normal sorting projection whose ORDER BY
starts with the sort column and which stores every read column is available and
projection optimization is enabled.

Closes: ClickHouse#110862

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The issue's exact repro (ORDER BY score, id LIMIT 10 SETTINGS use_top_k_dynamic_filtering=1 over a table with a (score, id) sorting projection): SELECT count()>0 FROM (EXPLAIN projections=1,actions=1 ...) WHERE explain ILIKE '%__topKFilter%' returns 1 before the fix, 0 after.
b Root cause explained? optimizeTopK's read-in-order guard compared sort_column_name against the base table's sorting key only. When a sorting projection whose ORDER BY starts with the sort column serves the read (ReadType: InOrder), the guard never matched, so use_top_k_dynamic_filtering stayed enabled and a redundant __topKFilter prewhere was installed on the projection read, re-reading the sort column that in-order reading already provided (SelectedRows 512 vs 256 in the issue).
c Fix matches root cause? Yes. The guard now also disables dynamic filtering when a normal sorting projection whose ORDER BY starts with the sort column and which stores every read column is available (and projection optimization is enabled) — the exact predictive condition under which the read later becomes in-order via that projection.
d Test intent preserved / new tests added? New test 04545_top_k_dynamic_filter_projection_in_order asserts no __topKFilter when a projection serves the read in-order, that the projection is still selected and the read stays InOrder, and that dynamic filtering is STILL applied when no projection can serve the order.
e Both directions demonstrated? Yes, on Build-ID-verified binaries: pristine 5bed6dd… → repro reports 1; fixed 14855b6… → reports 0, results identical, InOrder preserved.
f Fix is general across code paths? The guard is the single decision point for TopK dynamic filtering. The predictive check runs in the first pass (before projection/read-in-order); it iterates all normal projections, not just one. It does not touch the symmetric skip-index path, which has its own independent gating.
g Fix generalizes across inputs? Verified the fix does NOT over-disable: with no projection, or a projection that does not cover all read columns, or whose ORDER BY prefix differs, dynamic filtering still fires. Aggregate projections and projections not starting with the sort column are correctly ignored.
h Backward compatible? Yes. Pure planner optimization change; no setting default, on-disk/wire format, or metadata change. Behavior is only recoverable-equivalent (removes redundant work); results are unchanged.
i Invariants and contracts preserved? Yes. Results are byte-identical (verified). The projection is still selected and the read stays InOrder; only the redundant prewhere is dropped. Existing top_k suite (25 tests) and projection-plan tests pass.

Session id: cron:clickhouse-worker-slot-1:20260717-141200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @shankar-iyer — as offered on #110862. This makes optimizeTopK's read-in-order guard projection-aware: when a sorting projection whose ORDER BY starts with the sort column serves the read in-order, use_top_k_dynamic_filtering is now disabled so the redundant __topKFilter prewhere is no longer installed on top of the projection read.

@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b05ea01]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb

AI Review

Summary

This PR moves the TopK dynamic-filter suppression to ReadFromMergeTree::requestReadingInOrder, so the filter is removed only after the read is actually known to be in order, and it restores the hard in-order bound when that drop removes the last filter. The new 04545_top_k_dynamic_filter_projection_in_order coverage exercises the previously reported projection-selection, partial-materialization, drift, and bound-restoration cases. I did not find any remaining correctness, safety, or coverage issue in the current head.

Final Verdict

✅ Approve.

LLVM Coverage Report

Measured on commit b05ea01.

Metric Baseline Current Δ
Lines 88.90% 89.00% +0.10%
Functions 91.70% 91.70% +0.00%
Branches 81.30% 81.40% +0.10%

Changed lines: Changed C/C++ lines covered: 36/38 (94.74%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 17, 2026
…case

The projection branch of readWouldBeInOrderForColumn returned true as soon as
a normal sorting projection with the same leading sort key and all read columns
existed. The second-pass chooser (optimizeUseNormalProjections) applies extra
gates before it actually selects a projection, so the guard could disable
use_top_k_dynamic_filtering on queries that still read the base table,
reintroducing the redundant read the __topKFilter avoids.

Mirror the chooser's metadata-evaluable rejections and stay conservative:
- respect preferred_optimize_projection_name (only that projection is considered);
- skip projections with their own WHERE (needs a query-filter implication we
  cannot check in the first pass);
- do not trust the projection path when a query filter is present, since the
  chooser may keep the cheaper filtered base read and reject the projection on
  cost (sum_marks > parent_reading_marks).

Extends test 04545 with a filtered query and a pinned non-matching projection,
asserting __topKFilter stays present when the projection is not selected.

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

Copy link
Copy Markdown
Collaborator Author

Good catch. Tightened readWouldBeInOrderForColumn in a7aa62c so the projection branch only fires when the projection is reliably selected, mirroring the second-pass chooser's metadata-evaluable rejections:

  • honours preferred_optimize_projection_name (when set, only that projection is considered, same as the chooser);
  • skips projections with their own WHERE (the chooser needs the query filter to imply it, which is unknowable in the first pass);
  • does not trust the projection path when there is a query filter below the sort. That is the only case where the chooser rejects the projection on cost (sum_marks > parent_reading_marks), which happens precisely when a filter lets the base table prune cheaper. Without a filter the sorting projection is not rejected on cost, so predicting in-order is safe.

The predictor stays conservative: when unsure it returns false, leaving dynamic filtering on for a base-table read.

Verified on Build-ID-checked binaries with EXPLAIN projections=1, actions=1:

  • filtered query WHERE k=7 ORDER BY score, id LIMIT 10 with a (score,id) projection present: __topKFilter was wrongly dropped before, now retained; top-k result byte-identical to use_top_k_dynamic_filtering=0.
  • preferred_optimize_projection_name pinned to a non-matching (k,score) projection: __topKFilter retained.
  • original no-filter case where p_score serves the order: __topKFilter still absent, projection still selected InOrder.

Added both regression cases to 04545.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (updated for a7aa62c)
# Question Answer
a Deterministic repro? Yes. EXPLAIN projections=1, actions=1 SELECT id, cityHash64(payload) FROM t WHERE k=7 ORDER BY score, id LIMIT 10 SETTINGS optimize_read_in_order=1, optimize_use_projections=1, use_top_k_dynamic_filtering=1, query_plan_max_limit_for_top_k_optimization=100 over a table with a (score,id) projection: SELECT count()>0 ... WHERE explain ILIKE '%__topKFilter%' returns 0 on the pre-tightening binary (filter wrongly dropped), 1 after. Same for a query pinned to a non-matching projection via preferred_optimize_projection_name.
b Root cause explained? readWouldBeInOrderForColumn predicted the read would be in-order as soon as a matching normal sorting projection merely existed. But TopK runs in the first plan pass; the projection chooser (optimizeUseNormalProjections) runs in the second pass and applies further gates (preferred-name filter, projection-WHERE implication, cost sum_marks <= parent_reading_marks). So a table that merely has a matching projection could lose __topKFilter even when the chooser keeps the cheaper base-table read, reintroducing the redundant read this optimization removes.
c Fix matches root cause? Yes. The predictor now mirrors the chooser's metadata-evaluable rejections and stays conservative (returns false when unsure): honours preferred_optimize_projection_name, skips projections with their own WHERE, and does not trust the projection path when a query filter is present (the only case where the projection is rejected on cost).
d Test intent preserved / new tests added? Preserved. 04545 extended with two cases: a filtered query where the projection is not selected, and a pinned non-matching projection; both assert __topKFilter remains. Original in-order case (no filter) still asserts 0.
e Both directions demonstrated? Yes, Build-ID-verified. Pristine b83a8ad…: filter case and preferred case both report 0 (bug). Fixed e148398…: both report 1, original case still 0, filtered top-k result byte-identical to use_top_k_dynamic_filtering=0.
f Fix is general across code paths? The guard is the single TopK decision point. The predictor iterates all normal projections; the skip-index path has its own independent gating, untouched.
g Fix generalizes across inputs? Verified the tightening does not over-disable (filtered/pinned/partial-WHERE cases keep the filter) and does not over-enable (no-filter in-order case still drops it). Aggregate projections and non-prefix-matching sort keys remain ignored.
h Backward compatible? Yes. Pure planner optimization; no setting default, on-disk/wire/metadata change. Results unchanged.
i Invariants and contracts preserved? Yes. Results byte-identical. When the projection is selected the read stays InOrder and only the redundant prewhere is dropped; when it is not selected the base read keeps dynamic filtering.

Session id: cron:clickhouse-worker-slot-7:20260717-163800

@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.10% 86.00% -0.10%
Functions 91.80% 91.80% +0.00%
Branches 78.20% 78.20% +0.00%

Changed lines: Changed C/C++ lines covered: 42/45 (93.33%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a7aa62c

CI fully finished on this head (Config Workflow = SUCCESS, Finish Workflow = SUCCESS; 0 checks queued/in_progress; >20-min ingest buffer elapsed). CIDB shows ZERO failing tests for this commit.

Check / test Reason Owner / fixing PR
(no failing tests) - -
Sync - CH Inc sync (private, not actionable)

All checks green except the private CH Inc sync (exempt). No PR-caused failure.

Session id: cron:our-pr-ci-monitor:20260718-000000

@PedroTadim

Copy link
Copy Markdown
Member

@shankar-iyer can you review this PR soon?

@PedroTadim

Copy link
Copy Markdown
Member

@Michicosun maybe you can review this PR as you are assigned in the issue

Resolves the conflict in optimizeTree.cpp, where master added
optimize_prewhere, remove_unused_columns and read_in_order_through_spilling_join
to Optimization::ExtraSettings while this branch added optimize_projection.
Both sides are kept. The initializer lists are positional and every added
field is bool, so a wrong order would compile and silently swap two settings;
the merged order matches the declaration order in Optimizations.h.
The comments accumulated the review rationale over earlier rounds. Keep only what a
reader needs at each spot and move the reasoning here.

Why the predictor must be conservative: tryOptimizeTopK runs in the first plan pass,
while optimizeUseNormalProjections selects projections in the second. The predictor
therefore cannot observe the chooser's decision and only mirrors the gates that are
knowable from metadata:

  - preferred_optimize_projection_name: when it names an existing projection the
    chooser considers only that one.
  - projection WHERE: a partial projection is chosen only if the query filter implies
    its WHERE, an implication not available in the first pass.
  - cost (sum_marks <= parent_reading_marks): a filter can make the base read cheaper
    than the projection, so with a filter present the selection is not predictable.

A false positive is the expensive direction: it strips dynamic filtering from a read
that still hits the base table, which is the regression this guard was tightened to
avoid.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master (31 days of drift) to resolve the conflict. Now MERGEABLE at 268f4f7.

The only conflict was in optimizeTree.cpp: master added optimize_prewhere,
remove_unused_columns and read_in_order_through_spilling_join to
Optimization::ExtraSettings while this branch added optimize_projection. Both sides kept.
The initializer lists are positional and every added field is bool, so a wrong order would
compile and silently swap two settings; I asserted the order in both lists matches the
declaration order in Optimizations.h. Verified the merged tree differs from master by exactly
this PR's 5 files, with no submodule movement.

Also trimmed the guard comments to the local invariants and moved the chooser-gate reasoning
into the commit message.

Validation on the merged tree: full build clean, 04545 byte-identical to its reference, and
50/50 passes with optimize_read_in_order / optimize_use_projections randomized.

One correction to my earlier reply on this thread, since it claimed more than the code does.
The predictor still diverges from the second-pass chooser in two cases I reproduced on the
merged binary:

  • preferred_optimize_projection_name set to a name that does not exist: the chooser falls
    back to considering all projections (optimizeUseNormalProjection.cpp:389-401 narrows only
    when the name matches), so p_score is selected and the read is InOrder, yet
    __topKFilter is still installed. The original issue reproduces here.
  • A projection that is added but never materialized: no projection is selected and the read is
    not InOrder, but the guard already disabled dynamic filtering, since it reads metadata
    without checking that projection parts exist.

Neither is introduced by this merge; both predate it in this branch. Fixing them properly
means deciding from the selected plan rather than from metadata, which is the redesign your
original comment asked about, so I have not attempted it inside a conflict-resolution push.
Happy to follow up with that as the next change on this PR if you would like it here rather
than separately.

…directions

readWouldBeInOrderForColumn predicts whether the second-pass chooser will make
the read in-order. Two of its candidate gates did not match the gates the
chooser actually applies, so the prediction was wrong in both directions.

Over-pinning: the guard treated any non-empty preferred_optimize_projection_name
as a hard pin, but optimizeUseNormalProjection narrows the candidate set only
when that name matches an existing normal projection, and otherwise keeps all of
them. With a name that matches nothing, the chooser still selected the sorting
projection and read in-order while the guard skipped it and left the redundant
__topKFilter installed, which is the ClickHouse#110862 regression this change exists to
remove.

Over-permitting: the guard accepted a projection from metadata alone, but
analyzeProjectionCandidate drops a candidate when no read part carries a usable
projection part. A projection that was declared and never materialized therefore
suppressed dynamic filtering on a plain base-table read.

Both directions were measured on the guard's own binary before and after, and
the two new test arms redden against the pre-fix build. The part check tests
existence and is_broken; the chooser additionally applies its own
projectionPartHasRequiredColumns, which is file-static, so a projection whose
parts are all column-drifted is still predicted in-order.
The two fallback arms asserted only that __topKFilter was present, so they
stayed green whatever the plan did with the projection. Each now also asserts
the read type, which is the property the guard actually predicts.

Measuring the arms also showed the filtered arm's comment was wrong: with
WHERE k = 7 the chooser does select p_score, it just does not make the read
in-order, so the expected value was right for the wrong stated reason. The
comment now describes what was measured.
Two more divergences between the guard and the second-pass chooser.

The part check used any_of, so one materialized projection part was enough to
predict an in-order read. analyzeProjectionCandidate keeps the parts without a
usable projection part in candidate.parent_parts and still selects the projection
while projection_parts is non-empty, so in a mixed-materialization state
optimizeUseNormalProjections leaves a base-table branch under a UnionStep and
optimizeReadInOrder adds a full SortingStep to it. Dropping __topKFilter there
put that branch back on the full scan this guard exists to avoid. Every read part
must be served instead, and an empty part set is not in order either: the chooser
drops a candidate that would read nothing, which all_of's vacuous truth would
otherwise accept.

The guard also re-derived when a projection is usable at all, and so missed the
chooser's own preconditions. canUseProjectionForReadingStep is exported from
projectionsCommon.h and already covers FINAL, sampled, distributed, unique-key
and unsupported parallel-replica reads, none of which ever reach a projection.
Calling it removes that whole class rather than enumerating the cases; a sampled
read of a fully materialized projection previously lost the filter while its read
type stayed Default.

Measured against the previous head on both new arms, with the earlier arms
re-checked for regressions: mixed materialization and sampled reads went from
filter-absent to filter-present, while the fully materialized, unmaterialized and
non-matching-pin cases are unchanged. Results were identical in every arm, with
and without the filter. The mixed test arm asserts the surviving union branch
rather than the projection name, since the name is present whenever the
projection is selected but the union appears only while a base branch remains.
@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b05ea01b2 with master fc7975b07 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 5c0934adb; 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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ff8685c

CI is fully finished on this head and it is clean. 177 check-runs, 159 success / 17 skipped
(plus Finish Workflow success), 0 failed, 0 cancelled, 0 still running. Config Workflow,
Build profile diff and Finish Workflow all succeeded, and the praktika report is top-level
OK with 0 dropped jobs, so this is real coverage rather than a filtered or void run. CIDB holds
337618 rows across 162 checks for this commit, with 0 in FAIL/ERROR and 0 checks in
failure/error. A recursive walk of the praktika report finds 0 FAIL, 0 ERROR, 0 DROPPED
at any depth, which covers the non-gating per-test rows the check-runs API cannot see.

Check / test Reason Owner / fixing PR
(none) no failures on this head not applicable

The matrix that ran is broad, not a small filtered subset: 44 Stateless tests, 33
Integration tests, 26 Build, 10 Stress test, 7 Unit tests, 6 AST fuzzer, 6
Performance Comparison, 4 BuzzHouse, 3 Bugfix validation, 2 Fast test, plus
Upgrade check, LLVM Coverage, SQLLogic test, SQLStorm test and the packaging checks.

The regression test added here, 04545_top_k_dynamic_filter_projection_in_order, was executed
266 times on this head with 0 failures across 21 checks (1 skipped by tag), and it is present and
passing in both per-arch Bugfix validation (functional tests, amd64) and
Bugfix validation (functional tests, aarch64). Counts come from an aggregate CIDB query over
this commit, not a tally of the job list.

Session id: cron:our-pr-ci-monitor:20260816-010000

Resolves one conflict, in `optimizeTree.cpp`. Master collapsed the two
duplicated `Optimization::ExtraSettings` brace-initializers (first pass and
second pass) into a single `makeExtraSettings()` helper. This branch had added
`optimization_settings.optimize_projection` to both lists; git folded that entry
into the new helper on its own, at the position matching the struct field order
in `Optimizations.h` (after `read_in_order_through_join`, before
`join_swap_table`). The second-pass hunk therefore takes master's side verbatim:
the helper already carries the field, and the initializer is positional, so a
list missing that entry would shift every later value by one.

Net effect on this branch's own change: `optimizeTree.cpp` is +1 instead of +2.
No behaviour change.

`optimizeTopK.cpp` and both test files are byte-identical to the pre-merge head;
`contrib/` and `.gitmodules` are byte-identical to master.

Also aligns `contrib/datasketches-cpp` to the merged pin: master moved it to the
`ClickHouse/datasketches-cpp` fork, whose pinned commit is absent from the old
`apache/` remote the local checkout still named, so `git submodule update` could
not fetch it until the URL was synced from `.gitmodules`.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master again (the base was 7416 commits behind; one conflict, in optimizeTree.cpp, where master collapsed the two duplicated ExtraSettings initializers into makeExtraSettings(), so this branch's added field now lives in the helper and the diff there is +1 instead of +2). No behaviour change from the merge itself.

While re-reviewing the merged tree I measured a second, independent trigger for the over-predict class I described in #110883 (comment), and this one is still present.

readWouldBeInOrderForColumn returns as soon as some projection has a matching sort prefix and stores the read columns. The second-pass chooser instead minimises sum_marks and treats a useful sort order only as an equal-cost tie-breaker (optimizeUseNormalProjection.cpp:639-641). So a strictly cheaper non-ordering projection wins the ranking, the read ends up not in order, and the filter has already been suppressed.

Two materialised projections, one wide and ordering (1929 marks), one narrow and non-ordering (129 marks), parent 1929 marks:

__topKFilter Read type results
this PR absent Default identical
master present Default identical

Results are identical, so this is extra data read rather than wrong answers. Control on the fixture: with index_granularity = 256 and no index_granularity_bytes the two projections have equal marks, the equal-marks tie-breaker then picks the ordering projection, and the read is InOrder with the filter correctly absent. So it is the cost asymmetry that arms this, not merely having a second projection.

Reproducer
CREATE TABLE t_cmp (id UInt64, k UInt64, score UInt64, payload String CODEC(NONE))
ENGINE = MergeTree ORDER BY (k, id)
SETTINGS index_granularity = 8192, index_granularity_bytes = 4096, min_bytes_for_wide_part = 0;

INSERT INTO t_cmp SELECT number, number % 128, sipHash64(number), repeat('x', 200) FROM numbers(32768);
OPTIMIZE TABLE t_cmp FINAL;

ALTER TABLE t_cmp ADD PROJECTION p_wide_ord     (SELECT id, k, score, payload ORDER BY (score, id));
ALTER TABLE t_cmp ADD PROJECTION p_narrow_noord (SELECT id, score ORDER BY (id));
ALTER TABLE t_cmp MATERIALIZE PROJECTION p_wide_ord     SETTINGS mutations_sync = 2;
ALTER TABLE t_cmp MATERIALIZE PROJECTION p_narrow_noord SETTINGS mutations_sync = 2;

SELECT count() > 0 AS has_topk_filter FROM (
    EXPLAIN projections = 1, actions = 1
    SELECT id FROM t_cmp ORDER BY score, id LIMIT 10
    SETTINGS optimize_read_in_order = 1, optimize_use_projections = 1,
             use_top_k_dynamic_filtering = 1, query_plan_max_limit_for_top_k_optimization = 100
) WHERE explain ILIKE '%__topKFilter%';

The first pass has no sum_marks to compare: tryOptimizeTopK is an entry in the first-pass optimization array, while optimizeUseNormalProjections runs in optimizeTreeSecondPass. So the predictor cannot reproduce the chooser's ranking where it currently stands, which is the same second-pass design question as in the comment linked above.

A metadata-only narrowing is available without moving phases: keep the filter whenever another projection also stores all the read columns but its sort order does not match, i.e. whenever a cheaper competitor could exist. That is the conservative direction (master parity), at the cost of not extending the improvement to any table carrying a second projection. I am working on that, and I would rather this PR not be merged until it is resolved, since it carries four must-backport labels.

groeneai and others added 10 commits September 12, 2026 14:13
readWouldBeInOrderForColumn guessed, from projection metadata alone, which read the
second-pass chooser would select. The chooser ranks candidates by sum_marks and treats a
useful sort order as an equal-marks tie-breaker only (optimizeUseNormalProjection.cpp), so a
strictly cheaper non-ordering projection wins: with a 1929-mark ordering projection and a
129-mark non-ordering one over a 1929-mark parent, the read is not in order and the guard had
already switched dynamic filtering off, reading strictly more data than master.

That cannot be repaired by adding gates. The cost the chooser compares is not derivable from
metadata: index_granularity and index_granularity_bytes are per-projection DDL settings
(ALLOWED_PROJECTION_SETTINGS in ProjectionsDescription.cpp), so an ordering projection can be
strictly more expensive than the parent and be rejected on cost no matter how many metadata
gates match; and a candidate's sum_marks is narrowed by top-k granule selection when the
projection's own minmax index matches the sort column, which makes the parent and projection
halves of the comparison incommensurable in the first place.

The next commit takes the decision where the answer is already known instead.

Co-Authored-By: Claude Opus 5 <[email protected]>
Once a read is ordered by the top-k sort column it delivers the rows the LIMIT wants first, so
the dynamic threshold prewhere can only reject rows the sort has already passed, and every
rejected row keeps the pipeline reading instead of letting the LIMIT cancel it. That is the
regression issue ClickHouse#110862 reports: on master both "Read type: InOrder" and a __topKFilter
prewhere appear on the same read.

Which read ends up in order is decided after the filter is installed - tryOptimizeTopK is a
first-pass optimization, while the projection chooser and optimizeReadInOrder both run in the
second pass - so the suppression is done where the answer is already known, in
ReadFromMergeTree::requestReadingInOrder. The function already overrides two earlier decisions
that becoming in-order invalidates (a stranded virtual-row conversion and vertical FINAL), and
it owns both halves of this one: the read's prewhere and the read's order.

Installing the prewhere moves the sort column to the front of the header, because
ActionsDAG::updateHeader emits a DAG's outputs before the pass-through columns. Removing it
therefore reads the columns in the order the prewhere reported them, which reproduces the same
block the steps above were built for, including the converting step tryOptimizeTopK may have
inserted. The candidate header is compared before anything is committed, so an unexpected shape
keeps the filter.

Scope: the filter is dropped only when it is the whole prewhere. A user WHERE or PREWHERE, or a
row policy, is folded into the same DAG under and(...) (QueryDAG::build), and that conjunction
is left alone - removing it would drop the user's predicate. Under a union over a partially
materialized projection the filter is dropped from the ordered projection branch and kept on
the base-table branch, which is where the optimization still pays; the answer comes from the
sort and limit above the union, so it cannot change.

Co-Authored-By: Claude Opus 5 <[email protected]>
The internal top-k threshold function is deliberately absent from
`FunctionFactory`, and `ExternalUserDefinedExecutableFunctionsLoader::createObject`
rejects a UDF name only when `FunctionFactory` or `AggregateFunctionFactory`
already holds it; there is no reserved-prefix check under
`src/Functions/UserDefined/`. A server-configured executable UDF may therefore
be named `__topKFilter`, and for a query that writes such a PREWHERE by hand the
optimizer installs nothing (`tryOptimizeTopK` declines when a prewhere exists)
while the in-order hook would still match the user's function and discard the
user's PREWHERE, returning rows it filtered out.

Match `top_k_filter_info` (the stamp this read carries) instead of trusting the
name alone. No case the fix needs is lost: `tryOptimizeTopK` calls
`setTopKColumn` whenever `use_skip_index || use_dynamic_filtering`, so every read
carrying the optimizer's own dynamic prewhere is stamped, and
`optimizeUseNormalProjection.cpp`'s `copyTopKFilterInfoAndQueryConditionCacheGate`
carries the stamp onto the projection read.

Co-Authored-By: Claude Opus 5 <[email protected]>
…g a constant

Four places in the tree compare a function name against `__topKFilter`. The
constant introduced here was adopted at one of them, which is the worse of the
two consistent shapes: `ReadFromMergeTree.cpp`'s `isDeterministicAllowingTopKFilter`
deliberately mirrors `updateQueryConditionCache.cpp` textually (its own comment
says both gates must agree), and `MergeTreeDataSelectExecutor.cpp` keeps the
literal too. Converting all four is diff churn on a change four release branches
will carry, so match the three that exist.

This reverts `src/Functions/FunctionTopKFilter.{h,cpp}` to their previous state
and leaves the whole change in one file.

Co-Authored-By: Claude Opus 5 <[email protected]>
`InOrder` is only ever printed by `ReadFromMergeTree::describeActions`, which
`QueryPlan::explainPlan` calls only when `ExplainPlanOptions::actions` is set,
and that member defaults to false. The eight arms asserting read order passed
`projections = 1` alone, so they worked only through the `explain_query_plan_default
= pretty` default, whose option set switches `actions` on. Where that default is
not in effect the token is never emitted: the two arms expecting `InOrder`
(`uses_projection_in_order`, `unpinned_in_order`) read 0 and the file fails, and
the six arms expecting no in-order read pass for the wrong reason, including the
`competitor_in_order` control the new arm depends on.

Measured with `--explain_query_plan_default=legacy`: before this commit
reference lines 7 and 15 read 0; after it the whole file matches. Values under
the pretty default are unchanged, so no reference line moves.

Co-Authored-By: Claude Opus 5 <[email protected]>
…tered

When the projection covers only some partitions the plan is a union of a
projection read and a base-table read, and the prewhere is dropped per branch:
the ordered projection child loses it, the base-table child keeps it. A
`count() > 0` over the plan text cannot tell that apart from "every child is
filtered", which is the behaviour this change would be wrong about, so count the
children instead.

Measured on the shipped binary: 1 filtered child, 1 in-order child. With the
removal disabled the filtered count moves to 2 while the in-order count stays 1,
so the arm now fails for the right reason.

Co-Authored-By: Claude Opus 5 <[email protected]>
The column-name check proves the stamp names the matched column, not that the
optimizer installed the prewhere. setTopKColumn fires on
`use_skip_index || use_dynamic_filtering`, and only use_dynamic_filtering carries
the `!getPrewhereInfo()` precondition; use_skip_index needs only
use_skip_indexes_for_top_k (default true) plus a minmax index on the sort column.
So on such a table a query whose own PREWHERE is exactly `__topKFilter(col)` is
stamped, read in order, and had the user's filter erased. The internal function is
not registered in FunctionFactory and nothing reserves the name for executable
UDFs, so that PREWHERE is reachable.

`where_clause` is `filter_step || getPrewhereInfo() || getRowLevelFilter()`,
computed over the same subtree the top-k pass walked (LimitStep -> SortingStep ->
optional ExpressionStep -> optional FilterStep -> ReadFromMergeTree). A prewhere
can only originate from a filter, and a filter above the LimitStep cannot be
pushed below it, so a prewhere present at second-pass time with
`where_clause == false` can only be the one tryOptimizeTopK injected. The
projection read inherits the flag through
copyTopKFilterInfoAndQueryConditionCacheGate, so the union case is covered by the
same clause.

Co-Authored-By: Claude Opus 5 <[email protected]>
`countIf(explain ILIKE '%__topKFilter%')` counted occurrences of the name, and
that count is format-dependent. describeActions prints
`Prewhere filter column: __topKFilter(...)` once per prewhere-carrying read step
in both formats, but when `!format_settings.compact` it also re-prints the whole
prewhere DAG, which names the function again. Legacy (non-pretty) mode is
non-compact, so the arm read 2 there against a reference of 1. Measured on this
head: the old predicate gives 1 under the pretty default and 2 under
`--explain_query_plan_default=legacy`; the new one gives 1 under both.

That matters beyond a local run: `explain_query_plan_default` does not exist
before 26.7, so legacy is the only format on three of this PR's four backport
targets. Pinning the setting inside the test is therefore not an option either;
restricting the count to the per-step line is.

Co-Authored-By: Claude Opus 5 <[email protected]>
…t buy

The comment claimed the threshold prewhere "keeps the pipeline reading instead of
letting the LIMIT cancel it". Measured on two Build-ID-verified binaries, removing
the prewhere does not move `read_rows` at all: where the shape is cheap the number
is identical, and where a large amplification exists it survives the removal
(the skip-index half of the mechanism owns it). What the drop does buy is the
redundancy: an ordered read already delivers the wanted rows first, so the
threshold can only reject rows the read order has passed, and evaluating it per
row plus pulling the sort column through a separate prewhere reader is pure cost.

Co-Authored-By: Claude Opus 5 <[email protected]>
…ted per step

Requiring the `__topKFilter` token on the per-step line still left the arm blind in
non-pretty mode. On the projection child the prewhere column is the ALIAS
`_projection_filter`, so that line never names the function; pretty mode resolves the
alias and prints `__topKFilter(score)`, legacy mode does not. The token then exists
only in the DAG dump, which pretty suppresses. Measured over the whole file on two
Build-ID-verified binaries, pretty then legacy:

  token on the per-step line       fix 1 / 1    removal disabled 2 / 1   blind in legacy
  the same plus `compact = 1`      fix 1 / 1    removal disabled 2 / 1   blind in legacy
  per-step lines, no token         fix 1 / 1    removal disabled 2 / 2   sensitive in both

`in_order_children` holds at 1 in all four runs. The query carries no WHERE, PREWHERE
or row policy, so the only prewhere either child can hold is the injected threshold
filter and the count means what the arm's comment says.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added the groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR label Sep 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

I withdrew the narrowing remedy I announced in this comment. No metadata gate can predict the projection chooser's decision: the chooser ranks by sum_marks and treats a useful sort order as an equal-marks tie-breaker only, index_granularity and index_granularity_bytes are per-projection DDL settings, and a candidate's mark count is itself narrowed by top-k granule selection. The first-pass predictor is gone; the filter is now dropped in ReadFromMergeTree::requestReadingInOrder, where the read order is a fact rather than a guess. Master's base-sorting-key block in optimizeTopK is unchanged. Against master the source change is a single file, ReadFromMergeTree.cpp (+51); against this PR's previous head it is -71 lines, since reverting the predictor removes more than the hook adds.

❌ Blocker, fixed - the read-order assertions used EXPLAIN projections = 1 without actions = 1. Read type: is printed only by describeActions, which runs only under options.actions; that option is false by default and was reaching the tests solely through the explain_query_plan_default = pretty default, which exists on 26.7 and on none of 26.4, 26.5 or 26.6. Two arms would have failed on the backports and six were vacuous. Every read-order EXPLAIN now passes actions = 1, confirmed by running the file under --explain_query_plan_default=legacy.

❌ Blocker, fixed - the helper recognised the internal filter by name, and the stamp I first required is not proof of ownership: setTopKColumn also fires for the skip-index half alone, which does not require an absent PREWHERE. So a table with a minmax index on the sort column plus a user PREWHERE __topKFilter(col) - a legal executable-UDF name, since the internal function is deliberately absent from FunctionFactory and the loader only rejects names that factory holds - would have had the user's filter dropped on an ordered read. The drop now additionally requires !top_k_filter_info->where_clause, which is false exactly when the top-k pass saw no user filter below the LIMIT: that pass walks a fixed Limit / Sorting / optional Expression / optional Filter / ReadFromMergeTree chain and bails on any other shape, and the flag is copied into the replacing projection step rather than recomputed, so wherever the stamp exists the flag describes the same subtree the hook runs on.

❌ Blocker, fixed - the union arm counted occurrences of __topKFilter, which is format-dependent: legacy EXPLAIN prints the prewhere DAG a second time, so the count was 2 against a reference of 1. Legacy is the only format on 26.4, 26.5 and 26.6, so the arm failed on three of the four backport targets. It now counts the per-step Prewhere filter column line, which prints exactly once per prewhere-carrying child in either format. Requiring the function's own name there would reintroduce the same class of bug in mirror image: on the projection child the prewhere column prints under the _projection_filter alias the projection's QueryDAG adds, so legacy never names the function on that line, and a predicate demanding both tokens quietly counts one child where there are two. The query carries no WHERE, PREWHERE or row policy, so the only prewhere either child can hold is the injected one. Measured 1 with the fix and 2 with the removal reverted, in both formats.

⚠️ Claim corrected - my earlier changelog wording said the redundant prewhere prevented LIMIT from cancelling the read early and scanned the whole table. That attribution is wrong, and I had since over-corrected it in the other direction. The large amplification the old wording pointed at survives the prewhere's removal untouched (see the scope note), so it belongs to the mechanism's skip-index half rather than to this filter. What the drop does buy is measurable on the issue's own reproducer, on two binaries: RowsReadByPrewhereReaders 512 to 0 and read_rows 512 to 256, which is the separate prewhere reader over the sort column that the issue itself reported. The entry and the description now claim that and nothing beyond it.

⚠️ Test strength - the partially-materialized-projection arm could not tell "filter on both union children" from "filter on the base child only"; it now counts children, and reverting the removal moves that count from 1 to 2.

💡 Disagreed, with evidence - the competing-projection arm was said to match any analysed candidate rather than the selected one. The recorded EXPLAIN for that arm contains no Projections: section at all: when every part is served from the projection the parent read is replaced outright and never described, so p_narrow_noord can only appear as the selected step's own description. The contrast is visible in the union fixture, where parent parts survive and the candidate list does print.

💡 Declined, and the resulting gap stated plainly - a regression test for the UDF collision above would need a new server-config artifact in the repo declaring an executable function named __topKFilter, which I chose not to add here. It has no SQL substitute: an ordinary user filter makes the prewhere root an and(...), which the helper rejects before the ownership conjunct is ever reached, so every shape I tried scores identically with and without that conjunct. Deleting !top_k_filter_info->where_clause leaves the whole test file green in both formats. That conjunct therefore ships reasoned rather than covered, and the reasoning is in its commit message. Happy to add the config fixture if you would rather have it.

Scope, deliberate. A query that carries a user WHERE/PREWHERE or a row policy is left alone, so the first row of the gaps table in this comment stays open; the second closes by construction. where_clause is also coarser than strictly necessary: it suppresses the drop whenever any user filter existed below the LIMIT, including the case where the prewhere that reaches the hook is still the injected one, so the improvement does not extend to a FilterStep surviving under optimize_move_to_prewhere = 0. That is master's present behaviour, so it costs an optimization and never an answer; the exact alternative is a threshold-tracker identity check, which would mean exporting FunctionTopKFilter from its .cpp, and I kept the diff to one file. The skip-index half (the stamp, the threshold tracker, granule skipping) is untouched, and I measured what that costs: with a sorting projection and LIMIT above one granule, use_top_k_dynamic_filtering = 1 reads 32768 rows where = 0 reads 768, and that split is identical with and without this change, so it is a separate defect of the mechanism rather than of this fix. I am tracking it separately. My open #117968 puts the top-k filter inside a shared prewhere, which is precisely the shape declined here; the two interact by design and whichever merges second owns the follow-up.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. MergeTree ORDER BY (k, id), index_granularity = 8192, index_granularity_bytes = 4096, min_bytes_for_wide_part = 0, 32768 rows with a 200-byte payload, plus p_wide_ord (SELECT id, k, score, payload ORDER BY (score, id)) and p_narrow_noord (SELECT id, score ORDER BY (id)). Marks: parent 1929, p_wide_ord 1929, p_narrow_noord 129. Then EXPLAIN projections = 1, actions = 1 SELECT id FROM t ORDER BY score, id LIMIT 10 SETTINGS optimize_read_in_order = 1, optimize_use_projections = 1, use_top_k_dynamic_filtering = 1, query_plan_max_limit_for_top_k_optimization = 100 shows the same answer on every run. Added as an arm of 04545_top_k_dynamic_filter_projection_in_order.
b Root cause explained? tryOptimizeTopK runs in the FIRST optimization pass; the projection chooser and read-in-order both run in the second. The withdrawn version therefore predicted the second-pass choice from projection metadata. The chooser ranks candidates by sum_marks and lets a useful sort order break ties only between equal-cost candidates, so a cheaper non-ordering projection wins and the read is not in order, while the predictor had already suppressed the filter: strictly more data read than master. The cost is not derivable from metadata at all, since index_granularity and index_granularity_bytes are per-projection settings and a candidate's mark count is narrowed by top-k granule selection.
c Fix matches root cause? Yes. The root cause is that the decision was taken in a pass that cannot see the fact it depends on, so the fix takes it in ReadFromMergeTree::requestReadingInOrder, where the read has just been made in order and the fact exists. No widened bound, no no-random-* tag, no data reduction, no guard at the symptom; the predictor is deleted rather than patched a third time.
d Test intent preserved / new tests added? All 8 pre-existing filter-presence arms of 04545 and every read-order and selected-projection control keep their current expected values, and pass. One scenario is appended (5 rows + 3 assertions). Three oracle repairs were made after review: the eight read-order arms now pass actions = 1, without which InOrder is never printed and they assert nothing (measured with explain_query_plan_default = legacy: two arms read 0 instead of 1 and the rest passed vacuously); the partially materialized union arm now counts the filtered and in-order children (1 and 1) instead of asking whether any child is filtered, which could not distinguish "one child" from "both"; and that count is now taken over the per-step Prewhere filter column lines, because requiring the __topKFilter token made the arm blind in non-pretty mode, where the projection child's prewhere column prints under its alias. With the removal disabled the count moves 1 -> 2 in both EXPLAIN formats. One guard ships with no SQL oracle and this is deliberate: no query can present a pure __topKFilter prewhere while also carrying a user filter, since every such shape is merged into an and(...) that the helper already declines, so the only trigger would be a server-config fixture declaring an executable function of that name.
e Both directions demonstrated? Yes, on separately built and Build-ID-verified binaries against the same fixture: with the predictor restored the filter is absent (the regression), with this change it is present, matching master. The benefit direction is measured the way the issue measured it, on the issue's own reproducer: with the removal disabled RowsReadByPrewhereReaders is 512, SelectedRows 512 and read_rows 512; with it the same query reads 0, 256 and 256.
f Fix is general across code paths? The hook sits in the single function that turns a MergeTree read into an in-order read, so every caller reaches it: optimizeReadInOrder, its per-child union branch, and the aggregation/distinct/window-in-order entries (where the column-equality test is what correctly keeps the filter). Sibling requestReadingInOrder implementations in ReadFromObjectStorageStep and StorageMerge carry no MergeTree prewhere and are never stamped by tryOptimizeTopK.
g Fix generalizes across inputs (params/datatypes/wrappers)? The predicate is on plan shape, not on data: it compares the filter's argument name with the sort column name, so Nullable / LowCardinality / Array / Map / Const sort columns behave identically, and the read direction is not inspected, so a reverse-order read is covered by construction. The test file already exercises Nullable with NULLS FIRST, sampling, both pin behaviours, an unmaterialized projection, a partially materialized one, and a drifted projection part.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no format and no on-disk structure is touched, so no SettingsChangesHistory.cpp entry is due. The behaviour change is confined to a plan the optimizer builds within one query.
i Invariants and contracts preserved? The invariant is: a ReadFromMergeTree that produces its rows ordered by the top-k sort column does not carry the top-k dynamic prewhere this read was stamped for. The drop requires both the read's own top_k_filter_info to name the matched column and that stamp to record no user filter (!where_clause), so a user-defined executable function that happens to be called __topKFilter (the name is reserved nowhere) cannot have its PREWHERE discarded. The name check alone was not enough: the stamp is also set by the skip-index half, which needs no !getPrewhereInfo() precondition, so on a table with a minmax index on the sort column a user PREWHERE spelled exactly that way was stamped, read in order and erased. where_clause is false exactly when the top-k pass saw no filter below the limit, and a filter above the limit cannot be pushed below it, so a prewhere present later under that flag can only be the injected one. With the removal disabled, both has_topk_filter = 0 arms redden in both EXPLAIN formats, which is the evidence that the stamp is present in every case the fix must fire for. The block structure the steps above were built for is recomputed and compared with blocksHaveEqualStructure BEFORE anything is mutated, and on inequality the filter stays, so the fail-closed direction is master's behaviour. all_column_names is only ever replaced by a permutation of itself (a prewhere moves its own DAG outputs to the front and remove_prewhere_column erases the filter column, so no column is gained or lost), and updatePrewhereInfo is the class's own mutator, which recomputes the output header and the sort description. Removing a filter can only admit more rows and the answer is produced by the sort and limit above the read, so no answer can change; measured identical on a union plan with dynamic filtering on and off.

Session id: cron:clickhouse-impl-slot-5:20260912-155200

Dropping the injected `__topKFilter` prewhere in `requestReadingInOrder`
reorders `all_column_names` to the order the read must now return. A
projection read, however, is built by `optimizeUseNormalProjections` with
its ranges already analyzed (`readFromParts` takes
`merge_tree_projection_select_result_ptr`), and `spreadMarkRanges` feeds
the reader from `AnalysisResult::column_names_to_read`, not from
`all_column_names`. The new order therefore never reached the reader:
`initializePipeline` had to repair the header with a converting
`ExpressionTransform` between the read step and its source.

Measured on the projection in-order arm of 04545, two binaries:

  before  MergeTreeSelect header [id, payload, score], plus an
          ExpressionTransform above it inside (ReadFromMergeTree)
  after   MergeTreeSelect header [score, id, payload], no repair transform

Six other `all_column_names` mutators in this class already mirror the
list into the analysis when one exists; this makes the seventh do the
same. A non-empty `result_sort_description` is derived from
`output_header`, so the reordered list this branch commits cannot be
empty and the mirror cannot blank the read.

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

Copy link
Copy Markdown
Collaborator Author

The read amplification survives this hook, because the read bound is dropped by the caller

Measured on plain master and on this branch's head (Build-ID verified both sides), t (id, k, score, payload) ENGINE = MergeTree ORDER BY (k, id) SETTINGS index_granularity = 64, 200000 rows, materialised
p_score (SELECT id, k, score, payload ORDER BY (score, id)), query SELECT id FROM t ORDER BY score, id LIMIT 100, every setting at its default:

arm SelectedRows RowsReadByPrewhereReaders
master 62528 62528
this branch 62528 none
use_top_k_dynamic_filtering = 0 192 none

The hook works as designed: on this branch __topKFilter is gone from EXPLAIN and there are no prewhere
readers at all. The rows read do not move.

The reason is that the read bound is computed by the caller, before the hook runs. buildSortingDAG sets
limit = 0 for any ReadFromMergeTree that carries a prewhere (optimizeReadInOrder.cpp:306-309,
/// Should ignore limit if there is filtering.), and that zero arrives as the read_limit argument of
requestReadingInOrder (optimizeReadInOrder.cpp:1292-1296), which stores it in InputOrderInfo
(ReadFromMergeTree.cpp:3861). Nulling query_info.prewhere_info inside the callee cannot put the bound
back, so the in-order read stays unbounded and stops only when pipeline cancellation catches up.

Two checks that pin this to the bound rather than to the filter:

  • rows read are independent of the LIMIT on the amplified arm (LIMIT 100, 200, 500, 900 all read 62528),
    while with the mechanism off they scale: 192, 448, 960, 960;
  • an always-true user predicate with the mechanism off reproduces the identical 62528, both on this
    projection and on a base table ordered by (score, id). So the zeroing is a property of "the read
    carries a filter", not of projections and not of top-k.

requestReadingInOrder already receives the un-zeroed limit as its query_limit parameter
(optimizeReadInOrder.cpp:1237, passed at :1296; used today only for query_task_size_limit). After the
hook withdraws the top-k-only prewhere the read carries no filter at all, which is exactly the state in
which the LIMIT bound is legitimately usable, so the bound can be restored there.

I am not opening a separate PR for this. It is a few lines in the block this PR already adds, it cannot
land before this PR, and the changelog sentence attributing the full-table scan to the redundant prewhere
becomes accurate only once the bound is restored.

`Stateless tests (amd_binary, flaky check)` runs a changed test 50 times with
`--jobs nproc-1`, and fails any run whose wall time passes
TEST_MAX_RUN_TIME_IN_SECONDS (180). At head 75c1f96 that job reported 7 FAIL
with `Test runs too long` at 214.7 to 360.8 s, against 51 OK whose median was
91.7 s: every copy was building eight 32768-row fixtures with materialized
projections, so the cost was self-contention on the insert and mutation paths
rather than any single slow query.

Each fixture drops to 1024 rows (512 per partition for the two-partition one).
Nothing else about the fixtures changes: the granularity, byte-granularity,
part-width and projection definitions that each arm's plan decision rests on
are untouched, and all 25 boolean reference lines keep their current expected
values. Only the two five-row blocks of ids printed by the correctness arms
move, since they are the top 5 of a smaller row set.

Measured on one binary, 50 runs at `--jobs 25` (the flaky-check shape):

  32768 rows   min 1.39  p50 2.94  p90 3.74  max 5.40
  1024 rows    min 0.53  p50 0.74  p90 0.84  max 0.89

so p50 falls 4.0x and the tail 6.1x; the tail compresses more than the median
because the co-scheduled copies were contending, which is what produced the
outliers. Marks on the cost-asymmetry fixture stay ordered the way that arm
needs them (parent 62, p_wide_ord 62, p_narrow_noord 5).

`read_in_order_use_virtual_row = 0` on the pipeline-distance arm: a
VirtualRowTransform sits between the read step and its source at exactly the
position the repair transform would, and `clickhouse-test` randomizes that
setting. The arm read 1 at 32768 rows only because the index there drops the
projection's suffix key column and suppresses the producer, so without the pin
the arm would report 1 or 2 at random. Pinning it leaves the arm asserting the
one transform it is about.

Co-Authored-By: Claude Opus 5 <[email protected]>
The arm added for the analysis mirror counted EXPLAIN PIPELINE rows between
`(ReadFromMergeTree)` and `MergeTreeSelect`, which any processor inside the read
step moves. `clickhouse-test` randomizes `read_in_order_two_level_merge_threshold`,
and at 0 the in-order read gains an `ExpressionTransform x 2` of its own, so the
arm reported 2 on a correct binary. Measured on the shipped binary at the previous
head with the 32768-row fixtures, i.e. before the fixtures were resized:
reference line 8 read 2 and the whole file failed. The runner's own
`--diagnose-random-settings` named the setting after 67/67 reproductions and
74/74 passes without randomization.

`read_in_order_use_virtual_row`, also randomized, inserts a VirtualRowTransform
at the same position; the arm read 1 only because the projection's index drops
its suffix key column at that fixture size and suppresses the producer.

The property the mirror actually buys is that the source returns the reordered
columns itself, so read that: `EXPLAIN PIPELINE header = 1` and require the
`MergeTreeSelect` header to start with the sort column. Keyed on the source's own
line, the arm is indifferent to how many processors sit above it. Expected value
stays 1, so `.reference` is untouched.

Measured, one binary per arm, whole file:
  shipped                          pass in pretty and legacy, and with
                                   `read_in_order_two_level_merge_threshold=0`
  mirror removed                   line 8 -> 0 in all three
  200 runs, --flaky-check --jobs 25, randomization on: 200 OK

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

Copy link
Copy Markdown
Collaborator Author

Flaky check timeout at 75c1f96e, plus one arm that was randomization-dependent

Stateless tests (amd_binary, flaky check) failed 7 runs with Test runs too long (> 180s) (214.7 to 360.8 s) against 51 OK at a 91.7 s median. That job runs a changed test 50 times with --jobs nproc-1, so every copy was building eight 32768-row fixtures with materialized projections at once.

Each fixture now holds 1024 rows (512 per partition for the partitioned one). Granularity, byte granularity, part width and the projection definitions are untouched, and all 25 boolean reference lines keep their expected values, so only the two five-row id blocks moved. Marks on the cost-asymmetry fixture stay ordered as that arm needs: parent 62, p_wide_ord 62, p_narrow_noord 5.

Measured on one binary, 50 runs at --jobs 25 (the flaky-check shape):

fixture size min p50 p90 max
32768 rows 1.39 2.94 3.74 5.40
1024 rows 0.53 0.74 0.84 0.89

The tail falls 6.1x against 4.0x for the median, which fits the outliers coming from co-scheduled copies contending rather than from one slow query.

The arm I added in 0fbaf0ec was separately flaky. It counted EXPLAIN PIPELINE rows between (ReadFromMergeTree) and MergeTreeSelect, and clickhouse-test randomizes read_in_order_two_level_merge_threshold, which at 0 gives the in-order read an ExpressionTransform x 2 of its own, so the arm read 2 on a correct binary. I reproduced that on the previous head with the 32768-row fixtures still in place, so it is not a side effect of resizing them, and --diagnose-random-settings named the setting after 67/67 reproductions and 74/74 passes without randomization. The arm now reads the source's own header (EXPLAIN PIPELINE header = 1; the MergeTreeSelect header must start with the sort column), which is the property the mirror buys and is indifferent to what sits above the source. Expected value unchanged.

Both directions on separate binaries: disabling the prewhere drop reddens the three arms that assert it, in both EXPLAIN formats; removing the analysis mirror reddens the header arm and nothing else. 200 runs with --flaky-check --jobs 25 and randomization on: 200 OK, no timeout.

The branch is at 26 commits. I am happy to squash before merge if that is preferred.

…ilter

`buildSortingDAG` zeroes the read-in-order limit for any `ReadFromMergeTree`
that carries a prewhere or a row-level filter ("Should ignore limit if there is
filtering", optimizeReadInOrder.cpp), and that zero is what the caller passes as
`requestReadingInOrder`'s `read_limit`. The guard added by this PR withdraws the
redundant `__topKFilter` prewhere inside the callee, which cannot put the bound
back, so the in-order read stayed unbounded and stopped only when pipeline
cancellation caught up. The filter went away, the read amplification did not.

`requestReadingInOrder` already receives the intact bound as `query_limit` (used
so far only for `query_task_size_limit`), so the callee has what it needs.
Rebuild `InputOrderInfo` with it when, and only when, this branch commits the
drop: `read_limit == 0` with a non-zero `query_limit` means a filter suppressed
the bound, and after the drop no filter is left. The result is exactly the state
an unfiltered read of the same query already carries today, so the rebuilt bound
needs no correctness argument of its own.

`!query_info.row_level_filter` is the one precondition the bound needs and the
prewhere drop does not: a row policy also zeroes the limit and is not withdrawn
here. `top_k_filter_info->where_clause` already implies it (optimizeTopK sets
that flag for a prewhere, a row-level filter or a FilterStep, and its walk
admits only Expression/Filter steps between the LimitStep and the read, so a
Join/Distinct/arrayJoin that would zero the limit means no `top_k_filter_info`
at all), but asserting it here keeps the block verifiable without reading the
other pass. A caller that passes no `query_limit`, such as the distributed-read
injection, leaves the bound alone.

Measured on two binaries with Build-IDs asserted, `t (id, k, score, payload)
ORDER BY (k, id) SETTINGS index_granularity = 64`, 200000 rows, materialised
`p_score ... ORDER BY (score, id)`, `SELECT id FROM t ORDER BY score, id LIMIT n`,
rows read:

  n                     100     200     500     900
  before              62528   62528   62528   62528
  after                 192     448     960     960
  filter off            192     448     960     960

Rows returned are identical on every arm, so this was a read-amplification
defect and never a wrong-results one. The new test arm uses 1024 rows at
granularity 8, where the same query reads the whole table before the fix and 24
rows after it, and compares against the mechanism-off run so both sides see the
same randomized settings. It fails 3/3 on a binary without the change, with the
diff confined to that one line.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b05ea01

CI is fully finished at this commit. One check failed, and it has an owner.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in clickhouse-server.log trunk-side log noise, not a test assertion: a mutation on a stale empty part retries forever, and every attempt writes <Error> MutatePlainMergeTreeTask: Code: 47 ... Unknown expression identifier \b`. Maybe you meant: ['a']` (the part predates the column change), which the job's server-log scan reds on #118499 (mine, open) stops mutating an empty part that cleanup is about to drop, removing the retry loop that emits those lines

Mergeable Check and PR are aggregate statuses rolling up that same single failure, not separate ones.

Not caused by this PR. Measured over the last 30 days, that exact signature (Upgrade check log scan + MutatePlainMergeTreeTask + UNKNOWN_IDENTIFIER) appears in 70 rows across 66 distinct pull requests and 0 true-master runs, onset 2026-08-22; this commit contributes 1 of them. The previous commit on this branch (4858953e) carried the identical row, and the branch touches only src/Processors/QueryPlan/Optimizations plus its own test, nothing in mutations or cleanup.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110883&sha=b05ea01b2af4e8c981d72a7cf4b4f2aad83d159f&name_0=PR&name_1=Upgrade%20check%20(amd_release)

Session id: cron:our-pr-ci-monitor:20260913-050032

This branch has not been deployed

No deployments
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-bot PR origin: review-bot finding on a groeneai PR groeneai-origin-unknown PR origin: unclassified (legacy task) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

use_top_k_dynamic_filtering installs a redundant/counterproductive __topKFilter prewhere when the read is already in-order via a sorting projection

5 participants