Skip to content

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 - #124725

Merged
robot-clickhouse-ci-2 merged 11 commits into
backport/26.8/123808from
cherrypick/26.8/123808
Oct 9, 2026
Merged

robot-clickhouse-ci-2 merged 11 commits into
backport/26.8/123808from
cherrypick/26.8/123808

Conversation

@robot-clickhouse-ci-1

Copy link
Copy Markdown
Contributor

Original pull-request #123808

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Before you resolve anything

Conflicts are often caused by a prerequisite change that has not been backported yet, rather than by a real divergence. The bot re-tries this cherry-pick against the release branch on every run, so if that is the case here it will merge itself as soon as the prerequisite lands, and you will see a comment saying so. Manual resolution is only needed while the conflict persists.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

groeneai and others added 10 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 #123700: 18.9 String equality checks per row for
480-row leading runs with a unique second key, versus 2 comparisons per row before #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 #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]>
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]>
…-runs

# Conflicts:
#	src/Processors/Transforms/Window/SlidingIndexes.cpp
parallel_full_sorting_merge_join #1 (full_sorting_merge on one UInt64 key)
and window_function_with_order #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]>
Speed up in-order LIMIT BY, DISTINCT, window functions, merge joins and FINAL on multi-column keys with long leading-key runs
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request labels Oct 8, 2026
@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator

I resolved the conflicts by leaving out two groups of hunks, so this branch gets only the parts of #123808 that apply to 26.8 as is:

The rest (the SortedKeyRuns helper, SortCursor.h, LIMIT BY, negative LIMIT BY, DISTINCT in order, both merge joins, the gtest and the perf tests) merges cleanly.

What I checked:

  • git diff backport/26.8/123808 <resolution> touches 14 files (691 insertions, 28 deletions), and in each file the added and removed lines are the same as in Speed up in-order LIMIT BY, DISTINCT, window functions, merge joins and FINAL on multi-column keys with long leading-key runs #123808's own diff.
  • A Debug build with clang-22, the 26.8 toolset, compiles, and unit_tests_dbms --gtest_filter='SortedEqualRuns*:*EqualRange*' passes 19/19. On a two-column key with long runs of the first column and 997-row blocks, LIMIT BY, LIMIT n, m BY, negative LIMIT BY, DISTINCT in order, and full_sorting_merge (also with Nullable keys) and partial_merge joins match a GROUP BY oracle, with the debug check in SortedKeyRuns active. When I make the LIMIT BY transform keep its run cache across chunks, that query aborts, so it runs the ported code on this branch.
  • The resolution's first parent is 83c1e5c7493c, this PR's head, so applying it is a fast-forward.

@nihalzp, I have triage but not push on this repository, so I cannot update cherrypick/26.8/123808 myself. Applying it takes two commands:

git fetch https://github.com/groeneai/ClickHouse resolve-26.8-cherrypick-123808
git push origin FETCH_HEAD:cherrypick/26.8/123808

After that the robot merges this PR and opens the 26.8 backport PR itself.

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
@robot-clickhouse-ci-2
robot-clickhouse-ci-2 merged commit 7bcac75 into backport/26.8/123808 Oct 9, 2026
1 check passed
@robot-clickhouse-ci-2
robot-clickhouse-ci-2 deleted the cherrypick/26.8/123808 branch October 9, 2026 21:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants