Repository navigation
TopN dynamic filtering for reading Parquet files - #115798
Conversation
Extend the ORDER BY <column> LIMIT n dynamic-filtering optimization (use_top_k_dynamic_filtering, previously MergeTree-only) to Parquet reads through the file table function and the File engine. tryOptimizeTopK now also matches sources that opt in via SourceStepWithFilterBase::supportsTopKDynamicFilter and hands them a FormatTopKFilterInfo (the sort column plus the shared TopKThresholdTracker the sorting transforms publish into) through FormatFilterInfo. The native Parquet reader uses it twice: - as the first PREWHERE step, an internal __topKFilter(sort_column) drops rows that cannot enter the top-K heap; because it runs first, the columns of the later steps and of the output are then read only for the surviving rows, with whole pages skipped where possible; - right before a row group's column data would be read (the latest point with a threshold at hand), the row group is skipped entirely when the sort column's min/max statistics prove that none of its rows can improve the heap. The statistics are used only when they prove the chunk has no nulls, since they describe non-null values only and null rows may themselves belong to the top-K. Both uses only ever remove rows the sort + limit above would discard, so they compose with any WHERE / PREWHERE in any order, and a stale (not yet tightened) threshold is always safe. On the ClickBench t3a.small emulation (2 cores, 2 GiB, warm file): Q23 (SELECT * FROM hits WHERE URL LIKE '%google%' ORDER BY EventTime LIMIT 10) goes from 36.4 s to 7.4 s, Q24 from 3.2 s to 2.4 s, Q26 from 2.7 s to 1.7 s. On a file sorted by the sort column (1M rows, 100 row groups, 2 threads), ORDER BY k LIMIT 5 reads 43608 rows instead of 1000000. Object storage reads (s3, Iceberg) can adopt the same channel as a follow-up; their FormatFilterInfo is rebuilt per file for schema evolution and lazy materialization, which needs separate plumbing. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [1250b09] Summary: ❌
AI ReviewSummaryThis PR extends Final Verdict✅ No new review findings. LLVM Coverage ReportMeasured on commit 1250b09.
Changed lines: Changed C/C++ lines covered: 158/169 (93.49%) · Uncovered code |
…ic-filtering Resolve conflict in `StorageFile.cpp`: master moved the `ReadFromFile` step declaration into `StorageFile.h`, so the TopN dynamic filtering members (`supportsTopKDynamicFilter`, `setTopKFilter`, `top_k_filter`) move there too; `supportsTopKDynamicFilter` is defined in the `.cpp` to keep the `boost::iequals` dependency out of the header.
The style check rejects a bare `catch (...)` that silently returns, and falling back to "don't prune" on undecodable statistics is exactly the kind of hidden fallback the project guidelines forbid. Rethrow with a hint naming the column and the `use_top_k_dynamic_filtering` setting, mirroring what the static min/max pruning path does with `input_format_parquet_filter_push_down`.
Build profile diff (arm_release)Commit See the job log for details. |
|
📊 Cloud Performance Report
This PR adds TopN dynamic filtering for file-format sources (Parquet ORDER BY x LIMIT n row-group and per-row skipping) plus supporting plumbing in StorageFile and the query-plan optimizer. None of the ClickBench queries flagged here (Q16, Q18, Q30, Q31) read Parquet files or hit the changed code path — they run over MergeTree, so the new filter is never armed for them. The flagged deltas (+12.8% to +21.9%) sit within master's current variance band; Q16 is intrinsically noisy and Q31's baseline is unstable. All four are downgraded to not_sure as run-to-run variance rather than real PR regressions. clickbenchFlagged queries (4 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
Three fixes for the review findings on the row-group statistics shortcut and the query condition cache: - `getTopKSortColumnRange` now runs the same `adjustRangeFromIndexIfNeeded` validation as the static min/max pruning path, so self-contradictory column chunk statistics (`min_value > max_value`) fail closed instead of becoming live pruning input for `topKShouldSkipRowGroup`. - The row-group statistics shortcut is disabled when the sort description carries a collator: Parquet `min_value` / `max_value` are bytewise extrema, not extrema in the query's collation order, so a row group could be skipped while still holding values that sort before the running threshold. The per-row `__topKFilter` (which compares with the collator) keeps working. - `StorageFileSource` no longer populates the query condition cache for TopN reads. A row group can be reported as unmatched only because the running threshold - derived from all files the query reads - had already excluded its rows, which is not a predicate-only verdict, while the cache key encodes just the predicate and one file's version token. Reading the cache stays enabled: entries are only ever written by threshold-oblivious reads. Adds a regression test for a collated `ORDER BY` over Parquet where the bytewise and the collated order of the sort column disagree.
…le()` reads when `use_query_condition_cache_for_top_k` is off The setting is documented to make TopK reads neither consult nor populate the query condition cache. `StorageFileSource` already never writes entries for TopN reads, but it still consulted the cache unconditionally, so a TopN Parquet `file()` read could change behaviour based on previously cached predicate-only state even with the setting disabled.
…l of `05043_selected_rows_file_url_double_count` The test asserts that the lazy materialization cell of a Parquet `file()` read consumes exactly 1000 + 3 rows. With TopN dynamic filtering now applied to Parquet reads, and the runner randomizing `use_top_k_dynamic_filtering` on, the first pass skips whole row groups from the running threshold and the cell read 903 rows instead, which is the pruning working as intended rather than the double counting the cell is about. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115798&sha=8e70004ec031c83a28b0167585308a7818548889&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29 PR: #115798
…e reader physically reads `tryTopKForFormatSource` accepted any sort column found in the output header of `ReadFromFile`. That header is broader than what the format reads: `prepareReadingFromFormat` appends Hive partition columns (taken from the file path) and virtual columns such as `_path` and `_file` after the Parquet chunk is produced, while the native reader is built on `format_header` and only sees physical file columns. `ORDER BY _path LIMIT n` therefore set `top_k_filter` for a column the reader could never evaluate: no pruning happened, but the side effects still applied (offset-index prefetches for every column, no query condition cache writes). `SourceStepWithFilterBase::supportsTopKDynamicFilter` now receives the resolved sort column and `ReadFromFile` answers from `info.format_header` (name and type), so a sort key that is not physically supplied by the format never arms the filter. The test gains virtual-column and Hive-partition-column sort keys with matching results with and without the optimization.
|
Two more ways the row-group statistics shortcut loses rows, both verified on this PR's CI binary with crafted-but-spec-conformant Parquet files, plus a note on how the pre-existing 1. Undecodable min/max stats become
Verified both ways on the PR-head build: one file with 2. The shortcut requires a stats-proved For completeness: the per-row The rest of the mechanism held up under the same scrutiny: |
…ort column
`format_header` lists the query-schema columns, which is not the same as
"physically read from this file". A column carrying a `DEFAULT` /
`MATERIALIZED` / `ALIAS` expression is recomputed *above* the format by
`AddingDefaultsTransform` for every value the reader reported as missing:
a column this file does not store (the reader fills type defaults), or a
`NULL` read into a non-`Nullable` column. The threshold the sorting
transforms publish then comes from the recomputed values while
`__topKFilter` compares the reader's own placeholders against it, so rows
that belong to the top-K are dropped.
For example, over a file that stores only `k`,
`SELECT k, d FROM file('x.parquet', Parquet, 'k UInt64, d UInt64 DEFAULT k')
ORDER BY d DESC LIMIT 3` returned the three largest `d` of the first block
instead of the three largest of the file.
`ReadFromFile::supportsTopKDynamicFilter` now also rejects a sort column
with a default expression - such a column is exactly the one
`AddingDefaultsTransform` may rewrite - and the reader tracks, per file,
whether it physically stores the sort column (`top_k_column_is_read`).
When it does not, neither the per-row filter nor the offset-index reads
the filter would otherwise force are set up.
…path `ORDER BY` sorts `nan` together with the NULLs, but the comparison functions behind `__topKFilter` do not: a `nan` can become the published threshold and then reject every finite value read afterwards, or be dropped under `NULLS FIRST`. That is a pre-existing defect of the `MergeTree` path, tracked in #116705, and this pull request would extend its reach to Parquet reads. Parquet adds a second, independent hazard: `nan` values are legally absent from min/max statistics (parquet.thrift: "When looking for NaN values, min and max should be ignored"), so a finite range cannot prove that a row group holds no `nan` row that must sort first - exactly like a chunk that may contain nulls, which the shortcut already refuses. So `tryTopKForFormatSource` now skips a sort column whose type can contain a floating-point number anywhere inside it, and `getTopKSortColumnRange` independently refuses the statistics shortcut for such a column, since that half stays unsound after #116705 is fixed.
…ound
`getTopKSortColumnRange` starts from `Range::createWholeUniverse()` and
fills the bounds with `decodeField`, which deliberately leaves a bound
untouched when the statistic cannot be turned into a usable value - a
`NaN` extreme, a rescale overflow, a signed/unsigned mismatch. Those
sentinels are `Null`-typed `Field`s, and `TopKThresholdTracker` compares
any `Null` as SQL `NULL`, ordered by `nulls_direction`, not as an
infinity. Under the default ascending `NULLS LAST` an undecodable
`min_value` therefore read as "beyond the threshold" and the whole row
group was skipped, even when it held the best rows.
For example, over two files where the second stores a negative `Int64`
and is read as `UInt64` (so its `min_value` cannot be decoded),
`SELECT k FROM file('s{1,2}.parquet', Parquet, 'k UInt64') ORDER BY k
LIMIT 3` returned the first file's three smallest values and lost the two
smallest of the query.
An unbounded side can never prove exclusion, so `topKShouldSkipRowGroup`
now keeps the row group whenever the consulted bound is still `isNull()`.
Each of them returns wrong rows on the previous commit's parent, and all three now agree with `use_top_k_dynamic_filtering = 0`: - `ORDER BY d DESC LIMIT 3` over `d UInt64 DEFAULT k` where the file does not store `d` returned the top of the first block (`65408, 65407, 65406`) instead of the top of the file (`99999, 99998, 99997`); - with a `nan` row in one of the files, `ORDER BY f ASC NULLS FIRST LIMIT 2` lost the `nan` (`100, 101` instead of `nan, 100`), and reading that file first made the `nan` the threshold, which then rejected every finite value (`1000, nan` instead of `100, 101`); - a negative `Int64` read as `UInt64` makes `min_value` undecodable, and `ORDER BY k LIMIT 3` skipped the row group holding the two smallest values (`1000, 1001, 1002` instead of `5, 6, 1000`).
|
🕵 @zlareb1 thank you — both of your findings are fixed, and both reproduced exactly as you described on the CI binary of
A third case from the AI review is fixed in 396bda2: |
ClickBench measurementsRan ClickBench's two Parquet entries — The off-run reproduces the daily master results on the affected queries (
|
| machine | vCPU | Q23 | Q24 | Q25 | Q26 |
|---|---|---|---|---|---|
| t3a.small | 2 | 25.47 → 5.78 (0.23x) | 5.89 → 3.96 (0.67x) | 3.99 → 4.00 (1.00x) | 6.00 → 3.97 (0.66x) |
| c6a.large | 2 | 16.98 → 3.10 (0.18x) | 3.75 → 2.12 (0.57x) | 2.48 → 2.46 (0.99x) | 3.76 → 2.10 (0.56x) |
| c6a.xlarge | 4 | 3.34 → 1.35 (0.40x) | 1.30 → 0.88 (0.68x) | 0.91 → 0.91 (1.01x) | 1.32 → 0.88 (0.67x) |
| c6a.2xlarge | 8 | 2.09 → 0.69 (0.33x) | 0.83 → 0.41 (0.49x) | 0.45 → 0.45 (1.00x) | 0.83 → 0.41 (0.50x) |
| c6a.4xlarge | 16 | 1.35 → 0.41 (0.31x) | 0.48 → 0.24 (0.51x) | 0.27 → 0.27 (0.99x) | 0.48 → 0.24 (0.51x) |
| c8g.4xlarge | 16 | 0.89 → 0.29 (0.33x) | 0.35 → 0.18 (0.51x) | 0.21 → 0.20 (0.96x) | 0.35 → 0.18 (0.51x) |
| c6a.metal | 192 | 0.70 → 0.29 (0.41x) | 0.17 → 0.13 (0.74x) | 0.14 → 0.14 (1.02x) | 0.17 → 0.12 (0.72x) |
| c7a.metal-48xl | 192 | 0.85 → 1.18 (1.39x)¹ | 0.18 → 0.13 (0.68x) | 0.14 → 0.13 (0.96x) | 0.26 → 0.15 (0.58x) |
| c8g.metal-48xl | 192 | 0.65 → 0.45 (0.70x) | 0.16 → 0.12 (0.74x) | 0.10 → 0.10 (1.00x) | 0.15 → 0.11 (0.77x) |
clickhouse-parquet-partitioned (100 files), hot seconds, off → on
| machine | vCPU | Q23 | Q24 | Q25 | Q26 |
|---|---|---|---|---|---|
| t3a.small | 2 | 27.62 → 4.99 (0.18x) | 6.69 → 3.71 (0.55x) | 4.11 → 4.22 (1.03x) | 6.76 → 3.81 (0.56x) |
| c6a.large | 2 | 9.62 → 2.32 (0.24x) | 3.67 → 1.76 (0.48x) | 2.45 → 2.51 (1.02x) | 3.67 → 1.76 (0.48x) |
| c6a.xlarge | 4 | 1.96 → 0.56 (0.29x) | 0.84 → 0.39 (0.46x) | 0.51 → 0.51 (0.99x) | 0.84 → 0.38 (0.46x) |
| c6a.2xlarge | 8 | 1.36 → 0.34 (0.25x) | 0.48 → 0.22 (0.46x) | 0.30 → 0.29 (0.96x) | 0.48 → 0.22 (0.46x) |
| c6a.4xlarge | 16 | 1.35 → 0.27 (0.20x) | 0.35 → 0.16 (0.47x) | 0.26 → 0.25 (0.96x) | 0.36 → 0.17 (0.46x) |
| c8g.4xlarge | 16 | 0.53 → 0.17 (0.33x) | 0.18 → 0.09 (0.48x) | 0.13 → 0.12 (0.99x) | 0.18 → 0.09 (0.47x) |
| c6a.metal | 192 | 0.36 → 0.17 (0.47x) | 0.14 → 0.09 (0.68x) | 0.12 → 0.12 (0.97x) | 0.14 → 0.09 (0.67x) |
| c7a.metal-48xl | 192 | 0.33 → 0.21 (0.64x) | 0.14 → 0.10 (0.66x) | 0.13 → 0.13 (0.95x) | 0.15 → 0.10 (0.69x) |
| c8g.metal-48xl | 192 | 0.36 → 0.30 (0.84x) | 0.13 → 0.07 (0.58x) | 0.10 → 0.09 (0.93x) | 0.12 → 0.08 (0.66x) |
Cold (first run of each query, page cache dropped) improves more uniformly, including on the large machines: Q23 cold is 0.26–0.54x on every machine in both entries — 12.55 → 6.80 s on all three metals — and Q24/Q26 cold 0.48–0.97x.
Three things line up with what the PR predicts: the gain shrinks as core count rises, Q25 is untouched because ORDER BY SearchPhrase is variable-length and use_top_k_dynamic_filtering_for_variable_length_types defaults to 0, and the row-group shortcut shows up strongest in the cold numbers.
The rest of the benchmark is unaffected
Over the other 39 queries × 9 machines, on/off hot ratios have geomean 0.999 (single) and 0.996 (partitioned) across 351 pairs, with 12 and 5 pairs above 1.10x against 6 and 5 below 0.90x — symmetric, so noise rather than a systematic cost.
Effect on the benchmark totals
Hot totals, off → on, with the part contributed by the four top-K queries:
| machine | single: top-K | single: total | partitioned: top-K | partitioned: total |
|---|---|---|---|---|
| t3a.small | −23.6 s | +14.4 s² | −28.5 s | +24.2 s² |
| c6a.large | −17.2 s | −17.0 s | −11.1 s | −4.6 s |
| c6a.xlarge | −2.8 s | −5.2 s | −2.3 s | −3.9 s |
| c6a.2xlarge | −2.2 s | −2.2 s | −1.6 s | −2.7 s |
| c6a.4xlarge | −1.4 s | −2.1 s | −1.5 s | −2.6 s |
| c8g.4xlarge | −0.9 s | −1.0 s | −0.6 s | −0.9 s |
| c6a.metal | −0.5 s | −0.2 s | −0.3 s | −0.2 s |
| c7a.metal-48xl | +0.2 s | +0.3 s | −0.2 s | −0.2 s |
| c8g.metal-48xl | −0.3 s | −0.7 s | −0.2 s | −0.3 s |
Cold totals improve by 4–21 s nearly everywhere.
Two caveats
¹ The single apparent regression is variance, not a regression. Q23 on the 192-core machines is sub-second and dominated by scheduling jitter: the raw tries are off [12.566, 0.849, 1.478] vs on [6.803, 1.998, 1.179] on c7a.metal-48xl, and c8g.metal-48xl gives on [·, 2.963, 0.454] — a 6x spread between two tries of the same configuration. The cold number on those machines (0.54x, consistent across all three) is the reliable signal.
² t3a.small totals are not usable, though its per-query rows are. With 2 GB RAM and a swapfile against a 14 GB dataset, its slowest queries swing by tens of seconds between runs — Q31 24.4 → 37.2 s, Q18 +5.6 s, Q32 +4.4 s, none of them touched by this PR — which swamps the 24–28 s the feature actually saves.
|
Now we should implement Query Condition Cache for TopK in Parquet. |
The branch was 12555 commits behind and CONFLICTING. One conflict, in optimizeTopK.cpp, and both sides of it are pure additions in the same region just above tryOptimizeTopK, so both are kept: - master, from ClickHouse#115798 (TopN dynamic filtering for Parquet, merged 2026-09-24): typeCanContainFloat and tryTopKForFormatSource, plus the redirect that replaced the `if (!read_from_mergetree_step) return 0;` bail with `return tryTopKForFormatSource(...)`. - this branch: dependsOnItsBlock, and the signature spelling `QueryPlan::Nodes & /*nodes*/`. The parameter stays unnamed after the merge: master's new format-source path does not take `nodes`, and in this branch the only writer of new plan nodes is installTopKDynamicFilter, which takes its own reference. The two changes do not interact. The format-source redirect returns before the MergeTree dynamic-filtering decision this branch rewrites, and it delivers its filter through FormatTopKFilterInfo on a SourceStepWithFilterBase rather than through the ReadFromMergeTree stamp that installTopKDynamicFilter keys on. Verified that the merge neither reverted master's work nor dropped any of this branch's: the added/removed line payload of the diff against master is byte-identical before and after the merge (780 lines, 16 files, +712/-75), with master's two new functions now appearing as unchanged context.
The master merge left this branch dereferencing a pointer that can be
null. The re-entrancy check this branch added sits between the
`typeid_cast<ReadFromMergeTree *>` and the bail-out for a step that is
not a MergeTree read, and it was written when that bail-out was the very
next statement:
auto * read_from_mergetree_step = typeid_cast<ReadFromMergeTree *>(...);
if (!read_from_mergetree_step)
return 0; // merge-base, and this
// branch before the merge
if (read_from_mergetree_step->isSelectedForTopKFilterOptimization())
ClickHouse#115798 deleted that early bail and reinstated it ~50 lines further down
as `return tryTopKForFormatSource(...)`, which needs `sort_col_desc`, and
guarded the one line it could see (`isQueryWithFinal`) with an explicit
`read_from_mergetree_step &&`. It never saw this branch's line, so after
the merge the re-entrancy check was the only unguarded dereference
between the cast and the bail-out.
Guarded with the same `&&` spelling master uses two lines below, rather
than by moving the bail-out back above it: the bail-out is what routes a
format source into the Parquet TopN path, so hoisting it would disable
that feature. A step that is not a MergeTree read carries no TopK stamp,
so the re-entrancy question does not arise for it and falling through to
the format path is correct.
Verified: 79 TopK-family tests with randomization off give 78 OK / 0
crashes here, against 76 OK on a pristine master binary whose only two
extra failures are this branch's own 05059 and 03711 (they assert the
fix, so they must fail there). The single common failure,
02984_topk_empty_merge, reports byte-identical `Connection refused
(127.0.0.2:20200)` on both arms: this sandbox runs one node.
TopN dynamic filtering for Parquet (ClickHouse#115798) skips a row group when its min/max statistics are compared with the running threshold, at the OffsetIndex stage of ReadManager::finishRowGroupStage. ReadManager::init started all row groups at once, so with no bloom filter, dictionary or page index work every row group passed that check before the sorting transforms had published any threshold, and with such work the row groups still reached it in file order. Inside one file the skip almost never fired; 05025 only covers it across the files of a glob. Now, when the read order is free (no input_format_parquet_preserve_order, no lazy materialization row list) and at least one row group to read has a usable range of the sort column: - Reader::prefilterAndInitRowGroups orders the row groups by the minimum of the sort column for ascending order and by the maximum for descending order; row groups without a range go last. row_group_idx and start_global_row_idx keep the file positions, so _row_number, bucket matching and the query condition cache are unaffected. - ReadManager admits them gradually: at most max(parsing_threads, admitted / 2) are admitted but not fully read, and each is checked against the latest threshold right before it starts. A skipped row group does not raise the allowance and an admitted one does, so a scan that the threshold cannot prune quickly converges to an unthrottled one (the same scheduling as Pivot's table_source.rs). Row groups excluded by the bucket list or the query condition cache are deallocated at admission without being counted. - New profile event ParquetTopKSkippedRowGroups. The format-source branch of tryOptimizeTopK ran before the dependsOnItsBlock guard that only the MergeTree branch had, so a stateful or non-deterministic function below the sort (expression, WHERE, user PREWHERE) already saw rows dropped by the reader's threshold filter, and with the new order it would also see the row groups out of file order. The guard now applies to both branches. For formats it also covers a block-dependent row policy: the Parquet reader applies the row-level filter after the threshold filter, while MergeTree applies it first. Analysis and the original patch by snelheidai in ClickHouse#123564. Allowing statistics for a plain INT64 column read as DateTime (part 3 of that patch, needed for ClickBench's EventTime with the DateTime schema) is left to ClickHouse#117017. Closes ClickHouse#123564 Co-Authored-By: Claude Opus 5.5 <[email protected]>
A TopN (`ORDER BY ... LIMIT n`) read of Parquet files through the `File` engine now writes query condition cache entries for the row groups that held no row of the result, and a rerun of the same query skips them. The entries depend on the running TopK threshold, which comes from the rows of every file the query reads, so they are stored under a key that covers the TopK plan, the predicate (a read without one is cached too), and the version tokens of all the files; the key is made only when every token has settled. The plain predicate key keeps getting only threshold-oblivious entries. A cancelled read no longer writes entries, as the row groups it did not read report no matching rows either. Closes: ClickHouse#121876 Related: ClickHouse#115798 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Extends the
ORDER BY <column> LIMIT ndynamic-filtering optimization (use_top_k_dynamic_filtering, previouslyMergeTree-only) to Parquet reads through thefiletable function and theFileengine.tryOptimizeTopKnow also matches sources that opt in viaSourceStepWithFilterBase::supportsTopKDynamicFilterand hands them aFormatTopKFilterInfo(the sort column plus the sharedTopKThresholdTrackerthe sorting transforms publish into) throughFormatFilterInfo. The native Parquet reader uses it twice:__topKFilter(sort_column)drops rows that cannot enter the top-K heap; because it runs first, the columns of the later filter steps and of the output are then read only for the surviving rows, with whole pages skipped where possible;Both uses only ever remove rows the sort + limit above would discard, so they compose with any
WHERE/PREWHEREin any order, and a stale (not yet tightened) threshold is always safe - provided the reader's own value of the sort column is the value the query sorts by, and provided the threshold comparison matchesORDER BYsemantics. Each use is therefore armed only where that holds:the sort column must be one the format physically reads. Virtual columns (
_path,_file), Hive partition keys and columns carrying aDEFAULT/MATERIALIZED/ALIASexpression are produced above the format (AddingDefaultsTransform), soReadFromFile::supportsTopKDynamicFilterrejects them; and inside the reader the filter is dropped for a file that simply does not store the column;floating-point sort columns are excluded:
ORDER BYsortsnantogether with the NULLs while the comparison functions behind__topKFilterdo not (a pre-existing defect of theMergeTreepath, Wrong results forORDER BY <float> LIMIT nwithnanvalues under top-k optimizations #116705), andnanvalues are legally absent from Parquet min/max statistics, so a finite range cannot prove that a row group holds nonanrow;the row-group shortcut additionally stays off wherever the statistics do not bound the row group in the query's own order, or do not even live in the same value space as the data:
ORDER BY- Parquet extrema are bytewise, not collation-ordered;UUIDsort column - Parquet gives theUUIDlogical type theUNSIGNED(bytewise) sort order while ClickHouse compares aUUIDas its two 64-bit halves in the opposite order, so the bytewise extrema are not the extrema in the query's order and can even come out inverted (Parquet UUID min/max statistics are byte-lexicographic but are used as ClickHouse-order bounds: silent row loss and false INCORRECT_DATA at default settings #118371);decodeFieldleaves such a bound at theRangeinfinity sentinel, which is aNull-typedFieldand would otherwise be compared as a SQLNULL;INT32column read asUInt16keeps the raw physical value in the bound whilecastColumnwraps the values themselves around (Parquet filter push-down compares raw file values while a narrowing schema hint changes the decoded value:WHEREsilently loses rows thatSELECTshows, at default settings #118383).The last two disable the shortcut for the whole row group rather than for their own side of the range: a
min_valuethe output type cannot hold means some value reaches the sort wrapped to an arbitrary place, and then themax_valueno longer bounds the row group either.Everything else applies unchanged:
query_plan_max_limit_for_top_k_optimization, theDynamic/Variantexclusion, and the variable-length opt-in (use_top_k_dynamic_filtering_for_variable_length_types).Measured on the ClickBench
t3a.smallemulation (2 pinned cores, 2 GiB cgroup, file in page cache):SELECT * FROM hits WHERE URL LIKE '%google%' ORDER BY EventTime LIMIT 10SELECT SearchPhrase FROM hits WHERE SearchPhrase <> '' ORDER BY EventTime LIMIT 10... ORDER BY EventTime, SearchPhrase LIMIT 10On a file sorted by the sort column (1M rows, 100 row groups, 2 threads),
ORDER BY k LIMIT 5reads 43608 rows instead of 1000000 — with more reading threads the reduction is smaller because more row groups pass the pre-read checkpoint before the first threshold is published.Object storage reads (
s3, Iceberg) can adopt the same channel as a follow-up: theirFormatFilterInfois rebuilt per file for schema evolution and lazy materialization, which needs separate plumbing.Related: #114262
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Queries with
ORDER BY <column> LIMIT nover Parquet files (thefiletable function and theFileengine) now use TopN dynamic filtering (settinguse_top_k_dynamic_filtering): rows that cannot enter the top-K are filtered inside the reader before the remaining columns are read, and whole row groups are skipped when their min/max statistics prove they cannot contribute. Floating-point sort columns are excluded for now.Workflow [PR]
Sync PR [sync-upstream/pr/115798]
Version info
26.10.1.569-master(included in26.10and later)