Repository navigation
Conversation
…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]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-1:20260717-141200 |
|
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. |
|
Workflow [PR], commit [b05ea01] Summary: ❌
AI ReviewSummaryThis PR moves the Final Verdict✅ Approve. LLVM Coverage ReportMeasured on commit b05ea01.
Changed lines: Changed C/C++ lines covered: 36/38 (94.74%) · Uncovered code |
…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]>
|
Good catch. Tightened
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
Added both regression cases to 04545. |
Pre-PR validation gate (updated for a7aa62c)
Session id: cron:clickhouse-worker-slot-7:20260717-163800 |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 42/45 (93.33%) · Uncovered code |
CI finish ledger - a7aa62cCI 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.
All checks green except the private CH Inc sync (exempt). No PR-caused failure. Session id: cron:our-pr-ci-monitor:20260718-000000 |
|
@shankar-iyer can you review this PR soon? |
|
@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.
|
Merged master (31 days of drift) to resolve the conflict. Now The only conflict was in Also trimmed the guard comments to the local invariants and moved the chooser-gate reasoning Validation on the merged tree: full build clean, One correction to my earlier reply on this thread, since it claimed more than the code does.
Neither is introduced by this merge; both predate it in this branch. Fixing them properly |
…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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units8 translation units recompiled, 29 s compile time in total, 8 of them have a recent master baseline. |
CI finish ledger - ff8685cCI is fully finished on this head and it is clean. 177 check-runs, 159 success / 17 skipped
The matrix that ran is broad, not a small filtered subset: 44 The regression test added here, 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`.
|
Merged master again (the base was 7416 commits behind; one conflict, in 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.
Two materialised projections, one wide and ordering (1929 marks), one narrow and non-ordering (129 marks), parent 1929 marks:
Results are identical, so this is extra data read rather than wrong answers. Control on the fixture: with ReproducerCREATE 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 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 |
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]>
Internal second-model reviewI withdrew the narrowing remedy I announced in this comment. No metadata gate can predict the projection chooser's decision: the chooser ranks by ❌ Blocker, fixed - the read-order assertions used ❌ Blocker, fixed - the helper recognised the internal filter by name, and the stamp I first required is not proof of ownership: ❌ Blocker, fixed - the union arm counted occurrences of
💡 Disagreed, with evidence - the competing-projection arm was said to match any analysed candidate rather than the selected one. The recorded 💡 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 Scope, deliberate. A query that carries a user |
Pre-PR validation gate (click to expand)
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]>
The read amplification survives this hook, because the read bound is dropped by the callerMeasured on plain master and on this branch's head (Build-ID verified both sides),
The hook works as designed: on this branch The reason is that the read bound is computed by the caller, before the hook runs. Two checks that pin this to the bound rather than to the filter:
I am not opening a separate PR for this. It is a few lines in the block this PR already adds, it cannot |
`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]>
Flaky check timeout at
|
| 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.
CI finish ledger - b05ea01CI is fully finished at this commit. One check failed, and it has an owner.
Not caused by this PR. Measured over the last 30 days, that exact signature ( Session id: cron:our-pr-ci-monitor:20260913-050032 |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a performance regression where
use_top_k_dynamic_filteringinstalled a redundant__topKFilterprewhere on anORDER BY ... LIMITread 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 theLIMIT-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
LIMITwants 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_marksand 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::requestReadingInOrderdrops 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 nover 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/PREWHEREor a row policy is anand(...)and is left alone, as on master. Answers are unchanged with dynamic filtering on and off.Workflow [PR]
Sync PR [sync-upstream/pr/110883]