Skip to content

Order a GROUP BY without ORDER BY on its group keys - #20366

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

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

Conversation

@scottlan0113

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.

The rewrite only happens when the servers will use the sorted combine for the query: no HAVING, and a LIMIT below sortAggregateLimitThreshold (10,000 by default, or the query option). These queries are left as written:

  • queries that already have an ORDER BY
  • GROUPING SETS / ROLLUP / CUBE (the servers keep all their groups)
  • queries with HAVING, or with 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 rewrites only the queries that take the sorted combine, where the rewritten query was faster at LIMIT 10 and about the same at LIMIT 1,000 (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.
  • 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 like today.
  • It runs before the materialized view rewrite, so that rewrite sees the ORDER BY as if the user wrote it.

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.
  • 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.

Performance

One server, existing combine, 16 segments of 200,000 rows, about 815,000 groups, 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.72-0.73x (8.9-9.0 vs 12.3 MB) 0.44x (11.4 vs 25.7-25.9 ms)
LIMIT 1,000 yes 0.67-1.05x (7.9-13.1 vs 11.7-12.5 MB) 0.95-1.09x (13.9-15.8 vs 14.2-14.6 ms)
LIMIT 10,000, if ordered no 2.54-2.85x (33.9-35.3 vs 11.9-13.9 MB) 8.6x (114-123 vs 13.3-14.3 ms)
LIMIT 10,000, if ordered with sortAggregateLimitThreshold above the LIMIT no 2.82-2.84x (33.2-33.5 vs 11.7-11.9 MB) 2.33-2.48x (32.3-35.4 vs 13.9-14.2 ms)
LIMIT 100,000, if ordered no 6.35-6.37x (198.0-198.6 vs 31.2 MB) 55-59x (1,205-1,251 vs 20.5-22.7 ms)
LIMIT 100,000, if ordered with sortAggregateLimitThreshold above the LIMIT no 7.81-8.21x (243.7-256.1 vs 31.2 MB) 3.57-3.74x (79.4-82.0 vs 21.2-23.0 ms)
HAVING, LIMIT 1,000, if ordered no 9.7-10.5x (124.1-124.3 vs 11.9-12.8 MB) 82-93x (1,174-1,227 vs 13.2-14.3 ms)

Raising the threshold above the LIMIT makes the ordered query use the sorted combine. That is faster, but it uses about the same memory at LIMIT 10,000 and more 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.

Every ordered run returned the LIMIT smallest keys with complete values. Without HAVING, 7 of the 210 runs of the query as written returned a group with incomplete values, on this single server.

Tests

  • OrderByGroupKeysRewriterTest: which queries get rewritten (LIMIT against the default and a set threshold, HAVING, an invalid threshold), 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#testGroupByWithoutOrderByIsOrderedOnGroupKeys: the query sent to the servers and the query the materialized view rewrite sees both have the ORDER BY. A written ORDER BY is kept. A threshold set at the LIMIT leaves the query as written.
  • OfflineTimestampIndexIntegrationTest#testGroupBySse: the EXPLAIN plan now shows the sort in BROKER_REDUCE.

Validation

  • Rebased on master 4b3acc7721. The four test classes pass (3, 1, 37 and 8 tests).
  • spotless, license and checkstyle pass on pinot-common, pinot-core, pinot-broker and pinot-integration-tests. No compiler warnings on the added lines.

Labels

bugfix and release-notes, since the rows a GROUP BY without ORDER BY returns change.

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.46%. Comparing base (4b3acc7) to head (6ae9fc5).
⚠️ Report is 18 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff              @@
##             master   #20366      +/-   ##
============================================
+ Coverage     71.42%   71.46%   +0.04%     
  Complexity     1639     1639              
============================================
  Files          3607     3612       +5     
  Lines        243560   244158     +598     
  Branches      39555    39699     +144     
============================================
+ Hits         173953   174499     +546     
+ Misses        56562    56512      -50     
- Partials      13045    13147     +102     
Flag Coverage Δ
integration 100.00% <ø> (ø)
integration1 100.00% <ø> (ø)
integration2 0.00% <ø> (ø)
java-25 71.46% <100.00%> (+0.04%) ⬆️
lane-a 100.00% <ø> (ø)
lane-b 0.00% <ø> (ø)
temurin 71.46% <100.00%> (+0.04%) ⬆️
unittests 71.46% <100.00%> (+0.04%) ⬆️
unittests1 61.18% <100.00%> (+0.07%) ⬆️
unittests2 43.05% <84.21%> (+0.03%) ⬆️

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.

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.

// 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.

… 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.
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