Skip to content

Skip Parquet row groups that start at the top-K threshold when ORDER BY has one column - #124195

Open
groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:parquet-top-k-single-sort-column-ties
Open

groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:parquet-top-k-single-sort-column-ties

Conversation

@groeneai

@groeneai groeneai commented Oct 6, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #124164

Changelog category (leave one):

  • Performance Improvement

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

ORDER BY x LIMIT n over Parquet files with a single sort column now also skips row groups whose minimum (maximum for DESC) equals the current top-K threshold. This speeds up queries where many row groups share the smallest (largest) value, such as ORDER BY EventDate LIMIT 10 on ClickBench hits.parquet.

Description

Analysis and patch by @ snelheidai (#124164).

TopN dynamic filtering skipped a Parquet row group by its statistics only when its minimum (maximum for DESC) was strictly past the top-K threshold. With several sort columns a row equal to the threshold can still win on a later column. With one it cannot: every published threshold is backed by limit rows that sort no later than it, so an equal row can only replace an equal row (WITH TIES never takes this path). The planner now tells the format whether there is a single sort column, and topKShouldSkipRowGroup then compares strictly, unless a cloned object storage read shares the threshold with another copy.

Such a row group can hold rows equal to the n-th value, so the TopK query condition cache counts it as matched, with the bound of its statistics as its best value: it is still cached as empty when that bound is strictly past the final threshold. Without this, after 16 overlapping ORDER BY k LIMIT 1 reads of 16 files the next read returned no row in 5 of 100 cycles (0 of 120 with it).

Release build, ClickBench hits.parquet (226 row groups), geomean time fix/base [95% CI], 4 threads:

  • ORDER BY EventDate LIMIT 10: row groups read (one thread) 42 -> 1, 0.80 [0.75, 0.84]
  • ORDER BY EventDate DESC LIMIT 10: 26 -> 1, 0.92 [0.88, 0.97]
  • ORDER BY WatchID, ORDER BY EventDate, UserID: unchanged
  • parquet_top_k_row_group_order.xml, ORDER BY m LIMIT 10: 191 of 200 row groups skipped instead of 0, 0.35 [0.33, 0.36]

The test checks rows read with one and two sort columns, 11 queries against the unoptimized result, that a rerun over a File table skips the same row groups and none through the cache, and a cloned s3 read.

🤖 Generated with Claude Code


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

groeneai and others added 2 commits October 6, 2026 09:20
…BY has one column

TopN dynamic filtering over Parquet skipped a row group by its statistics
only when its minimum (maximum for DESC) was strictly past the running top-K
threshold. The comparison is non-strict because with several ORDER BY
columns a row equal to the threshold on the first column can still win on a
later column. With a single ORDER BY column it cannot: every published
threshold is backed by at least `limit` rows already in the sort whose key
sorts no later than it (PartialSortingTransform publishes row `limit - 1` of
a sorted block with at least `limit` rows, MergeSortingTransform publishes
after a remerge to exactly `limit` rows), so a row equal to the threshold can
only replace an equal row and the ORDER BY values of the result do not
change. WITH TIES never reaches this path.

When many row groups share the minimum of the file (e.g. ClickBench
`ORDER BY EventDate LIMIT 10`), every one of them used to be read in full.

`tryTopKForFormatSource` now passes the number of sort columns to the format
(`FormatTopKFilterInfo::single_sort_column`), and `topKShouldSkipRowGroup`
uses the new `TopKThresholdTracker::isValueStrictlyInsideThreshold` for a
single sort column. Multi-column sorts, the per-row `__topKFilter` and the
MergeTree paths are unchanged (MergeTree's `getTopKMarks` already ignores
ties for one sort column).

The perf test `parquet_top_k_row_group_order` gets an `ORDER BY m, k` control
query; its existing `ORDER BY m` query is the one this change speeds up.

Analysis and patch by snelheidai in ClickHouse#124164.

Closes ClickHouse#124164

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the duplicated field comment on single_sort_column; keep the why of the strict comparison once, in topKShouldSkipRowGroup.

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 6, 2026
@groeneai

groeneai commented Oct 6, 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; 0 findings) plus my own cold review (4 nits).

# Sev Finding Verdict Evidence / action
1 💡 PR description implied full MergeTree parity; MergeTree's mark skipping by the threshold during the read (canSkipMark) stays non-strict AGREE, fixed in the description only getTopKMarks ignores ties for one sort column
2 💡 Changelog entry described only the payoff case (threshold equal to the file's extreme value) AGREE, fixed in the description the threshold is the running top-K value
3 💡 isValueStrictlyInsideThreshold duplicates isValueInsideThreshold except for equality AGREE, not blocking 7 lines next to its sibling, same locking
4 💡 FormatTopKFilterInfo::single_sort_column comment says an equal row "cannot enter" the top-K; precise is "cannot change the result" AGREE, fixed comment removed in the pre-publish comment trim

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-9:20261006-100100

@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0b09b8b]

Summary: ✅


AI Review

Summary

