Skip to content

Read Parquet row groups in sort-key order for ORDER BY ... LIMIT - #123639

Merged
alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/parquet-top-k-row-group-order
Oct 3, 2026
Merged

alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/parquet-top-k-row-group-order

Conversation

@groeneai

@groeneai groeneai commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #123564
Related: #115798
Related: #117017

Changelog category (leave one):

  • Performance Improvement

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

ORDER BY ... LIMIT over a single Parquet file reads first the row groups whose min/max statistics are best for the result, so the top-K threshold skips the other row groups: SELECT URL FROM file('hits.parquet') ORDER BY UserID DESC LIMIT 10 skips 207 of its 226 row groups at 4 threads. New profile event ParquetTopKSkippedRowGroups.

Description

Proposed by @ snelheidai in #123564 (analysis and patch); numbers below are mine.

TopN filtering for Parquet (#115798) skips a row group whose statistics prove it holds no result row, but checks only when the row group starts, and ReadManager::init started all of them before the sort published a threshold: inside one file nothing was skipped.

Change. When the read order is free, row groups are ordered by the sort column's min (ASC) or max (DESC) and started gradually: at most max(parsing threads, started / 2) in flight, each checked against the latest threshold right before it starts. Skips do not raise the allowance, so an unprunable scan converges to unthrottled.

tryOptimizeTopK armed format sources before the dependsOnItsBlock guard (e.g. WHERE rowNumberInAllBlocks() % 3 = 0 below the sort) that only the MergeTree branch had; it now covers both, plus a block-dependent row policy for formats, which apply it after the threshold filter.

Measured (release, clickhouse local, 4 threads, hits.parquet, median of 11 alternating runs, identical results):

Query Before After Skipped
ORDER BY UserID DESC LIMIT 10 417 ms 246 ms 207/226
SearchPhrase <> '' ORDER BY EventTime 670 ms 263 ms 189
same, DESC 727 ms 198 ms 205
ClickBench q24 1422 ms 622 ms 184
ORDER BY ResolutionWidth (unprunable) 203 ms 207 ms 0

At 16 threads: 0.54-0.76; with more parsing threads than row groups only the order helps. ClickBench's DateTime schema also needs #117017 for EventTime.

Validation. New test 05317_parquet_top_k_row_group_order: rows_read (fails on the old binary), equality with the optimization off, and the block-dependence and row-policy cases (each fails without its guard). Perf test added.

🤖 Generated with Claude Code


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

Version info

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

groeneai and others added 5 commits October 2, 2026 20:07
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]>
Assert the new profile event for ascending and descending order with the
optimization on, and that it stays 0 with it off. Make the perf fixture
deterministic.

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

With the setting, ORDER BY ... LIMIT reads the row groups in file order, so
the top-K threshold skips none of them in the single-threaded fixture.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With the reorder, the first row group read holds the whole top-K, so only
its 1000 rows pass the in-reader threshold filter. In file order the first
row group read is another one, whose rows all pass before any threshold
exists, so the old bound of 3000 rows could not tell the two apart.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the admitTopKRowGroups comment line that restates the allowance expression below it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-issue PR origin: picked up an external GitHub issue labels Oct 3, 2026
@groeneai

groeneai commented Oct 3, 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; 4 rounds, 6 findings) plus my own review.

# Sev Finding Verdict Evidence / action
1 ⚠️ New ParquetTopKSkippedRowGroups event is not asserted by any test AGREE, fixed @ 98ea2b2 05317 checks it for ASC/DESC (17..20 of 20 skipped) and 0 with the optimization off
2 ⚠️ No multi-thread reduced-work assertion DISAGREE with N threads every admission races the sort's threshold publication (8 threads: 15000/14000 of 20000 rows read locally), so any bound is vacuous or flaky; the 1-thread arm is deterministic, the perf test measures the multi-thread effect
3 💡 Perf fixture used rand64() AGREE, fixed @ 98ea2b2 sipHash64(number)
4 ⚠️ The input_format_parquet_preserve_order = 1 arm compares results only, so it stays green without the guard that keeps the file order AGREE, fixed @ 6141b33 05317 checks that with the setting the single-file read skips nothing; red with the guard deleted
5 ⚠️ The ascending rows_read bound (3 row groups) also holds when the row groups are read in file order AGREE, fixed @ 0ff4884 bound tightened to the rows of one row group; with the sort deleted 2000 (ASC) / 5000 (DESC) rows are read and both lines turn red
6 ⚠️ The block-dependence guard does not refuse functions with hasObservableSideEffects (sleepEachRow below the sort runs on fewer rows with TopK) DISAGREE the property is read only by the join merge gate by design (9c18bdc), and evaluating sleepEachRow only on the rows that can reach the result is the direction 01834_alias_columns_laziness_filimonov expects; results are identical. The MergeTree TopK branch, unchanged here, behaves the same way

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

Session id: cron:clickhouse-review-slot-10:20261002-201900, cron:clickhouse-review-slot-8:20261002-230800, cron:clickhouse-review-slot-8:20261002-234300, cron:clickhouse-review-slot-8:20261003-002000

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 20 row groups of 1000 rows with disjoint k ranges, 1 thread: SELECT k FROM file('t.parquet') ORDER BY k LIMIT 3 reads 20000 rows on master and 1000 with the change (same for DESC).
b Root cause explained? Yes. The only TopN row-group check runs when a row group starts, and ReadManager::init started all row groups before the sort published a threshold; with prefilter work they still started in file order.
c Fix matches root cause? Yes. Row groups are started in sort-key order and gradually, each checked against the latest threshold right before it starts. No new setting, the skip predicate is unchanged.
d Test intent preserved / new tests added? Yes. New 05317_parquet_top_k_row_group_order (rows read, equality with the optimization off, block-dependent function and row policy below the sort), perf test parquet_top_k_row_group_order. Existing 05025, 05137 unchanged and green.
e Both directions demonstrated? Yes. The new test fails on master only on the rows_read lines; removing the planner guard (whole, or only its row-policy term) reddens exactly the matching cases.
f Fix is general across code paths? Yes. Both skip sites count the new profile event; the block-dependence guard of tryOptimizeTopK now covers format sources like MergeTree, plus a block-dependent row policy, which the Parquet reader applies after the threshold filter.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. ASC/DESC, NULLS FIRST with nullable chunks, multi-column ORDER BY, OFFSET across row groups, WHERE/PREWHERE/IN, String keys, preserve_order = 1, 1-64 threads and tiny memory watermarks: results equal with the optimization off. Floats, UUID and collations get no range and keep the old path.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; only the order of row groups when the output order is free. New profile event only.
i Invariants and contracts preserved? Yes. Row groups start in order, so the first incomplete row group is always started or every started one is done; the read path's memory and task leak checks pass in debug and TSan builds (50/50 runs of the new test, no TSan reports).

Session id: cron:clickhouse-impl-slot-4:20261002-172600

@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [75e9a7c]

Summary: ✅


AI Review

Summary

