Repository navigation
Skip Parquet row groups by their dictionary for ORDER BY <String> LIMIT when the filter rejects the empty string - #128290
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]>
…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]>
… 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]>
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).
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20261030-210700 |
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20261030-205100 |
|
cc @scanhex12 @al13n321, could you review this and add the |
|
Workflow [PR], commit [0bb9142] Summary: ✅
AI ReviewSummaryReviewed #128290 at Missing context / blind spots
Final VerdictStatus: ✅ Approve. No new inline findings to post. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units22 translation units recompiled, 218 s compile time in total, 22 of them have a recent master baseline. |
`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]>
|
@groeneai, check the slowdowns on Iceberg. |
|
I checked the
|
Closes: #128233
Related: #124827
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
ORDER BY <String column> LIMIT nover localParquetfiles with a filter that rejects the empty string (such asWHERE 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
SearchPhrasehas the minimum'', so withs != ''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''(!=,notEmptyor> '', also on aLowCardinalitycolumn, or a string value filter; notOR, notindexHint), the reader decodes it in theDictionarystage 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:
Prefetcherassigned read tasks to cancelled requests (ThreadSanitizer); it now skips them.Release, alternating runs, same results (time ratio [95% CI]; peak memory):
LIMIT 1000, one fileLIMIT 1000, one fileAt 16 threads the extra memory is dictionaries decoded ahead of the read; with
LIMIT 1000a bounded row group that is read decodes its dictionary twice. Test05474_parquet_top_k_string_dictionary_boundfails on #124827's head.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/128290]
Version info
26.11.1.1653-master(included in26.11and later)