Skip to content

TopN dynamic filtering for reading Parquet files - #115798

Merged
alexey-milovidov merged 26 commits into
masterfrom
parquet-top-k-dynamic-filtering
Sep 24, 2026
Merged

alexey-milovidov merged 26 commits into
masterfrom
parquet-top-k-dynamic-filtering

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 21, 2026 •

Copy link
Copy Markdown
Member

Extends 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 filter 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 - provided the reader's own value of the sort column is the value the query sorts by, and provided the threshold comparison matches ORDER BY semantics. 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 a DEFAULT / MATERIALIZED / ALIAS expression are produced above the format (AddingDefaultsTransform), so ReadFromFile::supportsTopKDynamicFilter rejects 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 BY sorts nan together with the NULLs while the comparison functions behind __topKFilter do not (a pre-existing defect of the MergeTree path, Wrong results for ORDER BY <float> LIMIT n with nan values under top-k optimizations #116705), and nan values are legally absent from Parquet min/max statistics, so a finite range cannot prove that a row group holds no nan row;

  • 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:

    The last two disable the shortcut for the whole row group rather than for their own side of the range: a min_value the output type cannot hold means some value reaches the sort wrapped to an arbitrary place, and then the max_value no longer bounds the row group either.

Everything else applies unchanged: query_plan_max_limit_for_top_k_optimization, the Dynamic/Variant exclusion, and the variable-length opt-in (use_top_k_dynamic_filtering_for_variable_length_types).

Measured on the ClickBench t3a.small emulation (2 pinned cores, 2 GiB cgroup, file in page cache):

query before after
Q23 SELECT * FROM hits WHERE URL LIKE '%google%' ORDER BY EventTime LIMIT 10 36.4 s 7.4 s
Q24 SELECT SearchPhrase FROM hits WHERE SearchPhrase <> '' ORDER BY EventTime LIMIT 10 3.2 s 2.4 s
Q26 ... ORDER BY EventTime, SearchPhrase LIMIT 10 2.7 s 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 — 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: their FormatFilterInfo is rebuilt per file for schema evolution and lazy materialization, which needs separate plumbing.

Related: #114262

Changelog category (leave one):

  • Performance Improvement

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

Queries with ORDER BY <column> LIMIT n over Parquet files (the file table function and the File engine) now use TopN dynamic filtering (setting use_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

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

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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1250b09]

Summary: ❌

job_name test_name status info comment
Performance Comparison (amd_release, master_head, 3/6) FAIL Performance dashboard
order_by_read_in_order #1 FAIL dashboard
Performance Comparison (arm_release, master_head, 2/6) FAIL Performance dashboard
order_by_read_in_order #1 FAIL dashboard
set_index #1 unstable query history
Performance Comparison (arm_release, master_head, 5/6) FAIL Performance dashboard
serialization_pool_lookup #0 FAIL dashboard
hash_join_gather #2 unstable query history

AI Review

Summary

This PR extends ORDER BY <column> LIMIT n TopN dynamic filtering from MergeTree to Parquet reads through the file table function and the File engine, wiring the running threshold into ReadFromFile and the native Parquet reader so it can drop non-competitive rows early and skip row groups when Parquet statistics are provably sound for the query's ordering semantics. I reread the current diff, rechecked every prior review thread and reply against the current code, and did not find a remaining correctness, safety, or contract issue in the patch as it stands; the Performance Improvement changelog metadata also matches the change and the entry is specific.

Final Verdict

✅ No new review findings.

LLVM Coverage Report

