Repository navigation
Read Parquet row groups in sort-key order for ORDER BY ... LIMIT - #123639
alexey-milovidov merged 6 commits into
Conversation
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]>
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.
Severity: ❌ blocker / 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 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20261002-172600 |
|
Workflow [PR], commit [75e9a7c] Summary: ✅
AI ReviewSummaryThis PR makes Findings❌ Blockers
Final Verdict
LLVM Coverage ReportMeasured on commit 75e9a7c.
Changed lines: Changed C/C++ lines covered: 126/128 (98.44%) · Uncovered code |
|
|
||
| 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)) |
There was a problem hiding this comment.
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]>
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (1 of 43)
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
|
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes8 object files changed (+41.69 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units18 translation units recompiled, 156 s compile time in total, 18 of them have a recent master baseline. |
alexey-milovidov
left a comment
There was a problem hiding this comment.
This is a great idea!
Closes: #123564
Related: #115798
Related: #117017
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
ORDER BY ... LIMITover a singleParquetfile 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 10skips 207 of its 226 row groups at 4 threads. New profile eventParquetTopKSkippedRowGroups.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::initstarted 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.tryOptimizeTopKarmed format sources before thedependsOnItsBlockguard (e.g.WHERE rowNumberInAllBlocks() % 3 = 0below 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):ORDER BY UserID DESC LIMIT 10SearchPhrase <> '' ORDER BY EventTimeDESCORDER BY ResolutionWidth(unprunable)At 16 threads: 0.54-0.76; with more parsing threads than row groups only the order helps. ClickBench's
DateTimeschema also needs #117017 forEventTime.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
26.10.1.1430-master(included in26.10and later)