This PR makes ORDER BY ... LIMIT over a single Parquet file much more effective by reordering row groups by sort-key statistics and admitting them gradually so the running top-K threshold can prune later groups. The overall design looks good and the new stateless/perf coverage is solid, but one correctness guard in the planner is still too weak: the format-source path can still enable the optimization across evaluation-sensitive DAGs that the new row-group reordering changes semantically.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/Optimizations/optimizeTopK.cpp:240] [dismissed by author -- https://github.com/Read Parquet row groups in sort-key order for ORDER BY ... LIMIT #123639#discussion_r4171069830] The new format-source guard still relies on dependsOnItsBlock, which only scans top-level DAG nodes and only checks isStateful() / !isDeterministicInScopeOfQuery(). It still misses evaluation-sensitive functions hidden inside lambda sub-DAGs and ignores hasObservableSideEffects(), so TopK can still be pushed below a WHERE / PREWHERE / expression / row-policy DAG whose behavior changes when earlier rows are pruned. That makes the optimization change query semantics or observable behavior instead of being a pure performance win. Suggested fix: use QueryPlanOptimizations::isSensitiveToEvaluationCount for these guards in the format-source path (keeping the existing arrayJoin checks), and add a focused regression where the sensitive function is hidden behind a lambda or other nested DAG. I still consider this real after the dismissal because sleepEachRow is only the side-effect example; the unresolved correctness part is that nested evaluation-sensitive functions are still invisible to dependsOnItsBlock, while isSensitiveToEvaluationCount already exists specifically to walk those nested DAGs.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions: strengthen the format-source guard to reject evaluation-sensitive DAGs with isSensitiveToEvaluationCount (not just top-level dependsOnItsBlock), keep the existing arrayJoin exclusions, and add one focused regression covering the nested-DAG case that the current guard misses.

LLVM Coverage Report

Measured on commit 75e9a7c.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.80% 92.10% +0.30%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 126/128 (98.44%) · Uncovered code

Full report · Diff report


const auto * source_step = dynamic_cast<const SourceStepWithFilterBase *>(node->step.get());
const auto prewhere_info = source_step ? source_step->getPrewhereInfo() : nullptr;
const bool actions_depend_on_block = (prewhere_info && dependsOnItsBlock(prewhere_info->prewhere_actions))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This guard is still too weak for the new format-source path. dependsOnItsBlock only scans actions.getNodes() and only checks isStateful() / !isDeterministicInScopeOfQuery(), so it misses evaluation-sensitive functions hidden inside lambda sub-DAGs and also ignores hasObservableSideEffects() (for example sleepEachRow). That means TopK can still be pushed ahead of a PREWHERE / WHERE / expression / row-policy DAG whose behavior changes when earlier rows are pruned. We already have QueryPlanOptimizations::isSensitiveToEvaluationCount in Optimizations/Utils.{h,cpp} for exactly this case; please use that here (and keep the existing arrayJoin checks alongside it).

Build (arm_tidy) failed on cppcoreguidelines-init-variables at
ReadManager.cpp:120. The value is always assigned under the admission
mutex before it is read, so there is no behavior change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-parquet-reader-v3 Issues related to the native Parquet reader. label Oct 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 32 queries analysed

No query shows a confirmed regression or improvement. The only flagged query, clickbench Q28 at -6.2%, stays not_sure: the two tests disagree, and the source measurements were noisy. The PR changes only the Parquet reader, which now reads row groups in order of the ORDER BY column's min/max statistics and admits them gradually. It also moves the MergeTree TopK block-dependency check without changing its behavior, so ClickBench and TPC-H queries on MergeTree tables should not be affected. The PR's real effect should appear in the new parquet_top_k_row_group_order performance test, which neither benchmark suite runs.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1106 1038 -6.2% <0.0001 This PR changes only Parquet row-group ordering for ORDER BY ... LIMIT and refactors the MergeTree TopK check with the same behavior. This ClickBench query reads MergeTree and sorts after aggregation, so the -6.2% is not attributable to this PR.

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: f4963c8d-0462-4218-be18-e9ecf7a21907
  • MIRAI run: 87a25fbb-44d0-48c5-b79a-194f97f8a595
  • PR check IDs:
    • clickbench_3005071_1790999818
    • clickbench_3005080_1790999818
    • clickbench_3005089_1790999818
    • tpch_adapted_1_official_3005115_1790999818
    • tpch_adapted_1_official_3005130_1790999818
    • tpch_adapted_1_official_3005144_1790999818

@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 75e9a7c61 with master bd202925d (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

8 object files changed (+41.69 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/Parquet/Reader.cpp.o 728.69 KiB 766.87 KiB +38.18 KiB (+5.24%)

719 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.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is a great idea!

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. groeneai-origin-issue PR origin: picked up an external GitHub issue 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