Measured on commit 1250b09.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 158/169 (93.49%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 21, 2026
…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`.
Comment thread src/Storages/StorageFile.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 1250b09e09f373c19b706c89324593c7ab157cb2 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — no significant changes across 37 queries analysed

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.

clickbench

⚠️ 4 inconclusive

Flagged queries (4 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 16 not_sure 552 622 +12.8% <0.0001 This PR only adds Parquet TopN dynamic filtering (ORDER BY x LIMIT n on file sources); ClickBench Q16 runs on MergeTree and never touches this path, so the +12.8% is run-to-run variance on an intrinsically noisy query.
⚠️ 18 not_sure 906 1036 +14.4% <0.0001 The change is confined to the Parquet file-source TopN filter path; ClickBench Q18 is a MergeTree scan that does not exercise it, so the +14.4% delta cannot be attributed to this diff.
⚠️ 30 not_sure 226 276 +21.9% <0.0001 Q30 does not read Parquet or use ORDER BY ... LIMIT on a file source, the only path this PR touches, so the +21.9% is unrelated variance rather than a PR effect.
⚠️ 31 not_sure 271 327 +20.7% <0.0001 Baseline flagged unstable and the query does not touch the Parquet TopN path this PR changes; the +20.7% is not attributable to the diff.

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
  • StressHouse run: 14e26b67-8591-42b6-a447-49d72fff2b50
  • MIRAI run: bed1e712-e377-4d04-82fe-0dfd3b032e27
  • PR check IDs:
    • clickbench_1429350_1790132630
    • clickbench_1429452_1790132637
    • clickbench_1429467_1790132637
    • tpch_adapted_1_official_1429668_1790132652
    • tpch_adapted_1_official_1429771_1790132684
    • tpch_adapted_1_official_1429785_1790132684

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.
@zlareb1

zlareb1 commented Sep 3, 2026

Copy link
Copy Markdown
Member

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 nan issues of the per-row filter reach this new surface.

1. Undecodable min/max stats become Range infinities, and compareFields treats an infinity as a SQL NULL — the row group with the best rows is skipped at pure default settings.

Reader::getTopKSortColumnRange (src/Processors/Formats/Impl/Parquet/Reader.cpp:365) starts from Range::createWholeUniverse() (:390) and fills the bounds via decodeField. When a bound can't be decoded into a usable value, it is deliberately left at infinity — FloatConverter::convertField returns nullopt for a nan stat (Decoding.cpp:1749, per the parquet.thrift compatibility rule "if the min is a NaN, it should be ignored"), and a tryConvertFieldToType failure on rescale overflow does the same (Decoding.cpp:1145-1150, whose comment "Leaving the bound at infinity is always safe" predates this consumer, for which it is not). The infinities are Null-typed Fields (src/Core/Field.h:17-18; Field::isNull() is true for them, Field.h:416). Reader::topKShouldSkipRowGroup (Reader.cpp:410) then feeds range.left/range.right straight into TopKThresholdTracker::isValueInsideThreshold, whose compareFields checks lhs.isNull() first and returns nulls_direction (src/Processors/TopKThresholdTracker.cpp:9-17) — so −∞ sorts like a NULL, i.e. LAST under the default NULLS LAST, lands outside the threshold, and the whole row group is skipped.

Verified both ways on the PR-head build: one file with Float64 values 100…65635, a second file with two rows of 0.5 whose footer min_value/max_value are nan (data pages intact; ParquetMetadata shows nan/nan; plain SELECT * returns the rows). SELECT f FROM file('c{1,2}.parquet') ORDER BY f LIMIT 3 returns 0.5, 0.5, 100 with use_top_k_dynamic_filtering = 0 and 100, 101, 102 with it on — the group holding the best rows is silently lost. nan min/max stats are real legacy-writer output (the compatibility rules quoted in Decoding.cpp exist because such files exist), and the static KeyCondition pruning path already tolerates them; this new consumer does not. The fix direction: refuse the skip whenever the consulted boundary Field isNull() — an unbounded side can never prove exclusion.

2. nan data rows are legally invisible to min/max stats, and the shortcut has no nan guard — NULLS FIRST orderings lose the nan rows even though the per-row filter would keep them.

The shortcut requires a stats-proved null_count == 0 before trusting the range, but nothing accounts for nan, which spec-conformant writers exclude from min/max (ClickHouse's own writer does: [1000, nan] produces stats min = max = 1000). Under ASC NULLS FIRST, a nan row must sort first, but the group's range says nothing about it and topKShouldSkipRowGroup skips the group once another group publishes a finite threshold. Verified both ways on the PR-head build with Nullable(Float64): a file of 100…65635 plus a file of [1000.0, nan]; ORDER BY f ASC NULLS FIRST LIMIT 2 returns nan, 100 with the filter off and 100, 101 with it on. Two discriminators isolate the mechanism: adding one real NULL to the second file (making null_count = 1) disarms the shortcut and the result becomes correct — so the per-row filter handles the Nullable case fine and the loss is exactly the row-group skip; and rows_read drops from 65538 to 65536 — the second group is never read. The fix direction matches the existing NULL guard: for float sort columns the stats range cannot prove exclusion (a group can carry nan invisibly to stats, exactly like NULLs before the null_count check).

For completeness: the per-row __topKFilter's own nan misbehavior — dropping nan rows under NULLS FIRST, and accepting a published nan threshold that then filters out every subsequent row under plain default ASC — is pre-existing on the MergeTree path (reproduced on a pre-PR build) and tracked in #116705, including the default-NULLS LAST threshold-poisoning case just added there. This PR extends that machinery's reach to Parquet reads (Reader.cpp:1396-1410), so a fix for #116705 should cover this surface too.

The rest of the mechanism held up under the same scrutiny: WITH TIES/alwaysReadTillEnd are rejected upfront in optimizeTopK.cpp, the NULL handling of the shortcut (given the null_count proof) and of the per-row filter is correct, the collation disarm from the earlier review round works, computed sort keys can't alias a source column (the source is armed only when the resolved sort column exists in the source header with an identical type), threshold races only lose skips, self-contradictory min > max stats fail closed, and the query condition cache can't be poisoned by threshold-dependent emptiness because TopK reads never write to it.

@clickhouse-gh clickhouse-gh Bot added the comp-parquet-reader-v3 Issues related to the native Parquet reader. label Sep 4, 2026
…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`).
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @zlareb1 thank you — both of your findings are fixed, and both reproduced exactly as you described on the CI binary of 7f5c1a0d.

  1. Undecodable stats become Range infinities → d226181. topKShouldSkipRowGroup now keeps the row group whenever the consulted bound is still isNull() after decoding, which is your suggested direction: an unbounded side can never prove exclusion. Instead of a crafted file the regression uses a negative Int64 read as UInt64 — IntConverter::convertField returns nullopt for that min_value just as FloatConverter does for a nan one — so ORDER BY k LIMIT 3 over file(..., 'k UInt64') returned 1000, 1001, 1002 and now returns 5, 6, 1000.

  2. nan data rows are invisible to min/max stats → ccaad28. getTopKSortColumnRange refuses the shortcut for a floating-point sort column, on the same footing as the existing null_count guard and for the same reason you gave. On top of that, tryTopKForFormatSource keeps floating-point sort keys off this path entirely until Wrong results for ORDER BY <float> LIMIT n with nan values under top-k optimizations #116705 is fixed, since the per-row filter carries the pre-existing defect you traced; the two guards are deliberately independent, because the statistics one stays necessary after Wrong results for ORDER BY <float> LIMIT n with nan values under top-k optimizations #116705 is fixed. Your ASC NULLS FIRST case, the DESC NULLS FIRST mirror and both threshold-poisoning orderings are in the test.

