Skip to content

Skip Parquet row groups by their dictionary for ORDER BY <String> LIMIT when the filter rejects the empty string - #128290

Merged
alexey-milovidov merged 14 commits into
ClickHouse:masterfrom
groeneai:groeneai/parquet-top-k-string-dictionary-bound
Nov 8, 2026
Merged

alexey-milovidov merged 14 commits into
ClickHouse:masterfrom
groeneai:groeneai/parquet-top-k-string-dictionary-bound

Conversation

@groeneai

@groeneai groeneai commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #128233
Related: #124827

Changelog category (leave one):

  • Performance Improvement

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

ORDER BY <String column> LIMIT n over local Parquet files with a filter that rejects the empty string (such as WHERE s != '') now skips row groups by the values of their dictionary when their min/max statistics (minimum '') cannot: ClickBench Q26 over its 100 Parquet files is about 11% faster with 4 threads. Closes #128233.

Description

Patch from @ snelheidai's #128233; the measurements are mine. Builds on #124827.

Every row group of ClickBench's SearchPhrase has the minimum '', so with s != '' the threshold of #124827 skips none. A chunk whose data pages are all dictionary-encoded has every value in its dictionary: when the threshold is set and PREWHERE or the pushed-down filter rejects '' (!=, notEmpty or > '', also on a LowCardinality column, or a string value filter; not OR, not indexHint), the reader decodes it in the Dictionary stage and bounds the row group by its non-empty entries; the existing check then skips it.

Remote reads are unchanged unless the file is read into memory: there the page is read with the data pages, and bounding held up to 3.4x the memory. Cancelling the separately read dictionary page made a data race reachable: Prefetcher assigned read tasks to cancelled requests (ThreadSanitizer); it now skips them.

Release, alternating runs, same results (time ratio [95% CI]; peak memory):

Query (local) Threads Time Memory
Q26, 100 files 4 0.886 [0.853, 0.920] 210 -> 174 MB
Q26, one 206 MiB file 1 0.850 [0.845, 0.855] 40 -> 37 MB
Q26, one file 4 0.758 [0.739, 0.778] 87 -> 83 MB
Q26, one file 16 0.907 [0.822, 1.001] 205 -> 250 MB
LIMIT 1000, one file 1 1.043 [1.034, 1.051] 40 -> 40 MB
LIMIT 1000, one file 4 1.026 [0.980, 1.075] 89 -> 90 MB

At 16 threads the extra memory is dictionaries decoded ahead of the read; with LIMIT 1000 a bounded row group that is read decodes its dictionary twice. Test 05474_parquet_top_k_string_dictionary_bound fails on #124827's head.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1653-master (included in 26.11 and later)

groeneai and others added 13 commits October 9, 2026 04:06
…ut the per-row filter

With `use_top_k_dynamic_filtering_for_variable_length_types = 0` (the default), `tryTopKForFormatSource`
returned before creating the threshold tracker for a `String` sort key, so the Parquet reader got no
threshold at all: no skipping of row groups by min/max statistics and no sort-key-ordered admission.
The setting exists because the per-row `__topKFilter` comparison can cost more than it saves; the
per-row-group statistics check is O(row groups) and does not have that cost.

Now a `String` key (through `Nullable` / `LowCardinality`) gets the threshold with
`FormatTopKFilterInfo::filter_rows = false`: the reader orders, admits and skips row groups by
statistics, but installs no `__topKFilter` and does not force the offset index. Not for a collated
order (the reader cannot use the statistics), not for `LIMIT + OFFSET >= 1500` (there
`PartialSortingTransform` filters rows by its own threshold, which it does not do once a tracker is
set), and only for sources that can use statistics (`ReadFromFile`, `ReadFromObjectStorageStep`; a
Memory table would otherwise get a per-row filter).

