Repository navigation
Speed up in-order LIMIT BY, DISTINCT, window functions, merge joins and FINAL on multi-column keys with long leading-key runs - #123808
Conversation
…eSorted overloads Checks the three multi-column overloads (columns, positions, SortDescription) against a row-by-row whole-key oracle for every begin and two range ends, on 2- and 3-column sorted keys with leading runs of 1, 7, 8, 9 and 600 rows and trailing runs of 1, 2, 7, 8, 9, 300 rows or unique values, over UInt64, UInt32, String, Nullable(String) with arbitrary nested values at NULLs, Float64 with NaN and -0.0/+0.0, and LowCardinality(String) with dictionary indices out of value order. Also the single-column and no-column paths. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The sorted-stream LIMIT BY, negative LIMIT BY and full_sorting_merge JOIN find every group with per-column narrowing: from the group's first row, column 0's run end is searched, then column 1 within it, and so on. They call it once per group, each call starting where the previous group ended, and nothing was remembered between calls. So when column 0 has long runs and a later column ends the groups early, column 0's whole remaining run was searched again for every group inside it (issue ClickHouse#123700: 18.9 String equality checks per row for 480-row leading runs with a unique second key, versus 2 comparisons per row before ClickHouse#106502). `SortedKeyRuns` remembers, for each key prefix, the last run found. Within a sorted range a search from a row inside that run ends the prefix's run at the same row, so column `i` is searched again only when the search leaves the run of columns `0..i`. Every per-column call it makes has exactly the arguments the stateless narrowing passes for that column from the same row; it only skips the calls for leading columns whose remembered run still contains the row, so results are identical and the per-column work is a subset of today's. A reuse checks both bounds of the remembered run, so any call order is correct. Keys of fewer than two columns take the stateless path unchanged. In debug and sanitizer builds every call is cross-checked against the full narrowing from the same row, so the sampled contiguity checks inside the per-column searches keep firing on the inputs they fire on today. The LIMIT BY transforms use one instance per chunk; the join cursor resets its instance in setChunk, the only writer of its key columns and row count. The stateless multi-column helper in SortCursor.h now shares the same narrowing loop. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The remembered runs use VectorWithMemoryTracking, as the style check requires for standard containers. Two perf-test arms cover the shape of issue ClickHouse#123700: LIMIT BY on a String key read in primary key order, and a full_sorting_merge join on a two-column UInt64 key, both with long runs of the leading column and every group ended by the second column. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…gative LIMIT BY perf arm The walk test now counts the per-column searches `findRunEnd` makes: column 0 must be searched once per run of column 0, and the walk must never search more than the stateless narrowing from the same rows. Debug and sanitizer builds cross-check every result through the same callback, so those calls are subtracted there. A `findRunEnd` that keeps nothing returns the same boundaries, so only the counts catch it. The five multi-column oracle tests become one loop over the shared list of key types. Performance tests: a negative `LIMIT BY` over two `String` key columns with long runs of the leading one, and the two-column `LIMIT BY` query reads a single sorted stream (`ORDER BY a, b`), so it measures the sorted-stream transform rather than the final hash `LIMIT BY`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eyRuns walk test In a forward walk, column `i` is searched only from the first row of a run of columns `0..i`, and the search stops after the first column whose run from that row is one row long. The walk test now derives the expected count of every column from the data and compares it with the searches `findRunEnd` makes, instead of checking column 0 only. A `findRunEnd` that reuses only column 0's run returns the same boundaries and passed before; it fails now on the 3-column keys, where the middle prefix's run is the one reused. The debug cross-check runs only for two or more columns, so its calls are subtracted only there. 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; 3 rounds: 1, 1 and 0 findings) plus my own review.
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-10:20261004-025400 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-41:20261003-234000 |
|
Workflow [PR], commit [f26ece3] Summary: ✅
AI ReviewSummaryThis PR introduces Final Verdict
LLVM Coverage ReportMeasured on commit f26ece3.
Changed lines: Changed C/C++ lines covered: 152/153 (99.35%) · Uncovered code |
|
Also do a scan for other locations where we can use |
Build profile diff (arm_release)Commit See the job log for details. |
|
📊 Cloud Performance Report ✅ AI verdict: I downgraded all four flagged improvements (clickbench Q33 -9.7% and Q34 -10.6%, tpch Q1 -16.9% and Q7 -24.7%) to not_sure, because none of these queries runs the code this PR changes. The PR caches multi-column sorted-run boundaries for merge joins, ReplacingMergeTree FINAL, DISTINCT/LIMIT BY on sorted input and window functions, while the flagged queries are hash aggregations or default hash joins. Both TPC-H PR medians sit inside master's recent range, which points to a slow baseline rather than a faster PR. To measure the PR's real effect, use the full_sorting_merge_join perf test it extends, especially the new two-key join query; these two benchmarks do not cover that code. clickbenchFlagged queries (2 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_officialFlagged queries (2 of 22)
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. Debug info
|
Extends SortedKeyRuns to the other callers that find the runs of one sorted range one after another with the multi-column narrowing search, where every group restarted the search on the leading key column (a gallop over the rest of its run): - DistinctSortedStreamTransform (DISTINCT in order) - WindowTransform peer groups: the RANGE/GROUPS frame end at CURRENT ROW and findPeerGroupEnd (GROUPS offset frames), one cache keyed on (block, end) shared by the frame boundaries; a single-column ORDER BY keeps the stateless search - SlidingIndexes::markKeyChanges (multi-column PARTITION BY boundaries) - MergeJoinCursor::getEqualLength (partial_merge join) - ReplacingSortedAlgorithm run skipping, one cache per source, invalidated on a new chunk or a new batch end The callers use new SortedKeyRuns-aware overloads of the multi-column getEqualRangeEndAssumeSorted in SortCursor.h; the LIMIT BY transforms switch to them too. SortedKeyRuns::findRunEnd is ALWAYS_INLINE: out of line it cost a few percent on keys with one-row leading runs. Measured on 20M rows sorted by (a String with runs of 20000, b String with runs of 4), RelWithDebInfo, interleaved, identical results: ReplacingMergeTree FINAL with enable_vertical_final = 0 0.44x, window ORDER BY a, b 0.73x, PARTITION BY a, b 0.81x, GROUPS frame 0.88x, DISTINCT a, b 0.83x, partial_merge join USING (a, b) 0.74x. With one-row or four-row leading runs the same queries stay within 0.99x-1.06x. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…Runs DISTINCT in order, window peer groups (RANGE and GROUPS frames), PARTITION BY boundaries, partial_merge join and ReplacingMergeTree FINAL without vertical FINAL, on a two-column String key with long runs of the leading column. Locally (5M rows, RelWithDebInfo, same results): 0.72x, 0.60x, 0.46x, 0.69x, 0.94x and 0.37x. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
I scanned the callers that walk the runs of a sorted range with the multi-column narrowing search, and all of them now use
That is on 20M rows sorted by two Left out, since they use a different search: |
CI finish ledger - b8e4af9Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261004-120236 |
|
@groeneai Fix conflicts. |
parallel_full_sorting_merge_join | 578.7 | 669.6 | +15.7% | amd | Uncertain | 1 | SELECT count() FROM pfsm_left AS a JOIN pfsm_right AS b ON a.k = b.k FORMAT Null SETTINGS join_algorithm = 'full_sorting_merge'This regression looks related. |
…-runs # Conflicts: # src/Processors/Transforms/Window/SlidingIndexes.cpp
parallel_full_sorting_merge_join ClickHouse#1 (full_sorting_merge on one UInt64 key) and window_function_with_order ClickHouse#3 got 10-20% slower: per row, the join called an out-of-line findKeyRangeEndAssumeSorted, and the window code called out-of-line copies of the SortedKeyRuns overloads and WindowTransform::findPeerRunEnd, where master inlined the stateless search. - force-inline findKeyRangeEndAssumeSorted, the SortedKeyRuns overloads in SortCursor.h and findPeerRunEnd; - the SortedKeyRuns overloads take the stateless search for one-column keys; - the peer-group marking of SlidingIndexes (new in master) uses one SortedKeyRuns per block instead of resetting it for every partition, which called vector::assign per partition. The partitions are searched in order and none starts inside an earlier one, so no stale run can be reused; the reset contract is stated precisely. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Merged master: the only conflict was The Release builds, interleaved, n=40, median against master: |
Take the multi-column sorted key run reuse for LIMIT BY, negative LIMIT BY, DISTINCT in order, full_sorting_merge and partial_merge JOIN. Skip the WindowTransform changes (reverted on master by #124640) and the ReplacingSortedAlgorithm run skipping (needs the batch sorting queue, absent in 26.8). Fixes the LIMIT BY regression from #106502 reported in #123700
Take the multi-column sorted key run reuse for LIMIT BY, negative LIMIT BY, DISTINCT in order, full_sorting_merge and partial_merge JOIN. Skip the WindowTransform changes (reverted on master by #124640) and the ReplacingSortedAlgorithm run skipping (needs the batch sorting queue, absent in 26.9). Fixes the LIMIT BY regression from #106502 reported in #123700
Cherry pick #123808 to 26.8: Speed up in-order LIMIT BY, DISTINCT, window functions, merge joins and FINAL on multi-column keys with long leading-key runs
…w functions, merge joins and FINAL on multi-column keys with long leading-key runs
Cherry pick #123808 to 26.9: Speed up in-order LIMIT BY, DISTINCT, window functions, merge joins and FINAL on multi-column keys with long leading-key runs
…w functions, merge joins and FINAL on multi-column keys with long leading-key runs
Backport #123808 to 26.8: Speed up in-order LIMIT BY, DISTINCT, window functions, merge joins and FINAL on multi-column keys with long leading-key runs
Backport #123808 to 26.9: Speed up in-order LIMIT BY, DISTINCT, window functions, merge joins and FINAL on multi-column keys with long leading-key runs
- Resolve the `TODO: wait for the revert-of-revert.` on #123808: #124640 reverted only its `WindowTransform` part and no re-apply is planned, so the window functions are dropped from the entry instead. - Sort every category by significance, clustering related entries. - Move 21 entries between categories (efficiency entries to `Performance Improvement`, user-visible failures to `Bug Fix`, usability changes out of `Bug Fix`, new SQL surface to `New Feature`). - Merge 28 groups of entries describing the same feature or fix, including regressions of this release folded into the feature they broke. - Rewrite entries that described internal classes instead of the user-visible effect, and fix backticks and formatting. - Drop two pure CI/test-build entries from `Build/Testing/Packaging Improvement` (#123180, #125593). Related: #120500 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@groeneai This logical error possibly introduced by this PR. SELECT count() FROM (SELECT k FROM (SELECT number % 100 AS k FROM numbers(1000) ORDER BY k WITH FILL TO 65536) LIMIT 3 BY k);Create a PR to fix it. |
|
This is not from #123808. The same assertion fires on The input to That is the class the open #112650 fixes ("Reject WITH FILL bounds that do not fit the ORDER BY column type"). On its CI debug build ( |
Closes: #123700
Related: #106502
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Faster sorted-stream processing on a multi-column key whose leading column has long runs, in
LIMIT BY, negativeLIMIT BY,DISTINCTin order, window functions (peer groups andPARTITION BYboundaries),full_sorting_mergeandpartial_mergeJOIN, andReplacingMergeTreeFINALwithout verticalFINAL: the run of a key prefix is now found once instead of again for every group in it. The query from #123700 is about 3.5x faster.Description
Since #106502, the sorted-stream
LIMIT BY, negativeLIMIT BYandfull_sorting_mergeJOIN find each group with per-column narrowing: from the group's first row, the end of column 0's run is searched, then column 1 within it, and so on. Nothing is kept between groups, so when column 0 has long runs and a later column ends the groups early, column 0's remaining run is searched again for every group in it (18.9Stringcomparisons per row on the issue's data, against 2 before #106502). The other callers of that search pay the same cost.SortedKeyRunsremembers the last run found for each key prefix, so a column is searched again only when the walk leaves its prefix's run. It never makes more per-column calls than the stateless search and reuses a run only for a row inside it, so results are identical; one-column keys keep the old path. Debug and sanitizer builds check every call against the full search. Users: theLIMIT BYtransforms,DISTINCTin order, window peer groups andPARTITION BYboundaries, thefull_sorting_mergeandpartial_mergejoin cursors, and the run skipping ofReplacingSortedAlgorithm(one per source, reset on a new chunk or batch end).Validation (RelWithDebInfo, base vs fix from the same config, results identical):
LIMIT -1 BY0.55x; numeric keys 0.35x;full_sorting_mergeself join 0.46x(a, b), leading runs of 20000:ReplacingMergeTreeFINALwithenable_vertical_final = 00.44x, windowORDER BY a, b0.73x,GROUPSframe 0.88x,PARTITION BY a, b0.81x,DISTINCT0.83x,partial_mergejoin 0.74x🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/123808]
Version info
26.10.1.1837-master(included in26.10and later)26.9.15.4,26.8.23.4