Skip to content

Optimization of GROUP BY in the presence of ORDER BY and LIMIT - #96630

Merged
alexey-milovidov merged 249 commits into
masterfrom
reimplement-group-by-limit-pushdown
Aug 24, 2026
Merged

alexey-milovidov merged 249 commits into
masterfrom
reimplement-group-by-limit-pushdown

Conversation

@thevar1able

@thevar1able thevar1able commented Feb 11, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Optimize GROUP BY ... ORDER BY ... LIMIT and GROUP BY ... LIMIT queries by maintaining a bounded heap during aggregation to prune groups that cannot appear in the result, significantly reducing memory usage and execution time for high-cardinality grouping. Controlled by the enable_group_by_top_k_optimization setting. Based on the initial implementation by Dmitriy Terenichev (#78553).

Related: #72610

Query shapes that benefit from this optimization:

  • SELECT key, agg() FROM t GROUP BY key ORDER BY key ASC LIMIT N -- single key, full ORDER BY match
  • SELECT key, agg() FROM t GROUP BY key LIMIT N -- single key, no ORDER BY
  • SELECT k1, k2, agg() FROM t GROUP BY k1, k2 ORDER BY k1, k2 ASC LIMIT N -- composite keys, full ORDER BY match
  • SELECT k1, k2, k3, agg() FROM t GROUP BY k1, k2, k3 ORDER BY k1, k2, k3 ASC LIMIT N -- 3+ keys, full match
  • SELECT k1, k2, agg() FROM t GROUP BY k1, k2 ORDER BY k1 ASC LIMIT N -- composite keys, ORDER BY is a prefix of GROUP BY
  • SELECT k1, k2, k3, agg() FROM t GROUP BY k1, k2, k3 ORDER BY k1 ASC LIMIT N -- prefix 1 of 3
  • SELECT k1, k2, k3, agg() FROM t GROUP BY k1, k2, k3 ORDER BY k1, k2 ASC LIMIT N -- prefix 2 of 3
  • SELECT k1, k2, agg() FROM t GROUP BY k1, k2 LIMIT N -- composite keys, no ORDER BY
  • SELECT URL, count() FROM t GROUP BY URL ORDER BY URL ASC LIMIT N -- String keys
  • SELECT URL, count() FROM t GROUP BY URL LIMIT N -- String keys, no ORDER BY

Not supported (optimization is skipped):

  • ORDER BY agg() (ORDER BY aggregate function, not a GROUP BY key) (handled by another PR)
  • WITH TOTALS, HAVING, GROUPING SETS, CUBE, ROLLUP
  • LIMIT WITH TIES
  • Non-final aggregation (distributed partial aggregation)
  • max_rows_to_group_by is set
  • rows_before_limit_at_least mode (exact count)
  • a COLLATE on any of the matched GROUP BY keys (a COLLATE on a later ORDER BY column past the full key prefix cannot affect which groups qualify and does not disable the optimization)
  • ORDER BY columns that are not a leading prefix of GROUP BY keys

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

Version info

  • Merged into: 26.8.1.1977 (included in 26.8 and later)

`select URL, count() from hits where URL !=  group by URL order by URL limit 5 settings top_n_group_by_limit_pushdown=1`
@clickhouse-gh

clickhouse-gh Bot commented Feb 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fdfebc6]

Summary: ✅


AI Review

Summary

This PR adds the new GROUP BY top-K aggregation optimization across the planner, query-plan optimizer, and aggregation runtime, including a large correctness/performance test suite. The current head is much closer than the early iterations, but I still see two live contract problems: a blanket serialize_query_plan fence disables the optimization for purely local queries, and spill reinitialization forgets the heap's sticky frozen state and re-enables work the query already proved unprofitable.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/optimizeGroupByTopK.cpp:52] serialize_query_plan is treated as a global kill switch for GROUP BY top-K, even when the current query never ships a serialized fragment anywhere. That changes the meaning of a distributed-execution session setting for ordinary local queries: enabling serialized distributed plans in the session silently turns this local optimization off as well. The symptom is visible in this PR's own tests, which have to pin serialize_query_plan = 0 just to exercise Top-K on otherwise local shapes. Gate this on an actual shipped/serialized fragment, or reject/document the unsupported combination explicitly instead of silently shrinking the feature surface.

  • [src/Interpreters/AggregatedDataVariants.cpp:61] External aggregation reinitialization preserves only top_k_heap_ever_rejected, but it drops the heap's sticky frozen / observation state. A query can therefore decide that Top-K is pure overhead, spill via flushToTemporaryFile(..., reinitialize = true), rebuild a fresh method here, and then start paying the heap cost all over again until it freezes a second time. That breaks the advertised "fall back to regular aggregation" behavior on spill-heavy workloads. Carry a persistent "top-K disabled for the rest of this query" bit across init, or clear params.top_k once the heap freezes.

Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Stop using the raw serialize_query_plan session flag as a blanket local-query fence for GROUP BY top-K.
  2. Preserve the heap's frozen/disabled state across external-aggregation reinitialization so a spilled query does not re-enable abandoned heap work.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 904/982 (92.06%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Feb 11, 2026