PR #124195 lets single-column ORDER BY ... LIMIT queries skip Parquet row groups whose statistics bound equals the running top-K threshold. It also protects query-condition-cache entries for tied groups and retains non-strict comparisons when cloned reads share a threshold. Review of head 0b09b8b64636e7578e1cdd2dd5817e22bca7b0ab, including the prior discussion, found no actionable findings. The PR supplies focused regression coverage and before/after performance measurements. No local build or tests were run.

Final Verdict

Status: ✅ Approve

@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0b09b8b64 with master dde6a0d9f (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.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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
  • StressHouse run: fbefdea9-fe57-4630-b615-041a4fecce71
  • MIRAI run: e08483c0-7101-4f52-8ad2-6fab8e5391a1
  • PR check IDs:
    • clickbench_779977_1791667672
    • clickbench_779983_1791667672
    • clickbench_779989_1791667672
    • tpch_adapted_1_official_780002_1791667672
    • tpch_adapted_1_official_780012_1791667672
    • tpch_adapted_1_official_780047_1791667672

@al13n321
al13n321 removed their request for review October 29, 2026 16:44
@snelheidai

Copy link
Copy Markdown

@groeneai The strict skip here needs the query-condition-cache fence you added for MergeTree in #125122: with the TopK cache now on master, overlapping runs can make later runs return wrong results.

Since #122064, a TopK read of a Parquet File table records, under a TopK key, the row groups that returned no row (StorageFile.cpp#L2488-L2497); file() and data lake tables do the same since #122127 and #124808 (StorageObjectStorageSource.cpp#L1206-L1212). This relies on __topKFilter keeping ties (L2472-L2475): such a row group, like one whose best value is strictly beyond the final threshold (L1853-L1856), holds no row of any run's result.

With this PR (Reader.cpp#L514-L515), a row group whose min (max for DESC) equals the threshold is skipped. It returns no rows, so getMatchedBuckets leaves it unmatched (ParquetV3BlockInputFormat.cpp#L442-L443; only statistics-only reads count skipped_by_top_k) and it is recorded, although it can hold rows equal to the n-th value. QueryConditionCache::write only clears bits (QueryConditionCache.cpp#L363-L365), so entries accumulate across runs. Sequential reruns stay correct, because each reads the row groups that produced the previous result. Overlapping runs that keep different tied row groups can mark all of them; later runs then return fewer than n rows or values past the true n-th one. This is the MergeTree failure you reproduced in #125122 (16 concurrent ORDER BY s LIMIT 1: 0 rows in 19/20 cycles).

The TopK key exists without WHERE (L2880-L2881), and use_query_condition_cache and use_query_condition_cache_for_top_k are on by default, so #124164's ORDER BY EventDate LIMIT 10 on File(Parquet) takes this path. #124164 was measured before #122064, when no TopK entries were written, so its "the ORDER BY values of the result cannot change" now needs this fence.

Smallest fences:

  1. Count a row group skipped by the new equality branch as matched: a flag next to skipped_by_top_k, checked in getMatchedBuckets as Skip Parquet row groups by statistics for a String ORDER BY key without the per-row filter #124827 does for statistics-only reads. Both cache writers use getMatchedBuckets, so this covers File, file() and data lakes. If you also report its min (max) as its best value, the existing final-threshold check still records it as empty when that value sorts strictly beyond the final threshold.
  2. Or, as in Use the top-K dynamic filter for ORDER BY of a single String column on MergeTree #125122, write no TopK entry for a file where such a skip happened. That is coarser: the file then records nothing, including row groups emptied by WHERE.

Test: the wrong result needs overlapping runs, so a deterministic check of the fence fits better, like 05355's "no cache entries after dropping ties" pair. Over 05333's file as a File table, with use_query_condition_cache = 1 and one thread, run ORDER BY k LIMIT 3 twice. With a fence, both runs have the same nonzero ParquetTopKSkippedRowGroups, and the rerun has no QueryConditionCacheHits; without one, the rerun skips those row groups through the cache. The cache ignores a file modified less than 3 s earlier.

This is source-derived (master a7f7136, this PR at d7d4200); I have not reproduced it on Parquet.

groeneai and others added 4 commits October 31, 2026 18:41
…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]>
With one sort column the threshold now skips the row groups of
`parquet_top_k_best_value` whose minimum equals it, so its queries no
longer record the best value over almost every row (measured on 40 row
groups: 30 skipped, 9.4M of 40M rows read). Add the same queries with a
second sort column, which keep the non-strict comparison and read every
row group. Also document in `IInputFormat` that a bucket skipped by the
threshold reports the bound of its statistics as its best value.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A cloned `ReadFromObjectStorageStep` shares the threshold tracker with the
other copy, as `SortingStep::clone` does, so the threshold can come from the
sort of the other copy, which this read has not yet given enough rows that
sort no later than it. With a correlated subquery read without the
in-memory buffer, the strict comparison then skipped every row group of the
second copy: `sum(n)` was NULL instead of 9.

Mark the tracker as shared by plan copies on clone, as `ReadFromMergeTree`
does, and compare strictly only while it is not shared, as `__topKFilter`
does for MergeTree.

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

Copy link
Copy Markdown
Collaborator Author

Reproduced (after 16 overlapping reads, the next one returned no row in 5 of 100 cycles) and fixed with your fence 1 in e3d4bff; 74b8a36 also keeps the comparison non-strict for a cloned object storage read, which shares the threshold.

@snelheidai

Copy link
Copy Markdown

@groeneai When #124899 is merged too, fence 1 (e3d4bff) misses one case: a tied row group that #124899's late skip stops after it has returned some rows is recorded as empty in the TopK cache entry. Neither PR alone is affected. In this PR alone, every skip (admission and OffsetIndex) happens before any subgroup is read; without this PR, the late skip is non-strict, so a row group it stops has all its rows strictly beyond the final threshold.

Example with ORDER BY k LIMIT n:

  1. A row group whose statistics min is 5 returns its first subgroup, all with k >= 6; it is queued for delivery before the next subgroup starts (ReadManager.cpp#L615-L629).
  2. Rows from other row groups bring the threshold to 5.
  3. skipIfExcludedByTopK (L202-L213, called per subgroup from L1139-L1140 and L1350-L1351) uses this PR's strict check for one sort column (Reader.cpp#L637-L638), so it drops the next subgroup, which holds k = 5, and sets skipped_by_top_k.
  4. The group is matched, since it returned rows. getTopKBestValuesOfBuckets (ParquetV3BlockInputFormat.cpp#L460-L467) reports the statistics bound only if no best value was folded from returned rows (ReadManager.cpp#L1594-L1595), so it reports 6.
  5. If the final threshold is 5, both writers erase the group (StorageFile.cpp#L1853-L1856, StorageObjectStorageSource.cpp#L417-L420), although it holds rows equal to the n-th value.

This is the record fence 1 prevents for a tied group that returned nothing, so overlapping runs can again mark every tied row group as empty.

Smallest fix: in getTopKBestValuesOfBuckets, report the bound for every skipped row group, before the folded best value.

--- a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp
+++ b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp
@@ -457,14 +457,15 @@
     {
         if (!row_group.need_to_process)
             continue;
-        if (row_group.top_k_best_value)
-            res.emplace_back(row_group.row_group_idx, (*row_group.top_k_best_value)[0]);
-        else if (row_group.skipped_by_top_k.load() && row_group.top_k_sort_column_range)
+        /// A row group can be skipped after returning some rows; only the bound also covers the skipped ones.
+        if (row_group.skipped_by_top_k.load() && row_group.top_k_sort_column_range)
         {
             const Range & range = *row_group.top_k_sort_column_range;
             const bool ascending = format_filter_info->top_k_filter->threshold_tracker->getDirection() == 1;
             res.emplace_back(row_group.row_group_idx, ascending ? range.left : range.right);
         }
+        else if (row_group.top_k_best_value)
+            res.emplace_back(row_group.row_group_idx, (*row_group.top_k_best_value)[0]);
     }
     return res;
 }

The bound sorts no later than any row of the group, so a group is still recorded as empty only when all its rows sort strictly beyond the final threshold. With this PR alone the change is a no-op, because a marked group has returned nothing and so has no folded best value; it can therefore land here whichever PR merges first.

This corrects my #124899 comment: the mark keeps a late skip of a tied row group from bypassing your fence "in either merge order" only if the group returned no row.

No test is proposed. The partial skip needs other rows to bring the threshold to the group's min between two of its subgroups, a scheduling race for which I found no cheap deterministic shape.

From source only, not reproduced: this PR at 74b8a36, #124899 at 335dacd, master at 22a323d.

With one sort column the top-K threshold skips a Parquet row group whose
minimum (maximum for DESC) equals it. A skip that happens after the row
group has already returned some rows (the per-subgroup recheck of ClickHouse#124899)
kept the best value of the returned rows as the row group's best value, so
the TopK query condition cache recorded the row group as empty whenever
that value sorts past the final threshold, although the unread rows may
equal it. Overlapping runs can then mark every tied row group, and a later
run returns no row. Report the bound of the statistics first: it sorts no
later than any row of the row group.

On this branch alone a skipped row group has returned no rows, so this
changes nothing until ClickHouse#124899 is merged too.

Measured with ClickHouse#124899's ReadManager change applied (debug build): two
Parquet files whose only k = 0 row is in the last row subgroup, 16
overlapping `ORDER BY k LIMIT 1` reads, then one more read. Before: no row
in 22 of 30 cycles through file(), 1 of 40 with a File table. After: 0 of
60 and 0 of 40.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A Nullable key is compared by the generic threshold tracker, whose strict
comparison is a separate implementation from the numeric one. Reading the
file with a `Nullable(UInt64)` structure covers it: with that comparison
made non-strict, both new queries read 1095 rows instead of 1005, and the
existing `UInt64` ones are unaffected.

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

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Reproduced with #124899's change applied (after 16 overlapping reads, the next one returned no row in 22 of 30 cycles through file(), 0 of 60 with the change) and applied your reorder in 93d5be2.

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. groeneai-origin-issue PR origin: picked up an external GitHub issue pr-performance Pull request with some performance improvements

Projects

None yet

3 participants