A third case from the AI review is fixed in 396bda2: format_header also admits a column carrying a DEFAULT / MATERIALIZED / ALIAS expression, which AddingDefaultsTransform recomputes above the reader, so ORDER BY d DESC LIMIT 3 over d UInt64 DEFAULT k in a file that does not store d returned the top of the first block. The step now rejects such a column, and the reader additionally drops the filter per file when the file does not physically store the sort column.

Comment thread src/Storages/StorageFile.cpp Resolved

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Sep 24, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

ClickBench measurements

Ran ClickBench's two Parquet entries — clickhouse-parquet (one 14 GB file) and clickhouse-parquet-partitioned (100 files) — on 9 EC2 instance types, twice each: this PR's release build with stock settings (so use_top_k_dynamic_filtering = 1, the feature on) and the same binary with --use_top_k_dynamic_filtering 0. Both entries read through ENGINE = File(Parquet, ...) under clickhouse-local, which is the path this PR extends. The clickhouse-datalake* entries go through S3(...) and are left out, since object storage is explicitly a follow-up here.

The off-run reproduces the daily master results on the affected queries (t3a.small Q23: master 27.01 s, off 25.47 s; c6a.large: 16.75 / 16.98; c6a.4xlarge: 1.33 / 1.35), so on-vs-off inside one binary is a clean A/B and master behaves as "off", as expected. Results are byte-identical with the feature on and off for all four queries.

clickhouse-parquet (single file), hot seconds, off → on

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.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 24, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Now we should implement Query Condition Cache for TopK in Parquet.

Merged via the queue into master with commit 5206307 Sep 24, 2026
173 of 177 checks passed
@alexey-milovidov
alexey-milovidov deleted the parquet-top-k-dynamic-filtering branch September 24, 2026 03:26
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 24, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 24, 2026
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.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 24, 2026
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.
jh0x pushed a commit to jh0x/ClickHouse that referenced this pull request Oct 3, 2026
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]>
nihalzp pushed a commit to nihalzp/ClickHouse that referenced this pull request Oct 9, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-parquet-reader-v3 Issues related to the native Parquet reader. pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants