Repository navigation
Optimization of GROUP BY in the presence of ORDER BY and LIMIT - #96630
Conversation
`select URL, count() from hits where URL != group by URL order by URL limit 5 settings top_n_group_by_limit_pushdown=1`
|
Workflow [PR], commit [fdfebc6] Summary: ✅
AI ReviewSummaryThis PR adds the new Findings
Final VerdictStatus: Minimum required actions:
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 904/982 (92.06%) · Uncovered code |
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
This comment was marked as outdated.
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
left a comment
There was a problem hiding this comment.
I can understand most of it.
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]>
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.
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]>
…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]>
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]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Optimize
GROUP BY ... ORDER BY ... LIMITandGROUP BY ... LIMITqueries 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 theenable_group_by_top_k_optimizationsetting. 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 matchSELECT key, agg() FROM t GROUP BY key LIMIT N-- single key, no ORDER BYSELECT k1, k2, agg() FROM t GROUP BY k1, k2 ORDER BY k1, k2 ASC LIMIT N-- composite keys, full ORDER BY matchSELECT k1, k2, k3, agg() FROM t GROUP BY k1, k2, k3 ORDER BY k1, k2, k3 ASC LIMIT N-- 3+ keys, full matchSELECT k1, k2, agg() FROM t GROUP BY k1, k2 ORDER BY k1 ASC LIMIT N-- composite keys, ORDER BY is a prefix of GROUP BYSELECT k1, k2, k3, agg() FROM t GROUP BY k1, k2, k3 ORDER BY k1 ASC LIMIT N-- prefix 1 of 3SELECT k1, k2, k3, agg() FROM t GROUP BY k1, k2, k3 ORDER BY k1, k2 ASC LIMIT N-- prefix 2 of 3SELECT k1, k2, agg() FROM t GROUP BY k1, k2 LIMIT N-- composite keys, no ORDER BYSELECT URL, count() FROM t GROUP BY URL ORDER BY URL ASC LIMIT N-- String keysSELECT URL, count() FROM t GROUP BY URL LIMIT N-- String keys, no ORDER BYNot 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,ROLLUPLIMIT WITH TIESNon-final aggregation (distributed partial aggregation)max_rows_to_group_byis setrows_before_limit_at_leastmode (exact count)Workflow [PR]
Sync PR [sync-upstream/pr/96630]
Version info
26.8.1.1977(included in26.8and later)