Skip to content

Do not copy Parquet String values beyond the top-K threshold for ORDER BY <String> LIMIT - #128757

Open
groeneai wants to merge 13 commits into
ClickHouse:masterfrom
groeneai:groeneai/parquet-top-k-string-decode-bound
Open

groeneai wants to merge 13 commits into
ClickHouse:masterfrom
groeneai:groeneai/parquet-top-k-string-decode-bound

Conversation

@groeneai

@groeneai groeneai commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #128573
Related: #128290

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 Parquet files with a filter that rejects the empty string (such as WHERE URL != '') no longer copies the values that are already beyond the top-K threshold: ClickBench ORDER BY URL LIMIT 10 and ORDER BY Title LIMIT 10 over the 100 Parquet files are about 40% faster with 4 threads, Q26 about 13%. Closes #128573.

Description

Patch from @ snelheidai's #128573, reworked; measurements are mine.

The partial sort above the reader discards almost every decoded value of the sort column. When that column is a String read without conversion, and PREWHERE needs it in its first step and reads it only in conjuncts that reject '', whose results only feed the filter, the PLAIN, DELTA_LENGTH_BYTE_ARRAY and DELTA_BYTE_ARRAY decoders write '' for a value strictly beyond the threshold (ties are kept), and dictionary pages use a per-entry mask; PREWHERE drops those rows before anything else reads the column. A single-column WHERE s != '' of such a read is moved to PREWHERE. While the bound is active, the query condition cache sees row groups as matched. With the columns cache enabled (#123890) neither the move nor the bound applies.

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

Query, 100 files Time Memory
URL <> '' ORDER BY URL LIMIT 10 0.592 [0.562, 0.624] 0.54
Title <> '' ORDER BY Title LIMIT 10 0.591 [0.561, 0.622] 0.76
Q26 0.868 [0.781, 0.964] 0.72
URL as DELTA_LENGTH_BYTE_ARRAY 0.895 [0.820, 0.978] 0.81

PREWHERE alone: 1.03 (URL), 1.04 (Title). Costs: Q26 over the single 14 GB hits.parquet is 0.919 [0.902, 0.937], where the PREWHERE alone would be 0.745, with peak memory 61 -> 99 MB; on reverse-ordered files that statistics cannot skip, the moved PREWHERE costs 1.07-1.14x and, with a dictionary, one mask build per column chunk another 1.03x. Test 05490_parquet_top_k_string_decode_bound fails on master.

🤖 Generated with Claude Code


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

groeneai and others added 10 commits November 2, 2026 06:48
…ngle-column queries a PREWHERE for it

Reworks the previous commit (the patch from ClickHouse#128573):

- The bound arms only on the PREWHERE path (`need_filter`), so that the values replaced by '' are dropped
  inside the reader. Without PREWHERE they leave the source, where `AddingDefaultsTransform` (a `DEFAULT`
  expression over the sort column) and filter-step nodes outside `filter_actions_dag` evaluate them:
  `CREATE TABLE t (s String, d UInt8 DEFAULT intDiv(100, length(s))) ENGINE = File(Parquet, ...)` and
  `SELECT s, d FROM t WHERE s != '' ORDER BY s LIMIT 10 SETTINGS optimize_move_to_prewhere = 0` threw
  `Division by zero` with the previous commit.
- `MergeTreeWhereOptimizer` moves a conjunct that rejects '' on the source's statistics-only `String` top-K
  sort column to PREWHERE even when it covers every queried column, like 9e651db does for string
  value filters. `SELECT s FROM file(...) WHERE s != '' ORDER BY s LIMIT n` (ClickBench Q26) then gets
  a PREWHERE. `SourceStepWithFilterBase::getTopKFilter` exposes the info that `tryOptimizeTopK` set in the
  first optimization pass.
- Who may read the column before the filter is decided by the allowed-readers rule of
  `extractStringValueFilters` (factored into `columnsWithOtherReaders`), via the new
  `filterReadsColumnOnlyInConjunctsRejectingEmptyString`, instead of a list of function names:
  `PREWHERE length(s) < 1000 AND s != ''` leaves the bound off.
- A column written to the columns cache in at least one row group gets no bound, the rule master already
  applies to the string value filter (61767f9, 45d9bde).
- The PLAIN bound lives in `PlainStringDecoderWithTopKBound`, so `PlainStringDecoder` is unchanged.
- The dictionary mask is allocated when the dictionary is decoded (`initTopKMask`) and counted in
  `Dictionary::decodedFootprintUpperBound`, like `string_value_filter_mask`; the dictionary keeps only the
  version of the threshold it was built from, not the threshold.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lumn query to the perf test

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… the bound-off paths on base code

Follow-up of the replan r1 (Gate A round 6), with the measurements of IMPL r1:

- The bound now covers DELTA_LENGTH_BYTE_ARRAY and DELTA_BYTE_ARRAY pages, like the string filter
  of PREWHERE does. Otherwise the conjunct moved to PREWHERE for the bound costs the PREWHERE path
  on such files with nothing to gain. The per-value checks (threshold refresh every 4096 values,
  pause after a window of 256 checked values without a replacement) live in one helper,
  `TopKStringBoundChecker`, used by the PLAIN and both DELTA decoders. The bound-off decoders are
  the base classes. Measured on URL rewritten as DELTA_LENGTH_BYTE_ARRAY (hits_0..9, 4 CPUs):
  0.767 [0.690, 0.854] of base.
- No move to PREWHERE for the bound when the columns cache may be written: the reader keeps the
  values of a column it writes, and a top-K read outputs its sort column anyway, so the move only
  cost memory (+32% peak memory measured on Q26 with `use_columns_cache = 1`).
- The dictionary records which per-entry mask it applies (`entry_mask`), so that `appendIndexes`
  and `appendRepeated` have one gate in front of both masks, and the top-K mask refreshes itself
  from inside its own branch. The bound-off dictionary path executes the base instructions
  (`perf stat` instructions:u within 0.1% of base on strings decoded in 1-row runs; before: +0.9%).

The test gets results arms on the DELTA files and a DESC + OFFSET arm, counter arms for both DELTA
encodings, and an EXPLAIN arm for the columns cache.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s top-K mask applies

A single-step PREWHERE that reads only the sort column decodes its dictionary as `ColumnReplicated`,
which bypasses the per-row gather where the top-K mask of the dictionary is applied. Do not use the
replicated decoding for a column with the bound.

Kept as a separate commit: measured on 4 CPUs, it gains nothing significant on ClickBench Q26 over
the 100 partitioned files (0.961 [0.892, 1.034] of the previous commit) and costs 11% on Q26 over
the single hits.parquet (1.109 [1.082, 1.136]); see impl-findings-r2.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Revert the previous commit. A single-step PREWHERE that reads only the sort column keeps decoding
its dictionary as `ColumnReplicated`, which copies no string at decode time; the top-K mask of the
dictionary then does not run for those subchunks, which is sound because they hold the real values.

Measured on 4 CPUs, 14 rounds, with the reverted commit against the one before it: ClickBench Q26
over the single hits.parquet 1.109 [1.082, 1.136], Q26 over the 100 partitioned files 0.961
[0.892, 1.034].

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

A tie on the sort key is only dropped wrongly when a copy of the threshold value arrives after the threshold
reached it and wins the tie-break: `ORDER BY t, k DESC LIMIT 1` (and DESC) has that shape, the `LIMIT 6` arms
do not. A top-K read writes a query condition cache entry only when its filter has a second conjunct, so the
cache arm also reads `WHERE s != '' AND k % 3 != 0`.

Checked with mutations: a non-strict comparison with the threshold now fails the tie arms on all four
encodings, and without the all-matched verdict in `getMatchedBuckets` the plain count returns 12000 rows
instead of 13333.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…esult is used elsewhere

`WITH notEmpty(s) AS ok ... PREWHERE throwIf(NOT ok) = 0 AND ok ORDER BY s LIMIT n` shares the `notEmpty(s)` node, so
`throwIf` saw the replaced '' through it and threw, while the readers check only looked at direct readers of `s`. The bound
now requires every PREWHERE node that depends on the column to be part of the filter's conjunction; `extractStringValueFilters`
is back to master's code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…p-k-string-decode-bound

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten or remove the comments of the top-K String bound that narrate its own design; keep the invariants.

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

groeneai commented Nov 2, 2026

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

Pre-publication review by an independent model (engine: codex; 3 rounds, 2 findings, 0 on the last two heads) plus my own review (4 nits).

# Sev Finding Verdict Evidence / action
1 ❌ A rejecting conjunct whose result is used elsewhere (WITH notEmpty(s) AS ok ... PREWHERE throwIf(NOT ok) = 0 AND ok) sees the replaced '' and throws AGREE, fixed every node that depends on the column must be part of the filter's conjunction; results and counter arms in 05490 (the previous head throws Code: 395 on them)
2 ⚠️ url() reads do not get the statistics-only top-K path DISAGREE ReadFromURL has no statistics-only top-K for String (optimizeTopK.cpp:130), which is #124827's surface; a separate PR
3 💡 While the bound is active every row group of the file is reported to the query condition cache as matched, not only the ones where values were replaced noted conservative, performance only
4 💡 The DELTA_LENGTH_BYTE_ARRAY bound decoder has no bulk copy path while the checks are paused noted the bound still pays off there (0.895)
5 💡 On the single 14 GB file the bound is slower than the moved PREWHERE alone noted disclosed in the description (0.919 vs 0.745)
6 💡 A dictionary decoded as ColumnReplicated still allocates the per-entry mask noted 1 byte per entry, counted in the reservation

Also noticed: master's scan-time string filter (#115848) has the same gap as finding 1 when a column has two conditions (WITH s LIKE '%1%' AS a ... PREWHERE throwIf(NOT a) = 0 AND a AND s LIKE '%2%' throws on 26.10.2.103). This PR leaves that code unchanged; the fix is the separate Bug Fix PR #128734, which adds a similar dependency check to the same file, so whichever of the two merges second will reuse the other's.

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

Session id: cron:clickhouse-review-slot-8:20261102-201400

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @grantholly-clickhouse @antaljanosbenjamin, could you review this and add the can be tested label so CI runs? For ORDER BY <String> LIMIT over Parquet with a filter that rejects '', the PLAIN, DELTA and dictionary decoders write '' for values strictly beyond the top-K threshold instead of copying them, and PREWHERE drops those rows; it stacks on #128290.

@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f6803eb]

Summary: ✅


AI Review

Summary

This PR avoids copying Parquet String values that cannot enter an ORDER BY ... LIMIT result by substituting empty strings that PREWHERE rejects. It covers PLAIN, DELTA and dictionary decoding, preserves threshold ties, and protects the columns cache and query condition cache. No actionable findings in the current diff at f6803eb51e5cc31285a20f86065a2da576de50d8. The supplied before/after measurements support the performance claim, and the added regression test exercises results, activation, exception-sensitive expressions and cache behavior.

Missing context / blind spots
  • ⚠️ No local build or test execution: this checkout has no ClickHouse binary. Current-head results for 05490_parquet_top_k_string_decode_bound were unavailable in the Praktika report during review; a completed stateless run would close this validation gap.
Final Verdict

Status: ✅ Approve. No code changes requested; normal CI validation remains required.

@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f6803eb51 with master 48f9d3b98 (stripped binary size, per-symbol sizes and ThinLTO time; 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.

Object file sizes

60 object files changed (+68.77 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/Parquet/Decoding.cpp.o 427.13 KiB 446.20 KiB +19.06 KiB (+4.46%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.63, programs/clickhouse-keeper ×0.67 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.7 s 11.5 s +7.9 s (+222%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.3 s 7.4 s +5.3 s (+257%)
Compile time of recompiled translation units

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

Job report

groeneai and others added 2 commits November 3, 2026 00:59
`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)`. A local stress of that test's
multi-threaded queries on a TSan build reproduced it in 23 of 2682 runs before
this change and 0 of 6720 after.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
It ran longer than 180 s in the flaky checks (185-267 s), where the thread
fuzzer is active in every clickhouse-local the test starts, so the cost is
per query and per row group read. The files now have 8 row groups of 500 rows
instead of 20 of 1000, and the queries whose plan does not depend on the
encoding (explicit schemas, the DEFAULT tables, the filters that arm or do not
arm the bound) run once instead of once per file. Every encoding still runs
the decoding arms: OFFSET, values '' in the file, ties at the threshold and a
second filter step. One clickhouse-local runs all of them, 49 queries in each
mode instead of 93.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 3, 2026
`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]>
@snelheidai

Copy link
Copy Markdown

On current master (b8c902a, which includes #128290), this PR cuts the time of ClickBench Q26 (SELECT SearchPhrase FROM hits WHERE SearchPhrase <> '' ORDER BY SearchPhrase LIMIT 10) over the 100 partitioned files by 19% hot (109 → 88 ms) and by 14% on the first run (139 → 121 ms). This uses the protocol ClickBench has used for clickhouse-parquet since ClickHouse/ClickBench@bbc2118aa5: clickhouse-server is restarted before each query. The machine is x86 and the server uses 16 threads.

The PR no longer merges cleanly: Parquet/Reader.cpp conflicts with #126530, and three files conflict with #129882. The resolution I measured is below; @groeneai, could you rebase with it?

ClickBench query (1-based) Master, median ms PR, median ms PR / master [95% CI]
Q26, hot 109 88 0.808 [0.790, 0.826]
Q26, first run 139 121 0.860 [0.832, 0.888]
Q15 (GROUP BY SearchEngineID, SearchPhrase), hot 229 233 1.016 [1.009, 1.024]
Q38 (GROUP BY Title), first run 50 55 1.072 [1.008, 1.141]

Q38 hot is unchanged. No other query is significantly slower in either metric; the geometric mean of the 43 ratios is 0.994 hot and 1.002 for the first run. Neither Q15 nor Q38 has a top-K filter, so this PR's bound is never set for them; I have not investigated them further. Q26's result, and every query's full result with ORDER BY/LIMIT removed, are identical to master's.

Conflict resolution

#129882 adds top_k_filter_column (the column of the __topKFilter step prepended to PREWHERE) in the same places where this PR adds top_k_string_sort_column. Keeping both resolves the conflicts:

  • MergeTreeWhereOptimizer.h/.cpp: optimize takes both parameters (each defaulting to {} in the declaration), and WhereOptimizerContext has both members. The step predicates in analyzeImpl and analyze end with:
    || isReadByTopKFilterOnly(conjunct, columns, where_optimizer_context.top_k_filter_column)
    || (where_optimizer_context.apply_string_filters_during_scan && isConditionSuitableForStringValueFilter(conjunct, where_optimizer_context))
    || isConditionRejectingEmptyTopKString(conjunct, where_optimizer_context));
    (info.columns instead of columns in analyzeImpl).
  • optimizePrewhere.cpp: keep both sides' additions; the call passes top_k_filter_column, top_k_string_sort_column.
  • Parquet/Reader.cpp: this PR's get_columns_written_to_cache() replaces master's equivalent inline block. Master now declares that vector as VectorWithMemoryTracking<bool> (Apply -WithMemoryTracking containers to src/Processors/Formats #126530). The measured build used this PR's std::vector<bool>; the rebase should keep master's type.

Master from b8c902a to f9e6c60 does not change the Parquet reader, PREWHERE or the ORDER BY ... LIMIT top-K filter, and adds no further conflicts.

Method and tests

Master b8c902a was compared with this PR's head 8e3b1d2 merged into it using the resolution above. Both are Release builds (clang 21, no LTO) on an r6i.8xlarge (Xeon 8375C). The server and client are pinned to cores 0-15, with max_threads = max_parsing_threads = 16, a minimal server config and the 100 files in the page cache.

For each round, query and build, the server was restarted and the query run 3 times, as in ClickBench: the first run is run 1 (the files stay in the page cache) and hot is the best of runs 2 and 3. Build order alternated between rounds. There were 8 rounds and the first was dropped. The table gives medians of the 7 paired rounds, with 95% Student-t intervals on the paired log ratios.

Using clickhouse local, the outputs of 116 MergeTree stateless .sql tests on the top-K dynamic filter and string filters, and of 99 Parquet stateless .sql tests, are identical to master's (03531 times out under both). I did not run this PR's 05490_parquet_top_k_string_decode_bound.sh.

…p-k-string-decode-bound

Resolve conflicts with ClickHouse#129882 and ClickHouse#126530: `optimize` takes both
`top_k_filter_column` and `top_k_string_sort_column`, the step predicates
keep both conditions, and `get_columns_written_to_cache` returns master's
`VectorWithMemoryTracking<bool>`.

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

Copy link
Copy Markdown
Collaborator Author

Resolved in f6803eb by merging master (.claude/CLAUDE.md asks for no rebase), using your resolution with master's VectorWithMemoryTracking<bool> in get_columns_written_to_cache.

This branch has not been deployed

No deployments
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

Projects

None yet

2 participants