Skip to content

Speed up in-order LIMIT BY, DISTINCT, window functions, merge joins and FINAL on multi-column keys with long leading-key runs - #123808

Merged
nihalzp merged 9 commits into
ClickHouse:masterfrom
groeneai:limit-by-sorted-key-runs
Oct 8, 2026
Merged

nihalzp merged 9 commits into
ClickHouse:masterfrom
groeneai:limit-by-sorted-key-runs

Conversation

@groeneai

@groeneai groeneai commented Oct 4, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #123700
Related: #106502

Changelog category (leave one):

  • Performance Improvement

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, negative LIMIT BY, DISTINCT in order, window functions (peer groups and PARTITION BY boundaries), full_sorting_merge and partial_merge JOIN, and ReplacingMergeTree FINAL without vertical FINAL: 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, negative LIMIT BY and full_sorting_merge JOIN 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.9 String comparisons per row on the issue's data, against 2 before #106502). The other callers of that search pay the same cost.

SortedKeyRuns remembers 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: the LIMIT BY transforms, DISTINCT in order, window peer groups and PARTITION BY boundaries, the full_sorting_merge and partial_merge join cursors, and the run skipping of ReplacingSortedAlgorithm (one per source, reset on a new chunk or batch end).

Validation (RelWithDebInfo, base vs fix from the same config, results identical):

  • issue query: 1.080 s -> 0.309 s; negative LIMIT -1 BY 0.55x; numeric keys 0.35x; full_sorting_merge self join 0.46x
  • 20M rows sorted by (a, b), leading runs of 20000: ReplacingMergeTree FINAL with enable_vertical_final = 0 0.44x, window ORDER BY a, b 0.73x, GROUPS frame 0.88x, PARTITION BY a, b 0.81x, DISTINCT 0.83x, partial_merge join 0.74x
  • one-row or four-row leading runs, single key, dependent keys: 0.96x to 1.06x
  • unit tests against a whole-key oracle and per-column call counts; performance tests for every user

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.1837-master (included in 26.10 and later)
  • Backported to: 26.9.15.4, 26.8.23.4

groeneai and others added 5 commits October 3, 2026 22:55
…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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 4, 2026
@groeneai

groeneai commented Oct 4, 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: 1, 1 and 0 findings) plus my own review.

# Sev Finding Verdict Evidence / action
1 ⚠️ The SortedKeyRuns tests compared returned boundaries only, so a version that caches nothing passed them; no multi-column negative LIMIT BY performance query AGREE, fixed @ 0eaaf3e per-column call counts in the walk test, live under result-preserving mutations; new two-column negative LIMIT BY performance query
2 ⚠️ The call counts were exact only for column 0, so a version that reuses only the leading column's run still passed AGREE, fixed @ f36cc8e exact expected count for every key column; a mutation that reuses only column 0 now fails on the 3-column keys
3 💡 The new LIMIT BY performance query had no ORDER BY, so the final hash LimitByTransform dominated it AGREE, fixed @ 0eaaf3e the query now uses ORDER BY a, b

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

Session id: cron:clickhouse-review-slot-10:20261004-025400

@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The issue query (ORDER BY c1, c2, c5 DESC LIMIT 1 BY c1, c2, String keys, 12M rows, one part) in clickhouse local, RelWithDebInfo base vs fix from one config, interleaved: 1.080 s vs 0.309 s (n=7, no overlap). perf (LBR): LimitBySortedStreamTransform 2611 vs 390 samples, ColumnString::getEqualRangeEndAssumeSorted 2313 vs 174.
b Root cause explained? The sorted-stream operators find each group by per-column narrowing and search once per group with nothing kept between groups, so with long runs of column 0 and groups ended by a later column, column 0's remaining run is searched again for every group in it (18.9 String comparisons per row on the issue data, 2 before #106502).
c Fix matches root cause? Yes. SortedKeyRuns keeps the last run of each key prefix during a walk, so column 0 is searched once per its own run. No setting, bound or tag; it never makes more per-column calls than today's search.
d Test intent preserved / new tests added? New unit tests check SortedKeyRuns against a whole-key oracle (walk, every call order, reset, 0/1-column keys) over UInt32/UInt64/String/Nullable(String)/Float64 with NaN and signed zeros/LowCardinality(String); each of four mutations fails at least one of them. The walk test also checks the exact number of searches of every column, so a cache that keeps nothing, or keeps only column 0's run, fails too. Debug builds compare every call with the full search, so existing SQL tests check the cache too (a missing reset in the join aborts 02273_full_sort_join). Three performance test queries added.
e Both directions demonstrated? Yes: base vs fix timings above; the unit tests fail under the mutations and pass on the fix, including four that keep results correct but drop all or part of the cache (stateless body with and without the debug check, no stores, reuse of column 0's run only), caught by the per-column call counts; the join tests fail with the cursor reset removed and pass with it.
f Fix is general across code paths? All three operators that walk consecutive groups with the narrowing are changed (LIMIT BY, negative LIMIT BY, full_sorting_merge); the stateless helper shares the same loop. Window peer groups, DISTINCT in order, partial_merge, ReplacingSorted and sliding indexes keep the stateless search unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? Type matrix above, 2 and 3 key columns, leading runs 1 to 600, trailing runs 1 to 300 or unique, range ends n/2 and n. Nullable join keys go through the same null-map search as before. Measured: runs of 2 to 64 rows 0.58x to 0.92x; single key, dependent keys, unique leading key and long runs 0.96x to 1.00x.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or behaviour change; results identical on every measured query.
i Invariants and contracts preserved? For every start row the cached search returns the stateless result while the columns and range end are unchanged since reset; a remembered run is reused only when it contains the row (both bounds). The join cursor's key columns and row count are written only in setChunk, which resets the cache on every path.

Session id: cron:clickhouse-impl-slot-41:20261003-234000

@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f26ece3]

Summary: ✅


AI Review

Summary

This PR introduces SortedKeyRuns, reuses cached key-prefix run ends across repeated multi-column equal-range searches, and threads that optimization through the sorted-stream callers that actually walk those runs (LIMIT BY, negative LIMIT BY, DISTINCT in order, window peer detection, full_sorting_merge / partial_merge joins, and ReplacingMergeTree FINAL run skipping). I did not find an unresolved correctness, lifecycle, or performance-contract issue in the current code: the new unit coverage explicitly checks arbitrary search order and reset semantics, the call sites reset or re-scope the cache consistently with its contract, the earlier one-column inlining regression is addressed in the current head, and the latest CI report for this PR is all green.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit f26ece3.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 91.80% -0.30%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 152/153 (99.35%) · Uncovered code

Full report · Diff report

@groeneai
groeneai requested review from nihalzp and vdimir October 4, 2026 03:16
@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 4, 2026
@nihalzp nihalzp self-assigned this Oct 4, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Oct 4, 2026
@nihalzp

nihalzp commented Oct 4, 2026

Copy link
Copy Markdown
Member

Also do a scan for other locations where we can use SortedKeyRuns idea to optimize further.

@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit f26ece38e2fbe6d5176b25498992b862a50d4dde was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 33 not_sure 1153 1041 -9.7% <0.0001 aggregation: This query does a large hash GROUP BY with a top-N ORDER BY. It never calls the sorted-run search this PR caches, which serves merge join, FINAL, DISTINCT/LIMIT BY on sorted input and window functions.
⚠️ 34 not_sure 1164 1041 -10.6% <0.0001 aggregation: The -10.6% change matches Q33 exactly. Both are hash-aggregation plus top-N queries that do not run the changed sorted-stream run detection, so the PR cannot explain the CPU drop.

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

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 1 not_sure 65 54 -16.9% <0.0001 aggregation: This query is a hash aggregation over lineitem and has a noisy history. The PR median of 54 ms sits inside master's recent 50-64 ms range, while the 65 ms baseline sits just above it.
⚠️ 7 not_sure 81 61 -24.7% <0.0001 join_operator: This query uses the default hash join, not full_sorting_merge, so the changed merge-join cursor is not run. The 61 ms PR median is inside master's recent 60-78 ms range, and the 81 ms baseline is above it.

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
  • StressHouse run: d48e4df1-31c8-4873-a544-3c728c39aafc
  • MIRAI run: 96b74183-ad0d-4ba1-9e2f-7189cf996a3d
  • PR check IDs:
    • clickbench_350486_1791463253
    • clickbench_350492_1791463253
    • clickbench_350498_1791463253
    • tpch_adapted_1_official_350509_1791463253
    • tpch_adapted_1_official_350543_1791463253
    • tpch_adapted_1_official_350557_1791463254

groeneai and others added 2 commits October 4, 2026 06:34
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]>
@groeneai groeneai changed the title Speed up in-order LIMIT BY and full_sorting_merge JOIN on multi-column keys with long leading-key runs Speed up in-order LIMIT BY, DISTINCT, window functions, merge joins and FINAL on multi-column keys with long leading-key runs Oct 4, 2026
@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

I scanned the callers that walk the runs of a sorted range with the multi-column narrowing search, and all of them now use SortedKeyRuns (7c08013b88, perf test in b8e4af9285):

  • ReplacingSortedAlgorithm run skipping, one per source, reset on a new chunk or batch end: FINAL with enable_vertical_final = 0 0.44x
  • WindowTransform peer groups, one shared by the frame boundaries and keyed on block and bound: ORDER BY a, b 0.73x, GROUPS frame 0.88x
  • SlidingIndexes (PARTITION BY a, b boundaries): 0.81x
  • DistinctSortedStreamTransform: 0.83x
  • MergeJoin (partial_merge) getEqualLength: 0.74x

That is on 20M rows sorted by two String columns with leading runs of 20000 (RelWithDebInfo, identical results); with one-row or four-row leading runs the same queries stay at 0.99x to 1.06x. The callers go through new SortedKeyRuns overloads of getEqualRangeEndAssumeSorted in SortCursor.h, which the LIMIT BY transforms now use too.

Left out, since they use a different search: AggregatingInOrderTransform (a full-key upper_bound per group, it would need the narrowing search first), FillingTransform::getRangeEnd (collation-aware predicate), and the linear scans in cume_dist and RowOrderOptimizer, whose per-group work is linear anyway. The other merge algorithms compare neighbouring rows and have no run search.

@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b8e4af9

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (amd_release, master_head, 5/6) / json_extract_rapidjson #3 dashboard regression 0.180 -> 0.229 s; the query (JSONExtractUInt over zeros) runs none of the code this PR changes; the same query is slower on 7 other PRs today and on no master run in 14 days #123755 (mine, open)
Mergeable Check, PR rollups of the row above #123755 (mine, open)

Session id: cron:our-pr-ci-monitor:20261004-120236

@nihalzp

nihalzp commented Oct 7, 2026

Copy link
Copy Markdown
Member

@groeneai Fix conflicts.

@nihalzp

nihalzp commented Oct 7, 2026

Copy link
Copy Markdown
Member
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.

groeneai and others added 2 commits October 7, 2026 17:19
…-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]>
@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master: the only conflict was SlidingIndexes.cpp with #123737, resolved onto its per-partition peer-group marking (e5aef2bafe7cb).

The parallel_full_sorting_merge_join #1 regression is real and caused by this PR. nextDistinct is inlined at about ten call sites, and clang kept its one-column branch, findKeyRangeEndAssumeSorted, as one out-of-line function called twice per matched row on a unique key. The window path had the same problem (out-of-line findPeerRunEnd and SortedKeyRuns overloads; window_function_with_order #3 was +22% on arm in the last run). Fixed in f26ece38e2fbe: these helpers are force-inlined, one-column keys take the stateless search, and the peer-group marking no longer resets the cache for every partition.

Release builds, interleaved, n=40, median against master: parallel_full_sorting_merge_join #1 0.995x, the sorted-input full_sorting_merge query 1.00x, window_function_with_order #0/#2/#3 0.99x; the two-column full_sorting_merge arm stays at 0.40x. Single-row partitions with a two-column window ORDER BY (not in a perf test) remain about 4% slower.

@nihalzp
nihalzp enabled auto-merge October 8, 2026 06:36
@nihalzp
nihalzp added this pull request to the merge queue Oct 8, 2026
Merged via the queue into ClickHouse:master with commit 83c1e5c Oct 8, 2026
152 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 8, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 8, 2026
fm4v added a commit that referenced this pull request Oct 9, 2026
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
fm4v added a commit that referenced this pull request Oct 9, 2026
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
robot-clickhouse-ci-2 added a commit that referenced this pull request Oct 9, 2026
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
robot-clickhouse added a commit that referenced this pull request Oct 9, 2026
…w functions, merge joins and FINAL on multi-column keys with long leading-key runs
robot-clickhouse-ci-2 added a commit that referenced this pull request Oct 9, 2026
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
robot-clickhouse added a commit that referenced this pull request Oct 9, 2026
…w functions, merge joins and FINAL on multi-column keys with long leading-key runs
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 9, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 9, 2026
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
nihalzp added a commit that referenced this pull request Oct 10, 2026
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
alexey-milovidov added a commit that referenced this pull request Oct 16, 2026
- 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]>
@nihalzp

nihalzp commented Oct 20, 2026

Copy link
Copy Markdown
Member

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

This is not from #123808. The same assertion fires on c9d4edb5640, the master CI debug build from just before #123808 merged (and on master today, c8a410bb971). With a single LIMIT BY column the run search goes through the same code as before #123808, and the abort is the existing checkEqualRangeEndAssumeSorted sortedness check under LimitBySortedStreamTransform::transform.

The input to LIMIT BY is already unsorted: k is UInt8, so WITH FILL TO 65536 wraps around after 255. The subquery alone returns 66436 rows with min 0, max 255 and groupArray(k) = arraySort(groupArray(k)) = 0, while still advertising ORDER BY k.

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 (3554da39bf1, which already contains #123808) your query returns Code: 475 ... WITH FILL generates the value 256 which is out of range of the ORDER BY column ... of type UInt8. (INVALID_WITH_FILL_EXPRESSION) instead of aborting, and the in-range control TO 255 returns 455 on all three builds. So I'm not opening a duplicate PR for it.

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-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

LIMIT BY on a stream already sorted by its keys is about 2x slower (26.6 -> 26.8)

6 participants