Skip to content

Optimize LIMIT BY - #103349

Merged
nihalzp merged 28 commits into
ClickHouse:masterfrom
nihalzp:optimize-limit-by
Jun 5, 2026
Merged

nihalzp merged 28 commits into
ClickHouse:masterfrom
nihalzp:optimize-limit-by

Conversation

@nihalzp

@nihalzp nihalzp commented Apr 22, 2026 •

Copy link
Copy Markdown
Member

Core Optimizations:

  • Remove per-row hashing from in-order LIMIT BY.
  • Replace the generic LIMIT BY SipHash + HashMap<UInt128, UInt64> path with typed hash methods from AggregatedDataVariants. This reduces memory usage for many common key types and lets LIMIT BY benefit from existing optimizations. It also avoids relying on hash equality alone to distinguish keys.
  • Improve chunk materialization during transform. Instead of always using IColumn::filter, choose the cheapest strategy for the output: reuse the whole chunk if all rows are part of the output, use faster IColumn::cut for contiguous output, and fall back to filter only when needed.
image 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):

Improve performance of LIMIT BY queries.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.414

@clickhouse-gh

clickhouse-gh Bot commented Apr 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [61118e2]

Summary: ✅


AI Review

Summary

This PR optimizes LIMIT BY by replacing the generic hash path with AggregatedDataVariants, adding sorted-stream LIMIT BY transforms, and improving chunk materialization. The representation issues from earlier review threads are addressed in the current code, but I still consider the accepted floating-point key equality divergence a real query-result risk.

Findings

⚠️ Majors

  • [src/Processors/Transforms/LimitByTransform.cpp:313, src/Processors/Transforms/NegativeLimitByTransform.cpp:368] [dismissed by author -- https://github.com/Optimize LIMIT BY #103349#discussion_r3334016896] LIMIT BY should preserve grouping semantics when the sorted optimization is selected, but the generic paths group floating-point keys by the typed hash/raw representation while LimitBySortedStreamTransform and NegativeLimitBySortedStreamTransform split runs with compareAt. compareAt treats +0.0/-0.0 and distinct NaN payloads as equal, so the sorted transforms can keep fewer rows than the generic transforms for the same LIMIT BY key. The added 04312_in_order_aggregation_inconsistency test documents this as known behavior; I still consider it real because this PR changes LIMIT BY results based on whether the plan can use the sorted path. Suggested fix: use the same key representation/equality as AggregatedDataVariants to detect sorted runs, or disable the sorted LIMIT BY variants for floating-point keys until the equality contract is made consistent.
Final Verdict

Status: ⚠️ Request changes

Minimum action: align float key equality between generic and sorted LIMIT BY, or explicitly keep the sorted optimization off for floating-point LIMIT BY keys.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Apr 22, 2026
@Fgrtue Fgrtue self-assigned this May 5, 2026
@nihalzp nihalzp mentioned this pull request May 10, 2026
1 task done
@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

@Fgrtue Fgrtue left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The implementation looks good to me. I would like to suggest adding a separate test for it, as we usually do this when we add new features of do improvements -- the test could just show that there are two different limit by pipeline processorts exist now.

Other than that I suggested two improvements: 1) Short circuit execution -- probably not so difficult to add; 2) SIMD computation of delimiters between different rows in columns -- probably more involved as it is supposed to add a new method and might even worth another PR. Would be interested knowing your opinion on those suggestions.

@nihalzp

nihalzp commented May 25, 2026

Copy link
Copy Markdown
Member Author

Thanks for the thorough review!

The implementation looks good to me. I would like to suggest adding a separate test for it, as we usually do this when we add new features of do improvements -- the test could just show that there are two different limit by pipeline processorts exist now.

Actually, the edited test tests/queries/0_stateless/03701_limit_by_in_order.reference shows both the processors LimitBySortedStreamTransform and LimitByTransform.

Other than that I suggested two improvements: 1) Short circuit execution -- probably not so difficult to add; 2) SIMD computation of delimiters between different rows in columns -- probably more involved as it is supposed to add a new method and might even worth another PR. Would be interested knowing your opinion on those suggestions.

  1. Added the short circuit execution.

  2. I think that's a very good idea; worth creating an RFC for it. We also have DistinctSortedStreamTransform, aggregation in order, which could also benefit from it. For LimitByTransform, the main cost is actually hashing, and having the same key appear consecutively may be rare, so we may not see a significant speedup. But for LimitBySortedStreamTransform, this could give quite a bit of speedup; we can also consider binary search to find the equal-key runs and see how it performs. I can see that for low-cardinality keys binary search would perform very well.

@Fgrtue

Fgrtue commented May 28, 2026

Copy link
Copy Markdown
Contributor

Actually, the edited test tests/queries/0_stateless/03701_limit_by_in_order.reference shows both the processors LimitBySortedStreamTransform and LimitByTransform.

I saw it, but I wanted to propose another one -- a new one, that will designate the appearance of this new processor. So even though we have the old test, we would also have a new one. But this is just a nit, and not critical, so I don't insist.

@Fgrtue

Fgrtue commented May 28, 2026

Copy link
Copy Markdown
Contributor

we can also consider binary search to find the equal-key runs and see how it performs.

Do you want to experiment with the binary search in the sorted version in this PR or in a separate one?

@nihalzp

nihalzp commented May 30, 2026

Copy link
Copy Markdown
Member Author

I saw it, but I wanted to propose another one -- a new one, that will designate the appearance of this new processor. So even though we have the old test, we would also have a new one. But this is just a nit, and not critical, so I don't insist.

Okay. Added 04268_limit_by_explain.sql.

Do you want to experiment with the binary search in the sorted version in this PR or in a separate one?

I think it will be better if done in a separate PR since it will be done as a new method of IColumn and performance improvement is guaranteed for all cases so need some experimenting.

@Fgrtue Fgrtue left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thank you for adding the test. Looking forward to further updates on ordered case.

@clickhouse-gh

clickhouse-gh Bot commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR rewrites only the LIMIT BY execution path, splitting it into a general transform and a new sorted-stream variant. ClickBench Q32 is a GROUP BY / ORDER BY ... LIMIT 10 query with no LIMIT BY clause, so it never touches the changed code. The single flagged delta (5.38% on Q32) is borderline — only one of the two tests flags it, on a query whose measurements were noisy — and is not attributable to this change. No real regression or improvement is evident in the flagged set.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
⚠️ 32 not_sure 1505 1586 +5.4% 0.0401 Q32 has no LIMIT BY; PR only rewrites the LIMIT BY path. 5% delta is borderline run-to-run noise.

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: a6f10eec-3c7d-4755-a3cb-4aa1406805df
  • MIRAI run: 15b17277-9571-40f4-be79-6869c37a1d50
  • PR check IDs:
    • clickbench_404918_1780644549
    • clickbench_404931_1780644549
    • clickbench_404934_1780644549
    • tpch_adapted_1_official_404939_1780644549
    • tpch_adapted_1_official_404944_1780644549
    • tpch_adapted_1_official_404953_1780644549

@clickhouse-gh

clickhouse-gh Bot commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.40% +0.00%
Functions 92.40% 92.40% +0.00%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 226/234 (96.58%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@nihalzp
nihalzp added this pull request to the merge queue Jun 5, 2026
Merged via the queue into ClickHouse:master with commit 57c8294 Jun 5, 2026
166 checks passed
@nihalzp
nihalzp deleted the optimize-limit-by branch June 5, 2026 10:48
@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 5, 2026
@nihalzp

nihalzp commented Jun 5, 2026

Copy link
Copy Markdown
Member Author

@Fgrtue The binary search idea that I discussed:

As expected, it is giving quite of speedup!

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.

4 participants