Skip to content

Speed up DISTINCT in order, sort-merge joins, LIMIT BY and negative LIMIT BY - #106502

Merged
nihalzp merged 47 commits into
ClickHouse:masterfrom
nihalzp:optimize-equal-run-end-search
Jun 25, 2026
Merged

nihalzp merged 47 commits into
ClickHouse:masterfrom
nihalzp:optimize-equal-run-end-search

Conversation

@nihalzp

@nihalzp nihalzp commented Jun 4, 2026 •

Copy link
Copy Markdown
Member

The PR tries to optimize the scenario when we have a sorted IColumn and we want to find the end row number of equal key in the column. In many places, we do normal linear scan and in some places, we do binary search but have duplicate implementation. This PR unifies this utility it as a IColumn method and allows a single optimized binary search implementation for all use cases.

image image image image

Changelog category (leave one):

  • Performance Improvement

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

Speed up operators that scan a sorted stream for runs of equal key values — DISTINCT in order, LIMIT BY in order, negative LIMIT BY in order, full_sorting_merge and partial_merge joins.

@clickhouse-gh

clickhouse-gh Bot commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fef062a]

Summary: ✅


AI Review

Summary
  • This PR adds a shared sorted equal-run search and wires it into sorted DISTINCT, LIMIT BY, negative LIMIT BY, and sort-merge join paths. I verified the current code against the prior discussion around collation, nullable null maps, permuted sort-prefix keys, and LowCardinality(Float*) dictionaries; the previous bot findings I rechecked are addressed, and I did not find new correctness or safety issues.
Missing context / blind spots
  • ⚠️ I could not run local tests because this checkout has no build* directory or clickhouse binary. I reviewed the code, prior discussion, targeted benchmark screenshots in the PR body, and the direct Praktika PR report for fef062ab, which reported no failed test entries.
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR adds a galloping plus binary-search fast path for finding equal-value runs in sorted columns (getEqualRangeEndAssumeSorted), wired only into sort-merge join equal-length detection and the LIMIT BY / negative-LIMIT-BY sorted-stream transforms. ClickBench queries use neither merge joins nor LIMIT BY, so the flagged improvements on Q4, Q28, and Q32 cannot be attributed to this change and read as run-to-run variance across the two builds; they have been downgraded. Notably the tpch_adapted_1_official suite, which is where join and ordering changes would actually surface, showed no per-query shifts, reinforcing that the ClickBench deltas are noise rather than a real effect of this PR.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 261 229 -12.3% <0.0001 ClickBench has no LIMIT BY and no merge joins; this PR's equal-range fast path isn't exercised. Off-path, run-to-run var
⚠️ 28 not_sure 6973 6613 -5.2% 0.0006 Off-path: PR only touches sort-merge join and LIMIT BY equal-range scanning, which this ClickBench query doesn't run. Va
⚠️ 32 not_sure 1343 1269 -5.5% <0.0001 Already not_sure; noisy (high variance, the two tests disagree). PR's merge-join/LIMIT BY change is off-path for ClickBe

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
  • StressHouse run: 22fc6d18-9782-4df6-9a06-0ef9338b2c8a
  • MIRAI run: b802e90d-8b37-474a-899d-dee612136e7e
  • PR check IDs:
    • clickbench_39534_1782392618
    • clickbench_39548_1782392618
    • clickbench_39554_1782392618
    • tpch_adapted_1_official_39561_1782392618
    • tpch_adapted_1_official_39572_1782392618
    • tpch_adapted_1_official_39582_1782392618

@nihalzp nihalzp changed the title Speed up DISTINCT in order, sort-merge joins, ORDER BY ... WITH FILL and LIMIT BY Speed up DISTINCT in order, sort-merge joins, ORDER BY ... WITH FILL, LIMIT BY and negative LIMIT BY Jun 5, 2026
@nihalzp nihalzp mentioned this pull request Jun 5, 2026
1 task
Comment thread src/Columns/ColumnUnique.h Resolved
@nihalzp
nihalzp requested a review from Algunenano June 22, 2026 09:07

@Algunenano Algunenano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@nihalzp It seems #106502 (comment) and #106502 (comment) are still unaddressed.

You mentioned Okay, I will keep it safe and not apply it for Float LC. but didn't change it AFAICT.

ColumnLowCardinality::getEqualRangeEndAssumeSorted would need to deal with floats, and nullable(float). And after that uniqueInsertCanonicalFloat is unused and should be removed

@nihalzp

nihalzp commented Jun 23, 2026

Copy link
Copy Markdown
Member Author

You mentioned Okay, I will keep it safe and not apply it for Float LC. but didn't change it AFAICT.

I requested review before I made that comment and have not gotten chance to work on it yet :'. I will work on it soon.

@clickhouse-gh

clickhouse-gh Bot commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.30% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.50% 77.50% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 482/490 (98.37%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 5 line(s) · Uncovered code

Full report · Diff report

@nihalzp
nihalzp added this pull request to the merge queue Jun 25, 2026
Merged via the queue into ClickHouse:master with commit 9f7b790 Jun 25, 2026
328 of 330 checks passed
@nihalzp
nihalzp deleted the optimize-equal-run-end-search branch June 25, 2026 16:16
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 25, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…end-search

Speed up `DISTINCT` in order, sort-merge joins, `LIMIT BY` and negative `LIMIT BY`
zvonand pushed a commit to zvonand/ClickHouse that referenced this pull request Oct 8, 2026
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]>
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants