Repository navigation
Skip Parquet row groups by statistics for a String ORDER BY key without the per-row filter - #124827
Conversation
…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]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; r1: 3 findings, r2: 3 findings, r3: 0 findings, r4 after the rebase onto #122064: 0 findings) plus my own review.
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20261009-043300 |
|
Workflow [PR], commit [794a551] Summary: ✅
AI ReviewSummaryEnables statistics-only TopK pruning for Final VerdictStatus: ✅ Approve |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-41:20261009-030300 |
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
CI finish ledger - a32dd7aEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All check runs completed. The other three Session id: cron:our-pr-ci-monitor:20261009-070003 |
The flaky check stopped 05346 as too slow on amd_tsan (180-192 s of the 180 s limit) and killed it at the 600 s timeout on amd_binary, amd_debug and amd_asan_ubsan. The check enables the thread fuzzer, which costs about 40 ms per 100-row Parquet subgroup, so each full read of the 80000-row file at input_format_parquet_max_block_size = 100 took 31-33 s there, and the test had about 50 of them: the unoptimized side of the result comparisons, the reference reads and counts of the cache arm, and the reads of the String-key tripwire. No full read is left: - the results of the three queries in four configurations are compared with fixed rows in the reference, in order; - the late-skip and cache arms repeat the read until it skips 38 row groups (at most 20 times), taking the counters from --print-profile-events; - the late-skip arms also assert that a skipped row group reads no page: the sort column has one page per row group, so skipped plus ParquetReadPages is 40; without rows_pass = 0 the counter alone still passed, and the sum is 41-42; - the String-key tripwire for ClickHouse#124827 runs only when a 4-row probe shows statistics skipping String row groups without the per-row filter. The probe prints 0 on master; with ClickHouse#124827 it prints 1 and the 5 reads and the cache-on count run, so whichever of the two merges second updates the reference and adds the skipped_by_top_k mark in scheduleTask; - the final cache-on count is removed: it only covered the query condition cache rule that master already has (no plain-key entry after a top-K read). Debug build, randomized, -j 8: fix 50/50 OK, base 20/20 FAIL (no read skips 38 row groups), fix without rows_pass = 0 10/10 FAIL (pages), this branch with ClickHouse#124827 at a32dd7a and the mark 20/20 OK on the armed reference, without the mark 20/20 FAIL (count 26000-30000 of 40000). From the per-query times of the amd_binary flaky check, the test now takes about 55 s there. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…coding The check in scheduleTask runs when a row subgroup's step is dequeued. One scheduling pass can dequeue several row groups' tasks (up to the ColumnData stage's share of the parsing threads, about 1/5) and batch them, so a task can still wait behind other decodes, in its batch or in the pool, while the threshold tightens. runTask now repeats the check when the step's last unfinished task starts: the step's other tasks have finished, so no other thread reads filter.rows_pass. Both sites share skipIfExcludedByTopK. The pages of such a subgroup are already prefetched, so only the decode is saved. Debug build, a file of 200 row groups x 100000 random UInt64 keys, SELECT k ... ORDER BY k LIMIT 10, 20 runs each. Row groups the threshold excluded when their first decode task started, decoded anyway, per query: - 32 parsing threads, one subgroup per row group: 8.15 (max 32) -> 0 - 32 parsing threads, default block size: 3.1 (max 12) -> 0 - 20 parsing threads: 1.6-1.75 -> 0 - 8 parsing threads: 0 -> 0 Results equal use_top_k_dynamic_filtering = 0 in 180 runs (5 queries; 2, 8 and 32 threads; 3 block sizes; PREWHERE on and off) and in 90 under TSan with no report; the parquet top-K tests pass, under TSan too. The skipped_by_top_k mark of ClickHouse#124827 now goes into skipIfExcludedByTopK. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…p-k-string-statistics 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]>
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units339 translation units recompiled, 3519 s compile time in total, 339 of them have a recent master baseline. |
… 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]>
CI finish ledger - c31f42dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The Session id: cron:our-pr-ci-monitor:20261023-220003 |
# 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]>
CI finish ledger - 009e161Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261028-120007 |
|
🕵 Merged master (no conflicts; the touched Parquet / |
…ache With one sort column the top-K threshold skips a row group whose minimum (maximum for DESC) equals the threshold. Such a row group can hold rows equal to the n-th value, but it returns no row, so the TopK query condition cache recorded it as holding no row of the result. Overlapping runs that keep different tied row groups then record all of them, and a later run returns fewer rows: after 16 overlapping `ORDER BY k LIMIT 1` reads of 16 Parquet files, the next read returned no row in 5 of 100 cycles (0 of 120 with this change, 0 of 40 on master). `getMatchedBuckets` now counts a row group skipped by the threshold of a single sort column as matched, as it already did for statistics-only reads, and `getTopKBestValuesOfBuckets` reports the bound of its statistics as its best value, so the final-threshold check of the cache writers still records it as empty when that bound sorts strictly beyond the final threshold. Master is merged in for `skipped_by_top_k` (ClickHouse#124827), which the fence uses. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…p-k-late-skip For `RowGroup::skipped_by_top_k` (ClickHouse#124827), which the late top-K skip now has to set.
ClickHouse#124827 reports a row group skipped by a statistics-only top-K threshold as possibly matching in the query condition cache, but only if skipped_by_top_k is set. The late check did not set it, so a String ORDER BY ... LIMIT read at the default settings recorded such row groups as not matching its WHERE, and a later read with the same WHERE missed their rows. skipIfExcludedByTopK now sets the mark for every subgroup and step it drops, not only where it counts the profile event. 05346: the String key section is no longer conditional, now that ClickHouse#124827 is merged. It runs on its own file of 10 row groups, because the read that uses the cache entry decodes every row subgroup of every row group (about 50 s for the 40 row groups of t.parquet under the flaky check's thread fuzzer, locally). The columns cache is disabled in all sections: it reads each row group in one row subgroup, so no row group waits behind another. Debug build of this branch merged with master 5053961, 05346 with random settings: 50 of 50 pass; without the mark the cached count() is 1000 or 2000 instead of 10000 in 20 of 20 runs; with master's ReadManager the late skip sections fail in 10 of 10. Before the columns cache pin, 13 of 50 runs failed, all with use_columns_cache = 1 and enable_writes_to_columns_cache = 1. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…red-by-streams Resolve the conflict in PartialSortingTransform.h: keep master's public `min_limit_for_partial_sort_optimization` (ClickHouse#124827) and the `threshold_collector` member. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since ClickHouse#124827 a Parquet top-K read by a `String` column skips row groups by their statistics alone, without the per-row filter. Such a read does not set `isTopKFilterApplied()`, so the object-storage writer stored its row blocks, and the blocks of the skipped row groups, never checked against the predicate, were stored as not matching. A later plain read of the same condition then skipped matching rows: with this branch merged into master and default settings, `SELECT s FROM s3(...) WHERE k > 0 ORDER BY s LIMIT 10` over 512 row groups, then `SELECT count() FROM s3(...) WHERE k > 0` returned 5863130 instead of 7190235. Gate the write on `!top_k_filter`, as the `File` writer already does. That also covers any other top-K mechanism that leaves blocks unread. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #124560
Related: #104216
Related: #122064
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
ORDER BY <String column> LIMIT noverParquetfiles skips row groups by the min/max statistics of the sort column, as it already did for numeric keys, without the per-row filter thatuse_top_k_dynamic_filtering_for_variable_length_typescontrols:SELECT Title FROM file('hits.parquet') ORDER BY Title DESC LIMIT 10skips 203 of its 226 row groups and is about 10 times faster at 4 threads. Closes #124560.Description
Proposed by @ snelheidai in #124560; numbers below are mine.
With
use_top_k_dynamic_filtering_for_variable_length_types = 0(the default since #104216),tryTopKForFormatSourcereturned before creating the threshold tracker for aStringkey, so Parquet reads skipped no row groups by statistics. The setting targets the per-row__topKFilter; the per-row-group check costs one comparison per row group.Change. A
Stringkey (alsoNullable/LowCardinality) gets the threshold withFormatTopKFilterInfo::filter_rows = false: the reader orders and skips row groups by statistics, but installs no per-row filter and does not force the offset index. Excluded: collations,LIMIT + OFFSET >= 1500(therePartialSortingTransformfilters rows itself, but not with a tracker),Memorytables (they would get a per-row filter) andURLreads (unchanged). If all row groups share the bound on the threshold side, the file order is kept. For the query condition cache such a read is a plain read: skipped row groups count as matched, and it takes the plain branches of #122064 (File) and #124808 (data lakes), whateveruse_query_condition_cache_for_top_kis.FIXED_LEN_BYTE_ARRAYread asStringno longer uses statistics for TopN: the cast strips trailing zero bytes that the statistics keep, soORDER BY f, v LIMIT 3could lose rows (reproducible today with the opt-in).Measured (release,
hits.parquet, 4 threads, 11 alternating runs, identical results):ORDER BY Title DESC LIMIT 10ORDER BY URL DESC LIMIT 10ORDER BY URL LIMIT 10MobilePhoneModel LIMIT 300At 16 threads: 0.20-0.46x. New test
05339_parquet_top_k_string_statistics(fails on the old binary) and perf testparquet_top_k_string.xml.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/124827]
Version info
26.11.1.961-master(included in26.11and later)