Skip to content

Order a GROUP BY on all its group keys - #20366

Open
scottlan0113 wants to merge 5 commits into
apache:masterfrom
scottlan0113:groupby-order-by-keys
Open

scottlan0113 wants to merge 5 commits into
apache:masterfrom
scottlan0113:groupby-order-by-keys

Conversation

@scottlan0113

@scottlan0113 scottlan0113 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A GROUP BY without ORDER BY can return incomplete groups. Each server stops adding groups once it has LIMIT of them, so different servers can keep different groups. A group the broker returns can then miss the values from the servers that dropped it. See #8039 and item 2 of #11706.

With this PR, the single-stage broker adds ORDER BY <all group-by expressions> ASC to such a query before sending it to the servers. Then every segment, every server and the broker keep the same smallest keys, so each returned group is complete (as long as no segment hits numGroupsLimit), and the result is the same on every run.

A GROUP BY that already has an ORDER BY gets the group-by expressions it doesn't order on appended, ascending and in the GROUP BY order, after its own terms, whose directions and null ordering stay as written. For example, GROUP BY a, b ORDER BY SUM(x) DESC, a DESC becomes ORDER BY SUM(x) DESC, a DESC, b ASC. Groups that tie on the written terms then come back in one order. This applies with HAVING and at any LIMIT. Whether the servers may keep only LIMIT groups is still decided by the existing rule: an ORDER BY on exactly the group-by expressions, without HAVING.

A GROUP BY without ORDER BY is only rewritten when the servers will use the sorted combine for it: no HAVING, and a LIMIT below sortAggregateLimitThreshold (10,000 by default, or the query option). These queries are left as written:

  • GROUPING SETS / ROLLUP / CUBE, with or without ORDER BY: their visible group-by expressions don't tell apart every group they return, and without ORDER BY the servers keep all their groups
  • queries without ORDER BY that have HAVING, or a LIMIT at or above the threshold. Ordering them would make them use more memory and run slower (numbers below).

An earlier PR, #8758, added the same rewrite behind a broker config, off by default, and was closed. The concern there was the cost for queries without ORDER BY. This PR adds an ORDER BY only to the queries that will take the sorted combine. With the default threshold, the rewritten query took about half the wall time at LIMIT 10 and 1.08-1.10x at LIMIT 1,000, with less heap at both. A query that sets the threshold above a larger LIMIT is rewritten too, and costs more there: at LIMIT 100,000, 7.8-8.2x the heap and about 3.5x the wall time of the query as written (numbers below).

For a GROUP BY ordered on exactly its group-by expressions without HAVING, the generic server combine and the broker reduce now keep LIMIT groups instead of max(5 * LIMIT, the minimum trim size), and trim at 2 * LIMIT instead of at the trim threshold. At LIMIT 100,000 that takes such a query on the generic combine from 6.4x to 1.55x the heap of the query as written, at 1.15x the wall time it took before (numbers below).

How it works:

  • OrderByGroupKeysRewriter (pinot-common) does the rewrite. It is not in the default rewriter list. The broker calls it in BaseSingleStageBrokerRequestHandler.compileRequest, so materialized view definitions, the multi-stage engine and queries sent straight to a server don't change.
  • For a query with an ORDER BY, it only appends the group-by expressions that are missing; the servers' rule for trimming (QueryContext.isUnsafeTrim()) is unchanged.
  • It reads sortAggregateLimitThreshold the same way the servers do. If the value is invalid, the query is left as is and the servers reject it as before.
  • It runs before the materialized view rewrite, so that rewrite sees the ORDER BY as if the user wrote it.
  • GroupByUtils.getTrimSize and getTrimThreshold size the server combine table and the broker reduce table: LIMIT and 2 * LIMIT under a safe trim (QueryContext.isUnsafeTrim() false). A threshold that disables trimming still disables it; an unsafe trim keeps the old sizes.