When all row groups of a file share the bound on the threshold side, the reader keeps the file order: no
row of that file is beyond that bound. For the query condition cache a statistics-only read is a plain
read: the row groups it skipped are reported as matched, all four cache gates (File and object storage,
read and write) treat it as a read without TopN, and a `File` read makes no TopK cache key for it
(tracking the best values for that key would compare every returned row).

`FIXED_LEN_BYTE_ARRAY` read as `String` no longer uses statistics for TopN: the cast strips trailing
zero bytes from the values, but the statistics keep them, so a row group whose padded minimum ties
the threshold could be skipped and rows that win on a later sort column lost. This was reachable with
the opt-in and would otherwise have become reachable by default.

Adds `tests/performance/parquet_top_k_string.xml`.

Closes ClickHouse#124560

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove a duplicate cache-write note and the design rationale of the filter-less TopK cache key (both in the commit message); shorten the FIXED_LEN_BYTE_ARRAY and PartialSortingTransform notes to one line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… condition cache after the master merge

Master (ClickHouse#124808) added a TopK query condition cache key for data lake reads and made a TopN read of
object storage neither consult nor write the plain predicate key while
`use_query_condition_cache_for_top_k` is off. A statistics-only read (a `String` sort key without
`use_top_k_dynamic_filtering_for_variable_length_types`) compares no row with the threshold, so, as for
`File` tables and as the setting's documentation says, it stays a plain read for the cache:

- the plain key is consulted (merge resolution) and written whatever the value of the setting;
- `ReadFromObjectStorageStep::makeTopKQueryConditionCacheKey` makes no TopK key for it, as
  `ReadFromFile` already does: the key would make the reader track the best value of every row group,
  a per-row comparison on the `String` column that the statistics-only mode exists to avoid.

Test: a statistics-only read with the setting off populates the cache (File, S3); an Iceberg read
without a filter consults the cache with the opt-in and not without it.
Mutants, each red on exactly its line: write gate without `filter_rows`, consult gate without
`filter_rows`, no early return in the data lake key.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… check

The flaky check runs eight copies of the test at once with the thread fuzzer on, where every process
start and every query is slow: the test took 161-180 s in the debug and 254-263 s in the ASan flaky
check, over the 180 s limit.

- clickhouse-local starts 4 times instead of 19: the fixtures in one process, the `rows_read` checks in
  one (a JSON document per query), all modes of the result comparison in one (switched with SET, the
  query condition cache off so that no mode reads the entries of an earlier one, as a process per mode
  guaranteed before), the Memory check in one.
- The 8-thread run compares only the optimization against the result without it, computed once: every
  query orders by a unique key, so that result does not depend on the threads. The 8-thread opt-in run
  is dropped: this change touches the opt-in path only by the FIXED_LEN_BYTE_ARRAY guard, which the
  single-thread opt-in run still checks.
- The server part runs one client call per group of queries, tags queries by `log_comment`, flushes and
  scans `system.query_log` once instead of nine times, counts without the cache once per table, and makes
  two attempts instead of three for the cache checks: no test of the parallel phase drops the cache.
- The skipped-row-group arms also read the `File` table's data as `Nullable(String)`,
  `LowCardinality(String)` and `LowCardinality(Nullable(String))`. The `rows_read` bound that the
  clickhouse-local checks assert for these wrappers holds with a per-row filter too, so only
  `ParquetRowsFilterExpression = 0` shows that they get none: a mutant that gives them the per-row
  filter is red on exactly these lines.

The reference loses one header line and gains the three wrapper lines. Debug, single run: 9.9 s ->
3.3 s; eight copies on 16 CPUs with the flaky check's thread fuzzer (no CPU migration) 47-50 s ->
18-21 s; one copy with the full thread fuzzer on 16 CPUs 465 s -> 231 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Processors/QueryPlan/Optimizations/optimizeTopK.cpp
#	src/Storages/StorageFile.cpp
…llel replicas

Since ClickHouse#127138 a persistent `S3` table is read over the replicas when parallel replicas are
enabled, so in the `ParallelReplicas` job the `ProfileEvents` of the initial query no longer
count the query condition cache lookups and the skipped row groups of the `t_05339_s3` and
`t_05339_s3_glob` reads, and four lines of the reference read 0. Pin
`enable_parallel_replicas = 0` for every server read of the test, as the `IcebergLocal` reads
already did, instead of tagging the whole test `no-parallel-replicas`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…IT when the filter rejects ''

With `WHERE s != '' ORDER BY s LIMIT n` over Parquet the TopN threshold could
not skip any row group by statistics: the minimum of nearly every row group of a
`String` column like ClickBench's `SearchPhrase` is the empty string, which the
filter removes. For a chunk whose data pages are all dictionary-encoded, the
dictionary holds every value, so its non-empty entries bound the rows that can
reach the sort.

When a row group reaches the `Dictionary` stage, the threshold is set, the
statistics bound on the threshold side is '' and a conjunct of PREWHERE or of the
filter pushed down to the source rejects '' (`s != ''`, `notEmpty(s)`, `s > ''`,
or a condition that `extractStringValueFilters` extracts), the dictionary page of
the sort column is decoded under the pruning memory budget, and the row group's
range is replaced by the min/max of the non-empty entries (cut to 256 bytes,
which only widens it). The `OffsetIndex` stage then skips the row group as
before. A dictionary decoded only for this is freed right away (a row group that
is read decodes it again on the data path) and does not feed the string value
filter statistics. On a local file, or a file held in memory, the dictionary
page is read for this by its own request and released with the dictionary, so a
row group that waits to be read holds nothing for the bound; on remote storage
the page stays shared with the read of the data pages. `indexHint` and `or` are
not treated as row filters.

The perf test `parquet_top_k_string` gets a dictionary-encoded column `d` and a
query on it.

New event `ParquetTopKRowGroupsBoundedByDictionary`. Based on the analysis and
patch by @ snelheidai in ClickHouse#128233.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
On remote storage the dictionary page is read together with the data pages,
which would then be held from the bound until the row group is read (1 thread,
206 MiB file on MinIO, `WHERE SearchPhrase <> '' ORDER BY SearchPhrase LIMIT 10`:
59 -> 199 MB peak). So the bound is applied only to a local file or a file held
in memory, where the page is read for it by its own request and released with
the dictionary. A remote read now runs the same code path as before the bound
was added. The test checks that a remote read is not bounded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…uet dictionary bound

The filter walker that decides whether a filter rejects the empty string
accepted only `String` and `Nullable(String)` inputs, so a column declared
`LowCardinality(String)` or `LowCardinality(Nullable(String))` was never
bounded, although the reader decodes it as `String` and the statistics path
of the top-K threshold covers it. It now accepts both. String value filters
keep their scope.

A `notEquals`/`greater`/`less` atom that is not a comparison with `''` now
falls through to the string value filter extraction, so comparisons of
`position(s, 'x')` with a constant are recognized too.

The test gains `LowCardinality`, `LowCardinality(Nullable)`, `position` and
no-PREWHERE arms, and no longer sets the obsolete
`query_plan_optimize_prewhere`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Delete the comments that restate the names of the new members and functions or narrate the new code, merge the 0xFF note into the cut-bound one, shorten multi-line notes, and state the forms filterRejectsEmptyString recognizes accurately (LowCardinality only for != '', notEmpty and > '').

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 rounds, 3 findings) plus my own review (5 notes).

# Sev Finding Verdict Evidence / action
1 ⚠️ The bound was never armed for LowCardinality(String) / LowCardinality(Nullable(String)) columns AGREE, fixed the empty-string check accepts LowCardinality inputs; two test arms
2 ⚠️ The statistics-only path is off for LIMIT >= 1500 although the setting text does not say so DISAGREE out of scope: that code and text are #124827's, unchanged here
3 💡 Comparisons of position(s, 'x') with a constant were not recognized AGREE, fixed test arm
4 💡 No test arm for the pushed-down filter without PREWHERE AGREE, fixed arm with optimize_move_to_prewhere = 0
5 💡 A bounded row group that is read decodes its dictionary twice DISAGREE measured and disclosed (LIMIT 1000, 1 thread, 1.043); keeping the decoded dictionary costs more memory
6 💡 The header comment names LowCardinality columns, but string value filter conditions are recognized on String only noted, not blocking header comment reworded before publishing

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261030-210700

@mintlify

mintlify Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 0bb9142.

Approve preview

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT e FROM file('t.parquet') WHERE e != '' ORDER BY e LIMIT 5 at 1 thread on a 20-row-group file where every row group has '': #124827's head skips 0 row groups, this PR bounds 18 and skips 16, same rows.
b Root cause explained? Min/max statistics include the rows the filter removes, so '' in every row group keeps the ASC boundary at '' and the threshold skips nothing. The dictionary of a fully dictionary-encoded chunk holds every value, so its non-empty entries bound the rows that pass a filter rejecting ''.
c Fix matches root cause? Yes. The row group's range is replaced by the dictionary bound at the Dictionary stage, before any data page is read; the existing skip check is unchanged; truncation to 256 bytes only widens the range.
d Test intent preserved / new tests added? New 05474_parquet_top_k_string_dictionary_bound: 19 queries compared with and without the optimization at 1 and 4 threads, 13 skip and 4 no-skip assertions (or, indexHint, no statistics, remote read), query condition cache arm. Perf test parquet_top_k_string.xml extended. Eight mutants of the change each fail it.
e Both directions demonstrated? Yes, on Build-ID-checked debug binaries: fails on #124827's head (13 skip lines), passes with the change; 50/50 randomized runs; bounding a remote read fails only the remote line.
f Fix is general across code paths? Both filter sources (PREWHERE with need_filter, filter pushed to the source), both call sites of the skip check, the query condition cache key, columns cache (not eligible), lazy materialization (never with TopN). Local files and files held in memory are bounded; remote reads keep the old code path.
g Fix generalizes across inputs (params/datatypes/wrappers)? Nullable (chunks with NULLs have no range), NULLS FIRST, LowCardinality(String) and LowCardinality(Nullable(String)) columns, comparisons of position; FixedString, converted strings, arrays and collations are not eligible. ASC/DESC, OFFSET, values over 256 bytes, 0xFF maxima, ties, missing statistics; a 19-query ClickBench sweep up to LIMIT 1499 returns identical results.
h Backward compatible? (maintainer-approved exception only) Yes. No new setting, no default or format change. use_top_k_dynamic_filtering = 0 or input_format_parquet_dictionary_filter_push_down = 0 turn it off.
i Invariants and contracts preserved? A row group is skipped only if no row passing the row filter can enter the result. Every new prefetch handle is released with its memory accounting on all paths (checked by the reader's leak check, which a mutant proves sees it). String filter statistics are counted once.

Session id: cron:clickhouse-impl-slot-4:20261030-205100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @scanhex12 @al13n321, could you review this and add the can be tested label so CI runs? For ORDER BY <String> LIMIT with a filter that rejects '', the Parquet reader bounds a fully dictionary-encoded row group by its non-empty dictionary values, so the TopN threshold of #124827 (required, still open) can skip row groups whose minimum statistic is ''.

@clickhouse-gh

clickhouse-gh Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0bb9142]

Summary: ✅


AI Review

Summary

Reviewed #128290 at 0bb9142aed12e11ac4f23a3b10e9a334642d2d2d, including the prior discussion and exact PR-head files. The change enables statistics-only pruning for String sort keys, refines eligible Parquet row-group bounds using non-empty dictionary values, preserves query-condition cache correctness, and fixes cancelled-prefetch task assignment. No actionable findings remain. The supplied result comparisons, mutation checks, TSan stress results, and before/after measurements support approval.

Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build directory was available, so runtime tests and benchmarks were not independently rerun. The available Praktika report contains no reported failures, but many jobs contain no test results; completed targeted stateless and sanitizer runs would close this verification gap.
Final Verdict

Status: ✅ Approve. No new inline findings to post.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-parquet-reader-v3 Issues related to the native Parquet reader. labels Oct 30, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0bb9142ae with master 3cb763874 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of df4cd0872; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

`Prefetcher::pickRangesAndCreateTaskLocked` coalesces past cancelled ranges
and then wrote `task` and `task_offset` for every range it covered, cancelled
ones included. A cancelled request may have had a task: `PrefetchHandle::reset`
reads `request->task` after the exchange to `Cancelled`, without the mutex, so
that write is a data race, and when the write lands first, `reset` can decrement
the new task's refcount instead of the old one's (the new buffer can be freed
while a covered request still reads it, the old one is never released).

The top-K dictionary page range (a second range at the dictionary page's start,
read alone and cancelled at the end of the dictionary stage) makes this
reachable: ThreadSanitizer reported it on 05474_parquet_top_k_string_dictionary_bound
in `Stateless tests (amd_tsan, flaky check)` of the stacked PR ClickHouse#128757. A local
stress of that test's multi-threaded queries on a TSan build of this branch
reproduced it in 12 of 1920 runs before this change and 0 of 6400 after.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, check the slowdowns on Iceberg.

@alexey-milovidov alexey-milovidov self-assigned this Nov 7, 2026
@groeneai

groeneai commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator Author

I checked the iceberg_s3 rows (the iceberg_local shards have no slower rows). I don't see a slowdown from this PR:

  • None of the flagged queries has ORDER BY ... LIMIT, so the dictionary bound is never armed for them (ParquetTopKRowGroupsBoundedByDictionary = 0). On their path the PR only adds a few flag checks per row group and one relaxed atomic load per range in Prefetcher::pickRangesAndCreateTaskLocked. S3 GETs, bytes read and row groups read are identical on both servers.
  • Local A/B on x86 with the amd_release CI binaries of this PR (c07b2d9, this PR merged into df4cd08) and of df4cd08 (the reference of this run), perf.py --table-engine iceberg_s3 on MinIO, 50 runs per query per round: merge_tree_small_blocks Repair subtree2 #1, Repair subtree2 #2, BaseDaemon: terminate on double SIGINT #3 over 5 rounds have medians of -1.5%, -0.7%, -1.8% (per-round values from -8.2% to +5.1%, the sign changes between rounds); negative_limit_by_in_order BaseDaemon: terminate on double SIGINT #3 over 2 rounds: +4.2%, -3.7%.
  • In this configuration the new server is slower on most PRs (CIDB, last 21 days, median new/old ratio): merge_tree_simple_select #0 1.67 (249 of 257 PR runs), merge_tree_small_blocks #0-doc: fix typo #4 1.06-1.11 (33-37 of 45). The ratios here are within the spread of other PRs, e.g. negative_limit_by_in_order BaseDaemon: terminate on double SIGINT #3 is 1.32 here, 22 runs of other PRs are at 1.15 or more, up to 1.43. text_index_low_cardinality_build #0 was flagged slower on 58 PRs (and Repair subtree2 #2 of the same test is faster here), point_in_polygon_index #0 on 9. The job has no historical thresholds for iceberg_s3 yet, so only the 15% floor applies.
  • Do not copy Parquet String values beyond the top-K threshold for ORDER BY <String> LIMIT #128757 contains this whole diff and ran the same jobs the same day: merge_tree_small_blocks and negative_limit_by_in_order were not flagged there (negative_limit_by_in_order BaseDaemon: terminate on double SIGINT #3 was 13% faster).

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 8, 2026
Merged via the queue into ClickHouse:master with commit 7f69e6e Nov 8, 2026
187 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-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

3 participants