Assisted-by: Claude Opus 4.6 via GitHub Copilot
…BoundedHeap

Migrate the top-N heap used in GROUP BY LIMIT pushdown from extracting
Field values and comparing with accurateLess() to storing keys in a
small IColumn and comparing via IColumn::compareAt/compareAtWithCollation.

This fixes type correctness issues (e.g. Int64 stored as UInt64 breaking
sort order), removes per-row Field allocation overhead, and enables
collation support for ORDER BY ... COLLATE queries.

Key changes:
- Replace MultiWayHeap with ColumnBoundedHeap (manual binary heap over
  row indices into a MutableColumnPtr)
- Guard heap push() calls with top_n_keys > 0 to prevent null deref
  when the optimization is disabled
- Add key_column member to HashMethodBase for getKeyColumn() access
- Override key_column in HashMethodSingleLowCardinalityColumn to point
  at the original LC column instead of the dictionary
- Pass collator through Planner -> Aggregator params -> heap init
- Remove collation guard from optimization eligibility check

Assisted-by: Claude Opus 4.6 via GitHub Copilot
…sion

When top_n_keys > 0 (GROUP BY limit pushdown), skip cached hash table
size hints to avoid massive over-allocation and unnecessary two-level
conversion from prior runs that processed all keys.

Also preserve the pqueue when converting single-level to two-level
mid-stream, and hoist getKeyColumn() out of hot loops.
…t_at_least

The pushdown optimization reduces the number of aggregation keys,
which lowers the rows_before_limit_at_least value. These tests
specifically verify that value, so disable the optimization.
Assisted-by: Claude Opus 4.6 via GitHub Copilot
@thevar1able

This comment was marked as outdated.

…dedHeap

Assisted-by: Claude Opus 4.6 via GitHub Copilot
Add erase() to StringHashTable (via EraseCallable dispatch), TwoLevelHashTable
(delegating to the correct bucket), and TwoLevelStringHashTable (via EraseCallable
dispatch). These are needed for pruning evicted keys from the hash table during
the group-by-limit-pushdown optimization.

Assisted-by: Claude Opus 4.6 via GitHub Copilot
Instead of popping one element at a time when the heap exceeds capacity,
let the heap grow to 1.5x capacity, then batch-trim back to capacity via
trimAndCompact(). This amortizes the cost of pop+erase operations. The
compaction step filters the heap column to remove dead slots and remaps
indices in the priority queue.

Also adds custom move constructor/assignment to fix the HeapComparator's
owner pointer (which would otherwise dangle after std::move during
convertToTwoLevel), and tracks capacity/compaction_threshold members.

Assisted-by: Claude Opus 4.6 via GitHub Copilot
Move all pruning logic (heap trim, hash table erase, aggregate state
destruction) out of executeImplBatch into a separate NO_INLINE template
method trimHeapAndPruneHashTable(). This prevents the lambda definitions
and pruning code from being inlined into every template instantiation of
executeImplBatch, which was causing code bloat and CI performance regressions
in queries that don't use the optimization (top_n_keys == 0).

The batch trim is called after emplace_result is consumed to avoid
invalidation by erase()'s linear probing chain repair.

Also fixes bugprone-macro-parentheses in AggregatedDataVariants.cpp.

Assisted-by: Claude Opus 4.6 via GitHub Copilot
… test

Add DESC variants for UserID, URL, EventTime, and numbers_mt to cover
descending sort direction in CI performance benchmarks.

Assisted-by: Claude Opus 4.6 via GitHub Copilot
Assisted-by: Claude Opus 4.6 via GitHub Copilot

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