Behavior change

  • For a GROUP BY without ORDER BY, without HAVING and with a LIMIT below the threshold, the rows now come back sorted by the group keys, and they are the smallest keys instead of whatever groups the servers built first.
  • For a GROUP BY whose ORDER BY leaves out some group-by expressions, those are appended. If it was ordered only on some of its group keys and has no HAVING, it is now ordered on all of them: the servers may keep only LIMIT groups (in each segment and in the combine, which is the sorted combine below the threshold), and the result is exact even when it is trimmed. A query ordered on an aggregate or with HAVING is trimmed as before; only its ties get an order.
  • For a GROUP BY ordered on exactly its group-by expressions without HAVING, the generic combine now returns LIMIT groups instead of max(5 * LIMIT, the minimum trim size), and it and the broker reduce trim at 2 * LIMIT instead of at the trim threshold. The result doesn't change.
  • accurateGroupByWithoutOrderBy (Enable Correct GROUP BY-Only Processing with accurateGroupByWithoutOrderBy #15844) no longer applies to these queries in the single-stage engine, since they now have an ORDER BY. It still applies to the queries left as written.
  • EXPLAIN for these queries shows the sort in BROKER_REDUCE, including the appended group-by expressions.

Performance

Master ed05b38759 with this PR's GroupByUtils; the rewritten queries run with their ORDER BY written out. One server, existing combine, 16 segments of 200,000 rows; each segment stops at the default numGroupsLimit (100,000), about 815,000 groups in all. SELECT d1, SUM(m1) FROM t GROUP BY d1 .... Two JVMs (four for LIMIT 1,000). Each number is against the query as written in the same JVMs.

Query Rewritten? Heap at the peak Wall
LIMIT 10 (the default) yes 0.67-0.79x (8.3-9.7 vs 12.3 MB) 0.50-0.51x (12.6-13.1 vs 25.1-25.4 ms)
LIMIT 1,000 yes 0.80-0.87x (9.8-10.9 vs 11.7-12.5 MB) 1.08-1.10x (15.4-16.6 vs 14.1-15.4 ms)
LIMIT 10,000, if ordered no 2.91-3.02x (34.3-35.3 vs 11.7-11.8 MB) 9.0-9.7x (130-135 vs 13.9-14.5 ms)
LIMIT 10,000, sortAggregateLimitThreshold set above the LIMIT yes 2.81-3.02x (33.1-35.3 vs 11.7-11.8 MB) 2.16-2.43x (31.3-33.9 vs 13.9-14.5 ms)
LIMIT 100,000, if ordered no 1.55x (48.3 vs 31.2 MB) 64-68x (1,452-1,469 vs 21.7-22.5 ms)
LIMIT 100,000, sortAggregateLimitThreshold set above the LIMIT yes 7.79-8.18x (243.2-255.1 vs 31.2 MB) 3.45-3.55x (77.2-77.6 vs 21.7-22.5 ms)
HAVING, LIMIT 1,000, if ordered no 9.8-10.6x (124.5 vs 11.7-12.7 MB) 81-87x (1,150-1,155 vs 13.3-14.3 ms)

Before this PR's change to the generic combine, which kept max(5 * LIMIT, 5,000) groups and trimmed at 1,000,000, the ordered query took 33.6-35.3 MB and 119.6-120.4 ms at LIMIT 10,000, and 198.3-199.1 MB and 1,263-1,276 ms at LIMIT 100,000, in the same JVMs. So at LIMIT 100,000 it now takes 0.24x the heap and 1.15x the wall time; at LIMIT 10,000, about the same heap and 1.08-1.13x the wall time.

Setting the threshold above the LIMIT gets the query rewritten and sends it to the sorted combine. That is faster than the ordered query on the generic combine (3.97-4.15x at LIMIT 10,000, 18.7-19.0x at 100,000), but uses about the same memory at LIMIT 10,000 and 5.0-5.3x at 100,000. Each task builds a sorted table of up to LIMIT groups for its segment before merging, while the query as written keeps about LIMIT groups in one shared table.

Completing an existing ORDER BY was not measured. A query ordered on an aggregate or with HAVING is still unsafe to trim, so it keeps as many groups and takes the same combine as before; only its ties are now broken by the group keys.

Every ordered run returned the LIMIT smallest keys with complete values, checked against the answer under the same numGroupsLimit. Without HAVING, 2 of the 210 runs of the query as written returned a group with incomplete values, on this single server.

Tests

  • OrderByGroupKeysRewriterTest: which queries without ORDER BY get rewritten (LIMIT against the default and a set threshold, HAVING, an invalid threshold); an existing ORDER BY completed in the GROUP BY order after its own terms, with its null ordering kept, with HAVING, at a LIMIT at the threshold and through an alias; a complete ORDER BY and grouping sets left as written; and that the result is the same as writing the ORDER BY yourself.
  • GroupByWithoutOrderByQueriesTest: two servers that build different groups first. With the rewrite, every returned group has values from both servers. Without it, each has values from only one.
  • BaseSingleStageBrokerRequestHandlerTest#testGroupByIsOrderedOnItsGroupKeys: the query sent to the servers and the query the materialized view rewrite sees both have the ORDER BY. A written ORDER BY gets the missing group key appended. The servers still treat an ORDER BY on an aggregate, or with HAVING, as unsafe to trim, and an ORDER BY on some group keys completed without HAVING as safe. A threshold set at the LIMIT leaves a query without ORDER BY as written.
  • OfflineTimestampIndexIntegrationTest#testGroupBySse: the EXPLAIN plan now shows the sort in BROKER_REDUCE.
  • GroupByTrimmingTest: the single-stage queries ordered on some group-by keys are now safe to trim (three tests renamed ...IsSafe), and the EXPLAIN plans show the appended keys. The multi-stage tests are unchanged.
  • OfflineClusterIntegrationTest#testExplainPlanQueryV1 (also run by MultiNodesOfflineClusterIntegrationTest): the EXPLAIN plan shows the appended key.
  • GroupByUtilsTest: the trim size and threshold for a query ordered on its group keys (LIMIT and 2 * LIMIT; a threshold that disables trimming still does) and for one ordered on an aggregate (unchanged). The server combine and broker reduce tables of a query ordered on its group keys, given 1,000 keys each upserted twice in shuffled order, never hold more than 2 * LIMIT groups and return the LIMIT smallest keys with complete values. A combine table keeps the LIMIT largest keys when descending, and max(5 * LIMIT, 5,000) groups when ordered on an aggregate or with HAVING.

Validation

  • Based on master 4b3acc7721. These pass on cbf7c27c9c (the last commit only adds a TODO comment): OrderByGroupKeysRewriterTest (4), GroupByWithoutOrderByQueriesTest (1), BaseSingleStageBrokerRequestHandlerTest (37), OfflineTimestampIndexIntegrationTest (8), GroupByTrimmingTest (20), testExplainPlanQueryV1 in OfflineClusterIntegrationTest and MultiNodesOfflineClusterIntegrationTest, GroupByUtilsTest (8), GroupByTrimTest (10), BrokerReduceServiceTest (6), StreamingGroupByCombineOperatorTest (9), MergeDataTablesOnlyTest (27), HavingFilterHandlerTest (4), GroupByFinalSchemaTest (2), ExplainPlanQueriesTest (32), InterSegmentGroupBySingleValueQueriesTest (44), InterSegmentGroupByMultiValueQueriesTest (18), InterSegmentGroupByMultiValueRawQueriesTest (18) and InterSegmentAggregationSingleValueQueriesTest (21).
  • spotless, license and checkstyle pass on pinot-common, pinot-core, pinot-broker and pinot-integration-tests. No compiler warnings on the added lines.

Follow-up

The rewrite of a GROUP BY without ORDER BY still applies only without HAVING and below the threshold. The other cases need a separate combine algorithm for a deterministic ordering; a TODO in OrderByGroupKeysRewriter marks them.

Labels

bugfix and release-notes, since the rows a GROUP BY without ORDER BY returns change, as do the tied rows of one with an ORDER BY.

A GROUP BY query without an ORDER BY can return groups with incomplete
values: a server stops adding groups once it holds LIMIT of them, so two
servers can keep different groups, and a group the broker returns misses
the values of the servers that dropped it.

The single-stage broker now orders such a query on all its group-by
expressions, ascending, in the query it sends to the servers, when the
servers then merge it in the sorted combine: without HAVING, and with a
LIMIT below sortAggregateLimitThreshold (10,000 unless the query sets
it). Every segment, server and the broker keep the smallest keys, so each
returned group is complete as long as no segment reaches numGroupsLimit.
A query with HAVING or a larger LIMIT stays as written: ordered, it would
keep more groups than as written and sort them.

OrderByGroupKeysRewriter is not in the default rewriter list, so
materialized view definitions and the multi-stage engine are unchanged.
The broker applies it before the materialized view rewrite, which sees
the ordering as a written ORDER BY.
@codecov-commenter

codecov-commenter commented Nov 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 71.49%. Comparing base (4b3acc7) to head (cbf7c27).
⚠️ Report is 28 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff              @@
##             master   #20366      +/-   ##
============================================
+ Coverage     71.42%   71.49%   +0.07%     
  Complexity     1639     1639              
============================================
  Files          3607     3618      +11     
  Lines        243560   244696    +1136     
  Branches      39555    39788     +233     
============================================
+ Hits         173953   174947     +994     
+ Misses        56562    56558       -4     
- Partials      13045    13191     +146     
Flag Coverage Δ
integration 100.00% <ø> (ø)
integration1 100.00% <ø> (ø)
integration2 0.00% <ø> (ø)
java-25 71.49% <100.00%> (+0.07%) ⬆️
lane-a 100.00% <ø> (ø)
lane-b 0.00% <ø> (ø)
temurin 71.49% <100.00%> (+0.07%) ⬆️
unittests 71.49% <100.00%> (+0.07%) ⬆️
unittests1 61.19% <100.00%> (+0.08%) ⬆️
unittests2 43.18% <65.30%> (+0.16%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

A query not built by the parser can come without an options map; the
rewriter then compares the LIMIT with the default
sortAggregateLimitThreshold. Every query the test compiled had a map,
so that branch never ran.

@Jackie-Jiang Jackie-Jiang 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.

I'd like to separate deterministic ordering from combine selection and improve generic-combine retention before broadening the rewrite. The additional leading-group-key optimization is optional.

Comment on lines +60 to +62
public PinotQuery rewrite(PinotQuery pinotQuery) {
if (pinotQuery.getGroupByListSize() == 0 || pinotQuery.getOrderByListSize() > 0
|| pinotQuery.getGroupingSets() != null || pinotQuery.getHavingExpression() != null

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.

Can we generalize this to preserve any existing ORDER BY and append missing GROUP BY expressions as tie-breakers, including queries with HAVING? Preserve existing directions and null ordering, then append missing expressions in GROUP BY order. For example, GROUP BY a, b ORDER BY SUM(x) DESC, a DESC becomes ORDER BY SUM(x) DESC, a DESC, b ASC.

HAVING should affect safe-trimming eligibility, while sortAggregateLimitThreshold should select the combine algorithm; neither needs to prevent completing an existing ordering. Queries with HAVING or aggregate-based ordering must still be treated as unsafe for early LIMIT trimming. We can keep grouping sets excluded because their visible group keys do not uniquely identify every output group.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 6ae9fc5. An existing ORDER BY keeps its terms, directions and null ordering, and the missing GROUP BY expressions are appended ASC in GROUP BY order, with HAVING and at any LIMIT. Grouping sets are still skipped. Trimming is still decided by isUnsafeTrim(), so HAVING and aggregate ordering stay unsafe. One effect in the single-stage engine: a query ordered on only some of its group keys, without HAVING, is now ordered on all of them, so it becomes safe to trim. Three GroupByTrimmingTest tests are renamed ...IsSafe for that.

Comment on lines +87 to +88
return pinotQuery.getLimit() < (sortAggregateLimitThreshold != null ? sortAggregateLimitThreshold
: Server.DEFAULT_SORT_AGGREGATE_LIMIT_THRESHOLD);

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.

Before enabling the rewrite more broadly, we should improve generic server combine for complete group-key ordering without HAVING. It can safely retain only LIMIT groups, but currently oversamples to max(5 * LIMIT, minServerGroupTrimSize) and can accumulate up to the configured trim threshold. We should optimize both intermediate retention and final output, then benchmark large-LIMIT queries across generic and sorted combine.

This threshold alone is also not a sufficient performance bound: sortAggregateLimitThreshold=100001 with LIMIT 100000 is rewritten, as the new test verifies, while the supplied benchmark reports roughly 8x heap and 3.6x runtime for that sorted-combine case. Optimizing generic combine is a prerequisite for broadening the rewrite, but does not by itself resolve that sorted-combine overhead.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in cbf7c27. For complete group-key ordering without HAVING, the generic server combine and the broker reduce now keep LIMIT groups instead of max(5 * LIMIT, min trim size), and trim at 2 * LIMIT instead of at the trim threshold.

Large-LIMIT benchmark: SELECT d1, SUM(m1) FROM t GROUP BY d1 [ORDER BY d1] LIMIT n, one server, 16 segments of 200,000 rows (each hits numGroupsLimit 100,000), master ed05b38, 2 JVMs. Heap at the peak, wall:

LIMIT 10,000 LIMIT 100,000
No ORDER BY 11.7-11.8 MB, 13.9-14.5 ms 31.2 MB, 21.7-22.5 ms
Generic combine, before 33.6-35.3 MB, 120 ms 198.3-199.1 MB, 1,263-1,276 ms
Generic combine, this PR 34.3-35.3 MB, 130-135 ms 48.3 MB, 1,452-1,469 ms
Sorted combine (threshold above the LIMIT) 33.1-35.3 MB, 31-34 ms 243.2-255.1 MB, 77 ms

At LIMIT 100,000 this PR takes 0.24x the heap and 1.15x the wall of before; at LIMIT 10,000, the same heap and 1.08-1.13x the wall. The sorted combine is 18.7-19.0x faster than this PR at LIMIT 100,000, with 5.0-5.3x the heap. All ordered runs were exact against the answer under the same numGroupsLimit.

The rewrite stays on the sorted-combine case for now, with a TODO for the other cases (408e61c). The description is updated and states the sorted-combine cost at LIMIT 100,000: 7.8-8.2x the heap and about 3.5x the wall of the query as written.

// TODO: Keeping only 'LIMIT' groups can cause inaccurate result because the groups are randomly selected
// without ordering. Consider ordering on group-by columns if no ordering is specified.
// without ordering. The single-stage broker orders such a query on its group-by columns when its LIMIT
// is below the sort aggregate limit threshold (OrderByGroupKeysRewriter). Consider a larger LIMIT too.

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.

Optional follow-up: we could use a leading group-key ORDER BY prefix to reduce overfetch further. Without HAVING, if that prefix includes all group keys, retaining only LIMIT is safe even when aggregate expressions follow, since those expressions cannot distinguish different groups after the full key tuple.

If the prefix covers only some group keys, prefix-based pruning must retain all ties at the cutoff. For example, GROUP BY country, city ORDER BY country, SUM(revenue) DESC LIMIT 10 cannot simply retain 10 local groups: cities within the boundary country still compete on partial aggregates. That boundary bucket may exceed 5 * LIMIT, so the first ordering key being a group key is not by itself enough for an exact LIMIT cap.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks, leaving this out of this PR.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks, leaving this out of this PR.

… expressions

A GROUP BY whose ORDER BY leaves out some group-by expressions ranks the groups that tie on the written terms in
whatever order the servers meet them, so the servers can keep different groups and the result can change between
runs. The single-stage broker now appends each group-by expression the ORDER BY does not order on, ascending and in
the GROUP BY order, after the written terms, whose directions and null ordering stay as written. HAVING and
sortAggregateLimitThreshold do not stop it. GROUPING SETS, ROLLUP and CUBE are still left as written: their visible
group-by expressions do not tell apart every group they return.

The rule for keeping only LIMIT groups is unchanged: an ORDER BY on exactly the group-by expressions, without HAVING
(QueryContext.isUnsafeTrim). A query ordered on an aggregate or with HAVING is trimmed as before. One ordered on some
of its group-by expressions without HAVING is now ordered on all of them, so its segments keep LIMIT groups, it takes
the sorted combine below the threshold, and its result is exact when it is trimmed. A GROUP BY without ORDER BY is
still rewritten only without HAVING and below the threshold.

GroupByTrimmingTest: the single-stage queries ordered on some group-by keys are now safe to trim, and the explain
plans show the appended keys, as does OfflineClusterIntegrationTest#testExplainPlanQueryV1.
@scottlan0113 scottlan0113 changed the title Order a GROUP BY without ORDER BY on its group keys Order a GROUP BY on all its group keys Nov 25, 2026
Ordered only on its group keys with no HAVING (a safe trim), a GROUP BY's LIMIT smallest keys are among the LIMIT
smallest of every table that has them. The server combine table and the broker reducer table now keep LIMIT groups
under a safe trim, instead of max(5 * LIMIT, the minimum trim size), and trim once they hold twice that, instead of
growing to the configured trim threshold first. A threshold that disables the trim still disables it.

GroupByUtilsTest covers both rules and both tables, with every key upserted twice in shuffled order.
A GROUP BY without ORDER BY that has HAVING or a LIMIT at or above sortAggregateLimitThreshold is still left as
written. Ordering it needs a separate combine algorithm for a deterministic ordering.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants