Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@
import org.apache.pinot.sql.parsers.CalciteSqlParser;
import org.apache.pinot.sql.parsers.SqlNodeAndOptions;
import org.apache.pinot.sql.parsers.rewriter.ExprMinMaxRewriter;
import org.apache.pinot.sql.parsers.rewriter.OrderByGroupKeysRewriter;
import org.apache.pinot.sql.parsers.rewriter.RlsFiltersRewriter;
import org.apache.pinot.sql.parsers.rewriter.RlsUtils;
import org.slf4j.Logger;
Expand All @@ -167,6 +168,7 @@ public abstract class BaseSingleStageBrokerRequestHandler extends BaseBrokerRequ
Set.of(CommonConstants.RewriterConstants.CHILD_AGGREGATION_NAME_PREFIX + EXPR_MIN,
CommonConstants.RewriterConstants.CHILD_AGGREGATION_NAME_PREFIX + EXPR_MAX);
private static final int MAX_UNAVAILABLE_SEGMENTS_TO_PRINT_IN_QUERY_EXCEPTION = 10;
private static final OrderByGroupKeysRewriter ORDER_BY_GROUP_KEYS_REWRITER = new OrderByGroupKeysRewriter();

protected final QueryOptimizer _queryOptimizer = new QueryOptimizer();
@Nullable
Expand Down Expand Up @@ -1292,6 +1294,10 @@ private CompileResult compileRequest(long requestId, String query, SqlNodeAndOpt
if (_enableDistinctCountBitmapOverride) {
handleDistinctCountBitmapOverride(serverPinotQuery);
}
// Order a GROUP BY without ORDER BY on its group keys when the servers then take the sorted combine, so that every
// server and the reduce, which reads this query, keep the same groups. The materialized view rewrite runs later and
// sees the ordering as if the user wrote it.
ORDER_BY_GROUP_KEYS_REWRITER.rewrite(serverPinotQuery);

Schema schema = _tableCache.getSchema(rawTableName);
_queryOptimizer.optimize(serverPinotQuery, schema);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
import org.apache.pinot.common.response.BrokerResponse;
import org.apache.pinot.common.response.broker.BrokerResponseNative;
import org.apache.pinot.common.response.broker.QueryProcessingException;
import org.apache.pinot.core.query.request.context.utils.QueryContextConverterUtils;
import org.apache.pinot.core.routing.RoutingTable;
import org.apache.pinot.core.routing.SegmentsToQuery;
import org.apache.pinot.core.routing.TableRouteInfo;
Expand Down Expand Up @@ -1038,6 +1039,114 @@ protected BrokerResponseNative processMaterializedViewSplitBrokerRequest(long re
};
}

/// A GROUP BY without ORDER BY is ordered on its group keys before the materialized view rewrite, which sees the
/// ordering as if the user had written it, and goes to the servers that way; the reduce reads the same query. The
/// rewrite reads the options of the query. A written ORDER BY gets the group keys it does not order on appended, and
/// the servers keep only `LIMIT` groups of it only when it then orders on the group keys alone, without HAVING.
@Test
public void testGroupByIsOrderedOnItsGroupKeys()
throws Exception {
String tableName = "baseTable_OFFLINE";
TableCache tableCache = mock(TableCache.class);
TableConfig tableCfg = mock(TableConfig.class);
when(tableCache.getActualTableName(anyString())).thenReturn(tableName);
when(tableCache.getColumnNameMap(anyString())).thenReturn(Map.of("ts", "ts", "revenue", "revenue"));
when(tableCfg.getTenantConfig()).thenReturn(new TenantConfig("tier_BROKER", "tier_SERVER", null));
when(tableCache.getTableConfig(tableName)).thenReturn(tableCfg);
BrokerRoutingManager routingManager = mock(BrokerRoutingManager.class);
when(routingManager.routingExists(tableName)).thenReturn(true);
when(routingManager.getQueryTimeoutMs(tableName)).thenReturn(10000L);
RoutingTable rt = mock(RoutingTable.class);
when(rt.getServerInstanceToSegmentsMap()).thenReturn(
Map.of(new ServerInstance(new InstanceConfig("Server_localhost_9000")),
new SegmentsToQuery(List.of("segment01"), List.of())));
when(routingManager.getRoutingTable(any(), anyLong())).thenReturn(rt);
QueryQuotaManager queryQuotaManager = mock(QueryQuotaManager.class);
when(queryQuotaManager.acquire(anyString())).thenReturn(true);
when(queryQuotaManager.acquireDatabase(anyString())).thenReturn(true);
when(queryQuotaManager.acquireApplication(anyString())).thenReturn(true);
AtomicReference<PinotQuery> querySeenByMaterializedViewRewrite = new AtomicReference<>();
MaterializedViewQueryRewriteEngine materializedViewEngine = mock(MaterializedViewQueryRewriteEngine.class);
when(materializedViewEngine.tryRewrite(any(PinotQuery.class), anyString())).thenAnswer(invocation -> {
querySeenByMaterializedViewRewrite.set(((PinotQuery) invocation.getArgument(0)).deepCopy());
return null;
});
BrokerMetrics.register(mock(BrokerMetrics.class));
PinotConfiguration config = new PinotConfiguration();
BrokerQueryEventListenerFactory.init(config);
AtomicReference<BrokerRequest> serverRequest = new AtomicReference<>();
BaseSingleStageBrokerRequestHandler handler =
new BaseSingleStageBrokerRequestHandler(config, "testBrokerId", new BrokerRequestIdGenerator(), routingManager,
new AllowAllAccessControlFactory(), queryQuotaManager, tableCache,
ThreadAccountantUtils.getNoOpAccountant(), null,
new DefaultMaterializedViewHandler(materializedViewEngine)) {
@Override
public void start() {
}

@Override
public void shutDown() {
}

@Override
protected BrokerResponseNative processBrokerRequest(long requestId, BrokerRequest originalBrokerRequest,
BrokerRequest serverBrokerRequest, TableRouteInfo route, long timeoutMs, ServerStats serverStats,
RequestContext requestContext) {
serverRequest.set(serverBrokerRequest);
return BrokerResponseNative.empty();
}

@Override
protected BrokerResponseNative processMaterializedViewSplitBrokerRequest(long requestId,
long materializedViewRequestId, BrokerRequest originalBrokerRequest, TableRouteInfo baseRoute,
TableRouteInfo materializedViewRoute, long timeoutMs, ServerStats serverStats,
RequestContext requestContext) {
throw new UnsupportedOperationException("Not implemented in test");
}
};

BrokerResponseNative response =
(BrokerResponseNative) handler.handleRequest("SELECT ts, SUM(revenue) FROM baseTable GROUP BY ts LIMIT 100");
assertTrue(response.getExceptions().isEmpty(), response.getExceptions().toString());
List<Expression> orderByKeys = CalciteSqlParser.compileToPinotQuery(
"SELECT ts, SUM(revenue) FROM baseTable GROUP BY ts ORDER BY ts LIMIT 100").getOrderByList();
assertEquals(querySeenByMaterializedViewRewrite.get().getOrderByList(), orderByKeys);
assertEquals(serverRequest.get().getPinotQuery().getOrderByList(), orderByKeys);

// A written ORDER BY keeps its terms, and the group key it does not order on follows them
response = (BrokerResponseNative) handler.handleRequest(
"SELECT ts, SUM(revenue) FROM baseTable GROUP BY ts ORDER BY SUM(revenue) DESC LIMIT 100");
assertTrue(response.getExceptions().isEmpty(), response.getExceptions().toString());
List<Expression> completedOrderBy = CalciteSqlParser.compileToPinotQuery(
"SELECT ts, SUM(revenue) FROM baseTable GROUP BY ts ORDER BY SUM(revenue) DESC, ts LIMIT 100").getOrderByList();
assertEquals(querySeenByMaterializedViewRewrite.get().getOrderByList(), completedOrderBy);
assertEquals(serverRequest.get().getPinotQuery().getOrderByList(), completedOrderBy);
// Ordered on an aggregate, the servers still keep more than LIMIT groups
assertTrue(QueryContextConverterUtils.getQueryContext(serverRequest.get().getPinotQuery()).isUnsafeTrim());

// With HAVING too, though the completed order is on the group keys alone
response = (BrokerResponseNative) handler.handleRequest(
"SELECT ts, revenue, COUNT(*) FROM baseTable GROUP BY ts, revenue HAVING COUNT(*) > 1 ORDER BY revenue DESC "
+ "LIMIT 100");
assertTrue(response.getExceptions().isEmpty(), response.getExceptions().toString());
assertEquals(serverRequest.get().getPinotQuery().getOrderByList(), CalciteSqlParser.compileToPinotQuery(
"SELECT ts, revenue, COUNT(*) FROM baseTable GROUP BY ts, revenue ORDER BY revenue DESC, ts LIMIT 100")
.getOrderByList());
assertTrue(QueryContextConverterUtils.getQueryContext(serverRequest.get().getPinotQuery()).isUnsafeTrim());

// Ordered on some of the group keys without HAVING, the completed order is on all of them: LIMIT groups suffice
response = (BrokerResponseNative) handler.handleRequest(
"SELECT ts, revenue, COUNT(*) FROM baseTable GROUP BY ts, revenue ORDER BY revenue DESC LIMIT 100");
assertTrue(response.getExceptions().isEmpty(), response.getExceptions().toString());
assertFalse(QueryContextConverterUtils.getQueryContext(serverRequest.get().getPinotQuery()).isUnsafeTrim());

// At this sortAggregateLimitThreshold the servers would not take the sorted combine, so the query goes as written
response = (BrokerResponseNative) handler.handleRequest(
"SET sortAggregateLimitThreshold = 100; SELECT ts, SUM(revenue) FROM baseTable GROUP BY ts LIMIT 100");
assertTrue(response.getExceptions().isEmpty(), response.getExceptions().toString());
assertEquals(serverRequest.get().getPinotQuery().getOrderByListSize(), 0);
}

/// A query with an RLS filter skips the MV rewrite: the broker looks up the RLS filter of the base table
/// "baseTable_OFFLINE", and the query runs on the base table with that filter in its options.
@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pinot.sql.parsers.rewriter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.pinot.common.request.Expression;
import org.apache.pinot.common.request.PinotQuery;
import org.apache.pinot.common.utils.config.QueryOptionsUtils;
import org.apache.pinot.common.utils.request.RequestUtils;
import org.apache.pinot.spi.utils.CommonConstants.Server;
import org.apache.pinot.sql.parsers.CalciteSqlParser;


/// Completes the order of a GROUP BY query on its group-by expressions, so that groups the query ranks alike still have
/// one order: every server and the broker then keep the same groups, and the result is the same on every run.
///
/// A query with an ORDER BY gets the group-by expressions it does not order on appended, ascending and in the GROUP BY
/// order; its own terms keep their place, direction and null ordering. HAVING and `sortAggregateLimitThreshold` do
/// not change this. Whether the servers may keep only `LIMIT` groups is decided apart from it, by 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, while one ordered on some of its group-by expressions without HAVING is then
/// ordered on all of them and may be trimmed to `LIMIT`, its combine picked by the threshold.
///
/// A query without an ORDER BY is ordered on all its group-by expressions, ascending, when the servers then merge it in
/// the sorted combine: without HAVING, and with a `LIMIT` below `sortAggregateLimitThreshold`, as in
/// `QueryContext.shouldSortAggregateUnderSafeTrim()`. Without an ORDER BY, a server stops adding groups once it holds
/// enough of them for the result, so two servers can keep different groups, and a group the broker returns can miss the
/// values of the servers that dropped it. Ordered on the group keys, every segment, server and the broker keep the
/// smallest keys. Without HAVING the trim is safe: each segment keeps only `LIMIT` groups, and each returned group is
/// complete as long as no segment reaches `numGroupsLimit`. With HAVING, or a `LIMIT` at or above the threshold, the
/// servers would not take the sorted combine, and in the other combines the ordered query keeps more groups than the
/// query as written and sorts them, which costs more memory and time, so such a query is left as written.
///
/// A GROUPING SETS, ROLLUP or CUBE query is left as written: its visible group-by expressions do not tell apart every
/// group it returns, and without an ORDER BY the servers keep all its groups, so none of them misses values.
///
/// This rewriter is not in [QueryRewriterFactory#DEFAULT_QUERY_REWRITERS_CLASS_NAMES]. The single-stage broker applies
/// it to the query it sends to the servers, so materialized view definitions and the multi-stage engine are unchanged.
///
/// E.g.
/// SELECT col1, col2, SUM(col3) FROM foo GROUP BY col1, col2 ORDER BY SUM(col3) DESC, col1 DESC LIMIT 10
/// --> SELECT col1, col2, SUM(col3) FROM foo GROUP BY col1, col2 ORDER BY SUM(col3) DESC, col1 DESC, col2 LIMIT 10
/// SELECT col1, SUM(col2) FROM foo GROUP BY col1 LIMIT 10
/// --> SELECT col1, SUM(col2) FROM foo GROUP BY col1 ORDER BY col1 LIMIT 10
///
/// This rewriter is stateless and thread-safe; each invocation mutates its own query.
public class OrderByGroupKeysRewriter implements QueryRewriter {

@Override
public PinotQuery rewrite(PinotQuery pinotQuery) {
if (pinotQuery.getGroupByListSize() == 0 || pinotQuery.getGroupingSets() != null) {
return pinotQuery;
}
if (pinotQuery.getOrderByListSize() > 0) {
completeOrderBy(pinotQuery);
} else if (pinotQuery.getHavingExpression() == null && isLimitBelowSortAggregateLimitThreshold(pinotQuery)) {
List<Expression> groupByList = pinotQuery.getGroupByList();
List<Expression> orderByList = new ArrayList<>(groupByList.size());
for (Expression groupBy : groupByList) {
orderByList.add(ascending(groupBy));
}
pinotQuery.setOrderByList(orderByList);
}
return pinotQuery;
}

/// Appends to the query's ORDER BY each group-by expression it does not order on, in the GROUP BY order.
private static void completeOrderBy(PinotQuery pinotQuery) {
List<Expression> orderByList = new ArrayList<>(pinotQuery.getOrderByList());
List<Expression> ordered = new ArrayList<>(orderByList.size());
for (Expression orderBy : orderByList) {
ordered.add(CalciteSqlParser.removeOrderByFunctions(orderBy));
}
boolean appended = false;
for (Expression groupBy : pinotQuery.getGroupByList()) {
if (!ordered.contains(groupBy)) {
ordered.add(groupBy);
orderByList.add(ascending(groupBy));
appended = true;
}
}
if (appended) {
pinotQuery.setOrderByList(orderByList);
}
}

/// An ascending ORDER BY term on a copy of the group-by expression, as the parser builds a written ORDER BY, so that
/// a later rewrite of one list does not change the other.
private static Expression ascending(Expression groupBy) {
return RequestUtils.getFunctionExpression(CalciteSqlParser.ASC, groupBy.deepCopy());
}

/// Reads `sortAggregateLimitThreshold` as the servers read it. An invalid value leaves the query unchanged, for the
/// servers to reject.
private static boolean isLimitBelowSortAggregateLimitThreshold(PinotQuery pinotQuery) {
Map<String, String> queryOptions = pinotQuery.getQueryOptions();
Integer sortAggregateLimitThreshold;
try {
sortAggregateLimitThreshold =
queryOptions != null ? QueryOptionsUtils.getSortAggregateLimitThreshold(queryOptions) : null;
} catch (IllegalArgumentException e) {
return false;
}
return pinotQuery.getLimit() < (sortAggregateLimitThreshold != null ? sortAggregateLimitThreshold
: Server.DEFAULT_SORT_AGGREGATE_LIMIT_THRESHOLD);
Comment on lines +122 to +123

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.

}
}
Loading