I can understand most of it.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 24, 2026
Merged via the queue into master with commit 807a4a1 Aug 24, 2026
178 checks passed
@alexey-milovidov
alexey-milovidov deleted the reimplement-group-by-limit-pushdown branch August 24, 2026 06:37
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 24, 2026
@alexey-milovidov alexey-milovidov mentioned this pull request Sep 6, 2026
1 task done
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The initial implementation ClickHouse#78553 belongs to a different optimization
(top-K heap pruning during aggregation, ClickHouse#96630, not yet merged), not
to the aggregation-in-order LIMIT push-down in ClickHouse#104859.

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Address ClickHouse#96630 (comment).

- Replace `std::priority_queue` with `std::vector<size_t>` plus
  `std::push_heap` / `std::pop_heap` / `std::make_heap`. This removes
  the `HeapAccess` friend-class hack that was repeated in three places to
  steal the underlying container, and makes move and move-assignment
  defaultable: there is no comparator instance with a back-pointer to the
  owning heap that would have to be rebuilt.
- Default move and move-assignment operators (was ~60 lines of manual,
  error-prone code).
- Extract the `compareAt` / `compareAtWithCollation` switch into a small
  `compareColumns` helper used in all three comparison paths.
- Defensively reset `should_skip_numeric_fn` in the composite `init` and
  at the top of `initNumericSkipFn` so re-initialization cannot leave a
  stale fast-path pointer.
- Drop unused `<queue>` and `<PODArray.h>` includes.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The AST-driven mirror of `tryOptimizeGroupByLimitPushdown` in
`createRemotePlanForParallelReplicas` bypassed the guards the plan-shape
optimizer gets for free: `HAVING`, `QUALIFY`, window functions, and
`DISTINCT` consume the full set of groups on the coordinator, so a
replica must not prune partial aggregation states - the coordinator
could filter out the only group a replica kept while the real answer
was already pruned. The same applies to `exact_rows_before_limit`,
which promises an exact `rows_before_limit_at_least` counter and
therefore requires counting every group (the plan-shape optimizer
checks this via `LimitStep::alwaysReadTillEnd`; the remote plan has no
`LimitStep`, so check the setting directly).

ClickHouse#96630 (comment)
ClickHouse#96630 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ng state

`trimHeapAndPruneHashTable` rebuilt evicted hash-table keys byte-wise via
`heap_column->getDataAt` + `unalignedLoad<KeyType>`. That read past the row
payload for methods whose hash key is wider than the column (`key32`:
`UInt32` column, `UInt64` key), and raised `NOT_IMPLEMENTED` for single-key
serialized `GROUP BY` over `Tuple` columns (`ColumnTuple::getDataAt`).

Evicted keys are now reconstructed with `Method::StateNoCache` constructed
over the heap's own columns, so each key goes through the same typed
accessors used during emplace (numeric widening, NULL maps, key packing,
serialization) and matches the hash-table key by construction. This also
enables hash-table pruning for composite keys, which previously accumulated
evicted entries without bound.

`GROUP BY ... LIMIT` without `ORDER BY` (Pattern 2) is now marked
`requires_pruning`: without a downstream sort, a group evicted from the
heap but left in the hash table with an incomplete aggregate state could
surface in the result. The aggregator disables the heap at runtime for
methods whose hash table cannot erase (`FixedHashTable`-based `key8` /
`key16`). The flag is round-tripped through `AggregatingStep::serialize`
and shown in `EXPLAIN actions = 1` as `requires_pruning=1`.

Based on the approach suggested in
ClickHouse#96630 (comment)

Also fixes:
ClickHouse#96630 (comment)
ClickHouse#96630 (comment)
ClickHouse#96630 (comment)
ClickHouse#96630 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Addresses the remaining review suggestions from nickitat:

- Merge `shouldSkipNumeric` / `hasNumericSkipFn` into a `shouldSkip`
  overload that transparently falls back to the virtual `compareAt` path
  (ClickHouse#96630 (comment)).
- Drop the `discarded_row_state` throwaway aggregate state: skipped rows
  now leave `places[i] = nullptr`, which the non-JIT batch paths already
  tolerate (`if (places[i]) add(...)`). The JIT path is disabled while
  the heap is active - it does not null-check `places[i]` - and
  `addBatchSinglePlace` is skipped entirely when the sole constant key
  was pruned
  (ClickHouse#96630 (comment)).
- Merge the two pattern cases in `tryOptimizeGroupByLimitPushdown` into
  a single match where the `SortingStep` is optional
  (ClickHouse#96630 (comment)).
- Restore the original include block in `AggregationMethod.h`
  (ClickHouse#96630 (comment)).
- Trim trivial comments throughout the top-K code
  (ClickHouse#96630 (comment)).

Adds a test case for a constant-key block arriving after its key was
evicted from the heap (exercises the skipped-`addBatchSinglePlace` path).

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov alexey-milovidov mentioned this pull request Sep 20, 2026
47 of 72 tasks
@rienath rienath linked an issue Nov 24, 2026 that may be closed by this pull request
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.

Query optimization for GROUP BY with ORDER BY keys and LIMIT.

6 participants