Skip to content

GROUP BY with ORDER BY and LIMIT performance optimization - #78553

Closed
Dmitry909 wants to merge 69 commits into
ClickHouse:masterfrom
Dmitry909:72610
Closed

Dmitry909 wants to merge 69 commits into
ClickHouse:masterfrom
Dmitry909:72610

Conversation

@Dmitry909

@Dmitry909 Dmitry909 commented Apr 1, 2025 •

Copy link
Copy Markdown

Changelog category (leave one):

  • Performance Improvement

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

GROUP BY with ORDER BY and LIMIT performance optimization. Resolves #72610.

Details

Idea of optimization

See in #72610.

The implementation works as follows:

  1. findOptimizationSublistIndexes is used to determine the applicability of optimization
  2. Optimization is being applied in emplaceImplOptimization. Before each insertion into the HT, it is checked whether this key can be ignored. This is done using a heap. Heap stores iterators in HT.
  3. compareKeyHolders is used as a comparator.
  4. Also the size of HT is controlled to prevent unnecessary allocations.

Not solved details:

  1. nullptr dereferences in JIT-compiled aggregate functions.

How to improve:

  1. Merge implementation for Integers and Floats in this PR.
  2. Next, implement for String columns also
  3. Next, support >1 column in GROUP BY expressions list

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Apr 2, 2025
@clickhouse-gh

clickhouse-gh Bot commented Apr 2, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [675b1041]

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Apr 2, 2025
@alexey-milovidov alexey-milovidov changed the title 72610 GROUP BY with ORDER BY and LIMIT performance optimization Apr 2, 2025
@Dmitry909
Dmitry909 force-pushed the 72610 branch 6 times, most recently from c0f8d73 to c70e910 Compare April 8, 2025 16:43
@nickitat nickitat self-assigned this Apr 8, 2025
@nickitat

nickitat commented Apr 8, 2025

Copy link
Copy Markdown
Member

Any comments on the implementation will be very much appreciated

@Dmitry909

Copy link
Copy Markdown
Author

Any comments on the implementation will be very much appreciated

Yeah, I'm now fixing the rest two (I hope) bugs and then will write comments and ask the review the PR

Comment thread src/Common/ColumnsHashingImpl.h Outdated
@@ -310,8 +326,50 @@ class HashMethodBase
null_map = &checkAndGetColumn<ColumnNullable>(*column).getNullMapColumn();
}

template <typename T, typename = void>

@Dmitry909 Dmitry909 Apr 10, 2025 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I added many type_traitrs-like structs to check do template types have specific methods or not

@Dmitry909

Dmitry909 commented Apr 10, 2025 •

Copy link
Copy Markdown
Author

@nickitat Hi, please, review the PR. I've written description and some comments

@nickitat

Copy link
Copy Markdown
Member
  1. We should do both: keep HT size limited and avoid inserting rows that certainly have values greater than the bottommost row of the top-N at all. Suppose we already have N rows in a priority queue. Then, we process another block and compare all rows with the least priority row from the current heap. It should be fast because we compare the whole block with the same grouping key value. Some rows will be discarded at this point; we will process the rest as usual. With the exception that when we insert the value into HT (i.e., when we know that this value wasn't seen before), we also add this value into the priority queue (maybe keeping the iterator to the position in HT). At the same time, we are watching the size of the HT. If it exceeds a certain limit, we rebuild the HT this way or another, leaving only N entries in place. From this point, we will use the new bottommost row for comparisons.
  2. We shouldn't do comparisons on KeyHolder-s. You already saw why - it is very hard to implement a generic way to do it. To see an example of a priority queue of sorting key values, you can look at how it is implemented for FINAL:
    std::priority_queue<PartsRangesIteratorWithIndex, std::vector<PartsRangesIteratorWithIndex>, std::greater<>> parts_ranges_queue;

@nickitat

Copy link
Copy Markdown
Member

Pls fix this failure; otherwise, CI won't run all checks

Screenshot 2025-08-29 at 15 23 06

@@ -0,0 +1,9 @@
-- aggregate functions are JIT-compiled after 3 queries

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.

It's not after three times, it's after compile_aggregate_expressions times

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks, fixed

Comment on lines +497 to +502
if constexpr (!std::is_same_v<KeyHolder, DB::SerializedKeyHolder>
&& !std::is_same_v<KeyHolder, DB::ArenaKeyHolder>
&& !std::is_same_v<KeyHolder, Int128>
&& !std::is_same_v<KeyHolder, UInt128>
&& !std::is_same_v<KeyHolder, Int256>
&& !std::is_same_v<KeyHolder, UInt256>) { // TODO support all types

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.

It looks like we would solve two problems (a lot of unsupported types and a lot of new, quite hacky code to compare key holders) by implementing the approach I suggested a long time ago, i.e., to store keys explicitly as std::vector<Field>, the same way we do it in the optimisation for FINAL:

using Values = std::vector<Field>;

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

store keys explicitly as std::vector<Field>, the same way we do it in the optimisation for FINAL

I would be great if I could get keys explicitly, but I don't know how to do it. I get key holder here: https://github.com/ClickHouse/ClickHouse/pull/78553/files#diff-c8b49fda2cd83ab0699159b9fe8664fd976cd8550c4f26feac1adc35a03a3546R319. How to receive std::vector<Field>? @nickitat

@clickhouse-gh

clickhouse-gh Bot commented Oct 14, 2025

Copy link
Copy Markdown
Contributor

Dear @nickitat, this PR hasn't been updated for a while. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@nihalzp nihalzp self-assigned this Nov 1, 2025
@nihalzp

nihalzp commented Nov 5, 2025

Copy link
Copy Markdown
Member

@Dmitry909 Thank you for working on it. Are you planning to continue? If not, I can base my work on your commits and finish it, preserving your authorship.

@nickitat

nickitat commented Nov 6, 2025

Copy link
Copy Markdown
Member

@Dmitry909 Thank you for working on it. Are you planning to continue? If not, I can base my work on your commits and finish it, preserving your authorship.

Last time we chatted, Dmitry planned to push new code next week.

@nickitat nickitat assigned nickitat and unassigned nihalzp Nov 6, 2025
@Dmitry909

Dmitry909 commented Nov 15, 2025 •

Copy link
Copy Markdown
Author

Hi @nihalzp. I asked @nickitat is this task very important for ClickHouse project or not. He said, that now there are not enough free developers to do it. I'm interested in the task, but I'm pretty tired of doing it. Now I made corrections, which Nikita told me about, seems that it is near completion. And I can work on it once a week maybe. Soooo, let's leave it assigned to me for now.

@Dmitry909
Dmitry909 force-pushed the 72610 branch 2 times, most recently from b6ff736 to 74c3850 Compare November 16, 2025 20:07
@rschu1ze

Copy link
Copy Markdown
Member

@thevar1able will continue with this PR (in a little time from now) - thanks.

@thevar1able

Copy link
Copy Markdown
Member

@Dmitry909

I've started reviewing the changeset, sorry for the delay.

I'm still getting up to speed with the aggregation implementation details, and mostly testing behavior changes at the moment. Looking at your previous benchmark, I see that you previously measured that the changeset drastically improves this simple query:

select number, count() from numbers(25e7) group by number order by number limit 100

However I can not reproduce this on the last commit: https://pastila.nl/?013c63ca/ab733283bc863bccb22cbb80672371a3#V53qorClfpgP4vFqfRiS8A==GCM
We're taking the branch here, and exiting early before we have a chance to apply the optimization. I think it'd make sense to add some performance tests to make such regressions trivially visible.

Would you like to continue working on the PR? It is okay if it is not convenient for you at the moment, I can take it over and continue for you.

@clickhouse-gh

clickhouse-gh Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

Dear @thevar1able, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@alexey-milovidov

Copy link
Copy Markdown
Member

Closing in favor of #96630

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 pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Optimization of GROUP BY in the presence of ORDER BY and LIMIT

7 participants