Repository navigation
Order a GROUP BY on all its group keys - #20366
scottlan0113 wants to merge 5 commits into
Conversation
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 Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
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
left a comment
There was a problem hiding this comment.
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.
| public PinotQuery rewrite(PinotQuery pinotQuery) { | ||
| if (pinotQuery.getGroupByListSize() == 0 || pinotQuery.getOrderByListSize() > 0 | ||
| || pinotQuery.getGroupingSets() != null || pinotQuery.getHavingExpression() != null |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| return pinotQuery.getLimit() < (sortAggregateLimitThreshold != null ? sortAggregateLimitThreshold | ||
| : Server.DEFAULT_SORT_AGGREGATE_LIMIT_THRESHOLD); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Thanks, leaving this out of this PR.
There was a problem hiding this comment.
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.
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.
Summary
A GROUP BY without ORDER BY can return incomplete groups. Each server stops adding groups once it has
LIMITof 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> ASCto 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 hitsnumGroupsLimit), 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 DESCbecomesORDER 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 anyLIMIT. Whether the servers may keep onlyLIMITgroups 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
LIMITbelowsortAggregateLimitThreshold(10,000 by default, or the query option). These queries are left as written:LIMITat 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
LIMITis 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
LIMITgroups instead ofmax(5 * LIMIT, the minimum trim size), and trim at2 * LIMITinstead 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 inBaseSingleStageBrokerRequestHandler.compileRequest, so materialized view definitions, the multi-stage engine and queries sent straight to a server don't change.QueryContext.isUnsafeTrim()) is unchanged.sortAggregateLimitThresholdthe same way the servers do. If the value is invalid, the query is left as is and the servers reject it as before.GroupByUtils.getTrimSizeandgetTrimThresholdsize the server combine table and the broker reduce table:LIMITand2 * LIMITunder a safe trim (QueryContext.isUnsafeTrim()false). A threshold that disables trimming still disables it; an unsafe trim keeps the old sizes.Behavior change
LIMITbelow 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.LIMITgroups (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.LIMITgroups instead ofmax(5 * LIMIT, the minimum trim size), and it and the broker reduce trim at2 * LIMITinstead 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.BROKER_REDUCE, including the appended group-by expressions.Performance
Master
ed05b38759with this PR'sGroupByUtils; 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 defaultnumGroupsLimit(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.sortAggregateLimitThresholdset above theLIMITsortAggregateLimitThresholdset above theLIMITBefore 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
LIMITgets 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 toLIMITgroups for its segment before merging, while the query as written keeps aboutLIMITgroups 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
LIMITsmallest keys with complete values, checked against the answer under the samenumGroupsLimit. 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 (LIMITagainst 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 aLIMITat 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 theLIMITleaves a query without ORDER BY as written.OfflineTimestampIndexIntegrationTest#testGroupBySse: the EXPLAIN plan now shows the sort inBROKER_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 byMultiNodesOfflineClusterIntegrationTest): the EXPLAIN plan shows the appended key.GroupByUtilsTest: the trim size and threshold for a query ordered on its group keys (LIMITand2 * 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 than2 * LIMITgroups and return theLIMITsmallest keys with complete values. A combine table keeps theLIMITlargest keys when descending, andmax(5 * LIMIT, 5,000)groups when ordered on an aggregate or with HAVING.Validation
4b3acc7721. These pass oncbf7c27c9c(the last commit only adds a TODO comment):OrderByGroupKeysRewriterTest(4),GroupByWithoutOrderByQueriesTest(1),BaseSingleStageBrokerRequestHandlerTest(37),OfflineTimestampIndexIntegrationTest(8),GroupByTrimmingTest(20),testExplainPlanQueryV1inOfflineClusterIntegrationTestandMultiNodesOfflineClusterIntegrationTest,GroupByUtilsTest(8),GroupByTrimTest(10),BrokerReduceServiceTest(6),StreamingGroupByCombineOperatorTest(9),MergeDataTablesOnlyTest(27),HavingFilterHandlerTest(4),GroupByFinalSchemaTest(2),ExplainPlanQueriesTest(32),InterSegmentGroupBySingleValueQueriesTest(44),InterSegmentGroupByMultiValueQueriesTest(18),InterSegmentGroupByMultiValueRawQueriesTest(18) andInterSegmentAggregationSingleValueQueriesTest(21).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
OrderByGroupKeysRewritermarks them.Labels
bugfixandrelease-notes, since the rows a GROUP BY without ORDER BY returns change, as do the tied rows of one with an ORDER BY.