Repository navigation
Conversation
|
Workflow [PR], commit [37271e4] Summary: ❌
AI ReviewSummaryThis PR adds a new disabled-by-default Findings
Final VerdictStatus: Minimum required actions:
|
…termination) For queries of the form `GROUP BY ... ORDER BY aggregate LIMIT K`, insert a single `TopNAggregatingStep` (below a kept `LimitStep`) in place of the aggregation + sort when the MergeTree table is physically sorted by the ORDER BY aggregate's argument. Reading in physical order, each group's aggregate is determined by its first occurrence, so the scan stops after K distinct groups — O(K) rows and O(K) memory instead of a full aggregate + sort. Supports max/min as the ORDER BY aggregate with any/argMax/argMin companions on the same determining argument. Aggregation is delegated to the standard Aggregator / AggregatedDataVariants (type-dispatched and LowCardinality-aware hash methods, arena-managed states). The LimitStep is kept above the operator so `rows_before_limit_at_least` is still reported. Cardinality gate (early termination only pays off when K is small relative to the GROUP BY cardinality), controlled by two settings: - `topn_aggregation_max_ndv_ratio` (default 0.5): with column `uniq` statistics, apply when `LIMIT <= ndv * ratio`; 0 disables the statistics path. - `topn_aggregation_max_limit` (default 1000): without statistics, apply when `LIMIT <= max_limit`; 0 requires statistics. Falls back to the standard pipeline for nullable sorting-key columns, collation-sensitive ORDER BY, reverse-flagged (DESC) sorting keys, WITH TOTALS / exact_rows_before_limit, max_rows_to_group_by, grouping sets, OFFSET, WITH TIES, and non-MergeTree engines. External aggregation is disabled for the Mode-1 Aggregator (bounded-memory by ~K groups; max_memory_usage still applies). Controlled by `optimize_topn_aggregation` (enabled by default). This is the Mode 1 slice of ClickHouse#98607; Mode 2 (unsorted-input hash aggregation with threshold pruning and dynamic `__topKFilter` prewhere) follows in a separate PR. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ze_query_plan limitation
The fused transform always calls Aggregator::executeOnBlock, so it cannot consume AggregateFunction state columns. Reject params.only_merge in the match guard and fall back to the standard pipeline. Adds an aggregate-projection plan-shape + correctness regression.
Early termination is checked at input-block boundaries, so peak group-state memory is K plus the distinct groups in the block being processed, not strictly O(K). Reword the step comment and docs to match (no behavior change).
The plan-shape assertions (EXPLAIN ... TopNAggregating present/absent) depend on whether the rewrite fires, which randomized settings can suppress. Pin settings for this test; the correctness (optimized == reference) checks are unaffected.
The stateless-test server profile enables parallel replicas by default. Under parallel replicas the Mode-1 rewrite falls back to the standard pipeline (a documented limitation), so the plan-shape assertions saw no TopNAggregating step and failed. Pin enable_parallel_replicas=0 for the test (single-node optimization). Also rework the aggregate-projection case: a Mode-1-eligible query fires the rewrite on the base table and the projection is not selected, so the only_merge path is not reachable here and force_optimize_projection threw. Replace the false plan-shape assertion with a correctness check (result matches the standard pipeline whether answered from the projection or the base table).
…ssor) The stateless-test profile (limits.yaml) sets max_rows_to_group_by / max_rows_to_sort / max_bytes_to_sort to 10G to exercise limit-handling code. The Mode-1 gate rejects when any such limit is set (the fused path cannot reproduce the overflow throw), so the rewrite never fired under the test profile and the plan-shape assertions returned 0. Reset the three limits to 0 in the test. Replaces the earlier enable_parallel_replicas=0 line — parallel replicas was a red herring (the no-parallel-replicas tag already skips the PR runner; no running job exercises this test under PR). Verified locally: with ambient 10G limits the test reproduces the failure, and passes with the reset (3/3 deterministic).
The rewrite runs at the LimitStep before projection selection reaches the child AggregatingStep, so with force_optimize_projection / force_optimize_projection_name it would consume the base-table plan and leave the forced projection unused, then raise PROJECTION_NOT_USED. Skip the rewrite when forced projection is active. Reworks the aggregate-projection regression to force the projection (now succeeds via the projection with the rewrite deferred). Verified locally on a built binary.
|
📊 Cloud Performance Report ✅ AI verdict: The only flagged query is TPC-H Q4, showing an 86% median improvement (2284ms to 317ms). This PR adds a new fused TopN aggregation optimization (GROUP BY ... ORDER BY aggregate LIMIT K) that is opt-in and disabled by default, plus supporting settings that also default to off. Q4 groups on o_orderpriority, orders by that group key, and has no LIMIT, so it does not match the optimization's shape and its default execution path is untouched. The base measurement was noisy (much higher run-to-run spread than the source) and only 6 source instances were sampled, so this large delta reads as cross-run variance rather than a PR effect; downgraded to not sure. clickbench🟢 No significant changes tpch_adapted_1_officialFlagged queries (1 of 22)
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. Debug info
|
Under asan + 50x concurrent flaky-check the test occasionally exceeded the 180s per-test cap. Drop index_granularity=1 from the two float tables (was 10000 rows = 10000 granules each), shrink the 200000-row no-stats table to 20000, and the other data-insensitive tables 10000 -> 1000/2000. Only tables whose output is a 0/1 assertion are touched, so the reference is unchanged (t_topn, which prints rows, is left as-is). Local wall time ~0.4s; reference verified identical.
| local_optimization_settings.read_in_order = subquery_optimization_settings.read_in_order; | ||
| local_optimization_settings.read_in_order_through_join = subquery_optimization_settings.read_in_order_through_join; | ||
| local_optimization_settings.aggregation_in_order = subquery_optimization_settings.aggregation_in_order; | ||
| local_optimization_settings.topn_aggregation = subquery_optimization_settings.topn_aggregation; |
There was a problem hiding this comment.
optimizeTopNAggregation now has a correctness gate on force_use_projection / force_projection_name, but the extracted ReadFromLocalParallelReplicaStep local plan only copies the topn_aggregation* knobs from the subquery context. That means a subquery-local SETTINGS force_optimize_projection = 1 can still make the initiator local plan install TopNAggregating here while the remote replicas, which optimize from the subquery context, correctly skip it. In the best case that reintroduces the PROJECTION_NOT_USED failure fixed in optimizeTopNAggregation; in the worse case the initiator switches to requestReadingInOrder while the replicas stay in the default coordination mode. Please copy the projection-force flags into local_optimization_settings alongside the new topn_aggregation settings.
| pipeline.getSharedHeader(), | ||
| pipeline.getNumStreams(), | ||
| merge_sort_desc, | ||
| /*max_block_size=*/DEFAULT_BLOCK_SIZE, |
There was a problem hiding this comment.
This merge step hardcodes DEFAULT_BLOCK_SIZE, even though TopNSortedAggregatingTransform only checks the early-stop condition after each merged chunk. On a multi-stream read, lowering max_block_size is the normal way to bound that overshoot, but this path ignores it and can still hand the TopN transform a ~65k-row chunk. With many distinct groups near the front, that means materializing tens of thousands of groups before finishConsume, which defeats the documented K + current block memory bound and creates avoidable latency spikes. Please thread the original sort/merge block size into TopNAggregatingStep and use it here instead of DEFAULT_BLOCK_SIZE.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 314/384 (81.77%) · Uncovered code |
nihalzp
left a comment
There was a problem hiding this comment.
I have left a few comments. Please have a look.
| ### TopN Aggregation Optimization {#topn-aggregation-optimization} | ||
|
|
||
| For queries of the form `GROUP BY ... ORDER BY aggregate LIMIT K`, ClickHouse can fuse aggregation, sorting, and limiting into a single optimized pass with early termination. | ||
| This is controlled by the [optimize_topn_aggregation](/operations/settings/settings#optimize_topn_aggregation) setting (disabled by default; set it to `1` to opt in). |
There was a problem hiding this comment.
I think we should enable it by default since it does not have any known regression.
| - The `ORDER BY` expression must reference exactly one aggregate, whose argument is the first column of the table sorting key. | ||
| - The sort direction must be compatible with the aggregate (for example, `max` + `DESC` or `min` + `ASC`). | ||
| - No `OFFSET`, `WITH TIES`, `HAVING`, or grouping sets. |
There was a problem hiding this comment.
For V1 this is okay. We can easily support OFFSET by terminating at terminate at K + offset groups groups.
| Not supported together with `serialize_query_plan` (parallel replicas): the fused step is not serializable, so | ||
| enabling both on an eligible query raises `NOT_IMPLEMENTED` (same as `optimize_aggregation_in_order`). | ||
| )", 0) \ | ||
| DECLARE(Float, topn_aggregation_max_ndv_ratio, 0.5, R"( |
There was a problem hiding this comment.
I think ndv would not be very understandable to users. Maybe we can use something like topn_aggregation_max_limit_to_distinct_keys_ratio.
| namespace | ||
| { | ||
|
|
||
| String traceColumnThroughDAG(const ActionsDAG & dag, const String & column_name) |
There was a problem hiding this comment.
Have a look at the requestSortedInput, buildSortingDAG, buildInputOrderFromSortDescription from src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp. I think we can reuse many of the functions from there.
This will not only make sure we use long tested code but also unlock some more capabilities. For example, we can support monotonic function chains and if filter fixes one of the leading MergeTree ORDER BY columns that we do not prefer, then we can still use this optimization in some cases.
One option could be that we move optimizeTopNAggregation into optimizeReadInOrder.cpp.
| return false; | ||
| } | ||
|
|
||
| return read_from_mt.requestReadingInOrder(1, order_agg.required_direction, limit); |
There was a problem hiding this comment.
Here is the limit hint should be 0 because in most cases K groups ≫ K rows.
| if (pipeline.getNumStreams() > 1 && !order_arg_col_name.empty() | ||
| && in_header.has(order_arg_col_name)) |
There was a problem hiding this comment.
!order_arg_col_name.empty() && in_header.has(order_arg_col_name) should be LOGICAL_ERROR guard; because if they are wrong but pipeline.getNumStreams() > 1 true then we use the else branch and do pipeline.resize(1); which directs multiple sorted streams in arbitrary order into one stream, losing global sorted order that we require, leading to wrong result.
| in_header, out_header, params, sort_description, limit)); | ||
| } | ||
|
|
||
| void TopNAggregatingStep::describeActions(FormatSettings & settings) const |
There was a problem hiding this comment.
We can make it more concise:
void TopNAggregatingStep::describeActions(FormatSettings & settings) const
{
params.explain(settings);
settings.out << settings.detail_prefix << "Limit " << limit << '\n';
settings.out << settings.detail_prefix << "Sort description: ";
dumpSortDescription(sort_description, settings);
settings.out << '\n';
}
void TopNAggregatingStep::describeActions(JSONBuilder::JSONMap & map) const
{
params.explain(map);
map.add("Limit", limit);
map.add("Sort Description", explainSortDescription(sort_description));
}| /// Scratch buffers reused across blocks by Aggregator::executeOnBlock. | ||
| ColumnRawPtrs key_columns; | ||
| Aggregator::AggregateColumns aggregate_columns; | ||
| bool no_more_keys = false; |
There was a problem hiding this comment.
If I have not missed anything, no_more_keys is not updated anywhere and can be removed.
| MutableColumns columns = getOutputPort().getHeader().cloneEmptyColumns(); | ||
| size_t total_groups = 0; | ||
| for (const auto & aggregated_chunk : aggregated) | ||
| { | ||
| const size_t rows = aggregated_chunk.chunk.getNumRows(); | ||
| if (rows == 0) | ||
| continue; | ||
| const auto & src = aggregated_chunk.chunk.getColumns(); | ||
| for (size_t i = 0; i < columns.size(); ++i) | ||
| columns[i]->insertRangeFrom(*src[i], 0, rows); | ||
| total_groups += rows; | ||
| } | ||
|
|
||
| if (total_groups == 0) | ||
| return {}; | ||
|
|
||
| const size_t output_limit = std::min(limit, total_groups); | ||
| const auto & sort_column = sort_description.front(); | ||
| const auto direction = sort_column.direction < 0 | ||
| ? IColumn::PermutationSortDirection::Descending | ||
| : IColumn::PermutationSortDirection::Ascending; | ||
|
|
||
| IColumn::Permutation permutation; | ||
| if (sort_column.collator) | ||
| columns[order_column_index]->getPermutationWithCollation( | ||
| *sort_column.collator, direction, IColumn::PermutationSortStability::Unstable, | ||
| output_limit, sort_column.nulls_direction, permutation); | ||
| else | ||
| columns[order_column_index]->getPermutation( | ||
| direction, IColumn::PermutationSortStability::Unstable, | ||
| output_limit, sort_column.nulls_direction, permutation); | ||
|
|
||
| Columns result_columns; | ||
| result_columns.reserve(columns.size()); | ||
| for (auto & column : columns) | ||
| result_columns.push_back(column->permute(permutation, output_limit)); | ||
|
|
||
| return Chunk(std::move(result_columns), output_limit); |
There was a problem hiding this comment.
We can simplify it greatly by using existing helpers:
const auto & header = getOutputPort().getHeader();
Blocks blocks;
blocks.reserve(aggregated.size());
for (auto & aggregated_chunk : aggregated)
blocks.push_back(header.cloneWithColumns(aggregated_chunk.chunk.detachColumns()));
Block block = concatenateBlocks(blocks);
if (block.rows() == 0)
return {};
sortBlock(block, sort_description, limit);
const size_t output_rows = std::min(limit, block.rows());
Columns result_columns = block.getColumns();
if (output_rows < block.rows())
{
for (auto & column : result_columns)
column = column->cut(0, output_rows);
}
return Chunk(std::move(result_columns), output_rows);There was a problem hiding this comment.
Similar to last PR, let's duplicate this test once for EXPLAIN queries and another for correctness. The correctness test should avoid any tags.
|
Also, let's add some performance tests for the query forms that we are optimizing. |
|
Dear @nihalzp, 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. |
|
Dear @nihalzp, 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. |
Related: #75098
Related: #98607
Optimizes
GROUP BY ... ORDER BY <min/max aggregate> LIMIT K. Today this executes as full aggregation → full sort → take K: it reads the whole table and usesO(unique groups)memory even though only K rows are returned.When the MergeTree table is physically sorted by the ORDER BY aggregate's argument (e.g. table
ORDER BY ts, queryORDER BY max(ts) DESC), the optimizer fuses the three steps into a singleTopNAggregatingstep. Reading in physical order, each group's aggregate is decided by its first occurrence, so the scan can stop once K distinct groups have been seen instead of reading the whole table. The operator holds the top K group states plus any groups already present in the input block being processed — early termination is checked at block boundaries, so peak memory is K plus one block's distinct groups rather than strictly O(K). The rows read are however many are needed to encounter the K-th distinct group in key order — not necessarily K rows — which is why the rewrite is gated on cardinality.Aggregation is delegated to the standard
Aggregator, reusing its type-dispatched andLowCardinality-aware hash methods and arena-managed states rather than a bespoke hash table. The rewrite is gated on the GROUP BY cardinality — it is skipped whenLIMITis large relative to the number of groups, where early termination cannot pay for the sorted single-stream read — and falls back to the standard pipeline for nullable / floating-point / collation-sensitive / reverse-flagged sort keys, computed (non-pass-through) aggregate arguments, merge-state aggregation (only_merge, e.g. when answered from an aggregate projection), forced projection (force_optimize_projection/force_optimize_projection_name),max_rows_to_group_by/max_rows_to_sort/max_bytes_to_sort,WITH TOTALS,exact_rows_before_limit,max_rows_to_group_by,max_rows_to_sort/max_bytes_to_sort, grouping sets,OFFSET, andWITH TIES.Known limitation: not supported together with
serialize_query_plan(parallel replicas) — the fused step is not serializable, so enabling both on an eligible query raisesNOT_IMPLEMENTED(same asoptimize_aggregation_in_order). The optimization is disabled by default in this release.Supports
max/minas the ORDER BY aggregate withany/argMax/argMincompanions on the same determining argument. Settings:optimize_topn_aggregation(default off for this first release — opt in withSET optimize_topn_aggregation = 1) — enable/disable the rewrite.topn_aggregation_max_ndv_ratio(default 0.5) — with columnuniqstatistics, apply whenLIMIT <= ndv * ratio;0disables the statistics path.topn_aggregation_max_limit(default 1000) — when statistics are absent, apply whenLIMIT <= max_limit;0requires statistics.Local A/B benchmark, Release, 50M-row tables,
GROUP BY k ORDER BY max(ts) DESC LIMIT 10(best of 3; results identical to the standard pipeline in every case):optimize_topn_aggregation=1=0(baseline)UInt32, 5M groupsLowCardinality(String), 5M groupsUInt32, 20 groupsThe gain grows with group cardinality: more distinct groups means a larger full aggregation + sort to avoid, while the fused path stops at the K-th distinct group and holds K group states plus the current input block's groups.
This is the first of a two-part split of #98607 (Mode 1, sorted input). The unsorted-input path — parallel partial top-K with threshold pruning and a dynamic
__topKFilterPREWHERE — follows in a separate PR. #98607 is closed in favour of the split.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Optimize
GROUP BY ... ORDER BY <min/max aggregate> LIMIT Kon aMergeTreetable sorted by the aggregate's argument: a fusedTopNAggregatingoperator reads in sort order and stops onceKdistinct groups have been seen, avoiding a full aggregation plus sort. The operator keeps the topKgroup states plus any groups already present in the current input block. Controlled by the newoptimize_topn_aggregationsetting (disabled by default in this release).