Skip to content

Add optimizer to convert min_by/max_by to row number function #25190

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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 @@ -331,6 +331,7 @@ public final class SystemSessionProperties
public static final String EXPRESSION_OPTIMIZER_NAME = "expression_optimizer_name";
public static final String ADD_EXCHANGE_BELOW_PARTIAL_AGGREGATION_OVER_GROUP_ID = "add_exchange_below_partial_aggregation_over_group_id";
public static final String QUERY_CLIENT_TIMEOUT = "query_client_timeout";
public static final String REWRITE_MIN_MAX_BY_TO_TOP_N = "rewrite_min_max_by_to_top_n";

// TODO: Native execution related session properties that are temporarily put here. They will be relocated in the future.
public static final String NATIVE_AGGREGATION_SPILL_ALL = "native_aggregation_spill_all";
Expand Down Expand Up @@ -1875,6 +1876,11 @@ public SystemSessionProperties(
"Enable single node execution",
featuresConfig.isSingleNodeExecutionEnabled(),
false),
booleanProperty(
REWRITE_MIN_MAX_BY_TO_TOP_N,
"rewrite min_by/max_by to top n",
featuresConfig.isRewriteMinMaxByToTopNEnabled(),
false),
booleanProperty(NATIVE_EXECUTION_SCALE_WRITER_THREADS_ENABLED,
"Enable automatic scaling of writer threads",
featuresConfig.isNativeExecutionScaleWritersThreadsEnabled(),
Expand Down Expand Up @@ -2352,6 +2358,11 @@ public static boolean isSingleNodeExecutionEnabled(Session session)
return session.getSystemProperty(SINGLE_NODE_EXECUTION_ENABLED, Boolean.class);
}

public static boolean isRewriteMinMaxByToTopNEnabled(Session session)
{
return session.getSystemProperty(REWRITE_MIN_MAX_BY_TO_TOP_N, Boolean.class);
}

public static boolean isPushAggregationThroughJoin(Session session)
{
return session.getSystemProperty(PUSH_PARTIAL_AGGREGATION_THROUGH_JOIN, Boolean.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,7 @@ public class FeaturesConfig
private int eagerPlanValidationThreadPoolSize = 20;
private boolean innerJoinPushdownEnabled;
private boolean inEqualityJoinPushdownEnabled;
private boolean rewriteMinMaxByToTopNEnabled;

private boolean prestoSparkExecutionEnvironment;
private boolean singleNodeExecutionEnabled;
Expand Down Expand Up @@ -2909,6 +2910,19 @@ public FeaturesConfig setInEqualityJoinPushdownEnabled(boolean inEqualityJoinPus
return this;
}

public boolean isRewriteMinMaxByToTopNEnabled()
{
return rewriteMinMaxByToTopNEnabled;
}

@Config("optimizer.rewrite-minBy-maxBy-to-topN-enabled")
@ConfigDescription("Rewrite min_by and max_by to topN")
public FeaturesConfig setRewriteMinMaxByToTopNEnabled(boolean rewriteMinMaxByToTopNEnabled)
{
this.rewriteMinMaxByToTopNEnabled = rewriteMinMaxByToTopNEnabled;
return this;
}

public boolean isInEqualityJoinPushdownEnabled()
{
return inEqualityJoinPushdownEnabled;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
import com.facebook.presto.sql.planner.iterative.rule.MergeLimitWithSort;
import com.facebook.presto.sql.planner.iterative.rule.MergeLimitWithTopN;
import com.facebook.presto.sql.planner.iterative.rule.MergeLimits;
import com.facebook.presto.sql.planner.iterative.rule.MinMaxByToWindowFunction;
import com.facebook.presto.sql.planner.iterative.rule.MultipleDistinctAggregationToMarkDistinct;
import com.facebook.presto.sql.planner.iterative.rule.PickTableLayout;
import com.facebook.presto.sql.planner.iterative.rule.PlanRemoteProjections;
Expand Down Expand Up @@ -653,6 +654,12 @@ public PlanOptimizers(
statsCalculator,
estimatedExchangesCostCalculator,
ImmutableSet.of(new SimplifyCountOverConstant(metadata.getFunctionAndTypeManager()))),
new IterativeOptimizer(
metadata,
ruleStats,
statsCalculator,
estimatedExchangesCostCalculator,
ImmutableSet.of(new MinMaxByToWindowFunction(metadata.getFunctionAndTypeManager()))),
Copy link
Contributor

Choose a reason for hiding this comment

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

Maybe we want to add this optimization before the window pushdowns? Let's make sure the topn=1 pushdown happens for this rewritten plan as well

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Maybe we want to add this optimization before the window pushdowns?

Done.

Let's make sure the topn=1 pushdown happens for this rewritten plan as well

Do you mean that limit=1 is pushed into the topN node? I already set maxRowCountPerPartition to be 1 when constructing the topN node, i.e. limit 1 is applied in the optimizer.

Copy link
Contributor

Choose a reason for hiding this comment

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

No but the pushdown of topn=1 (PartialTopN) looks like it already happened?

new LimitPushDown(), // Run LimitPushDown before WindowFilterPushDown
new WindowFilterPushDown(metadata), // This must run after PredicatePushDown and LimitPushDown so that it squashes any successive filter nodes and limits
prefilterForLimitingAggregation,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
/*
* Licensed 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 com.facebook.presto.sql.planner.iterative.rule;

import com.facebook.presto.Session;
import com.facebook.presto.common.block.SortOrder;
import com.facebook.presto.common.type.MapType;
import com.facebook.presto.matching.Captures;
import com.facebook.presto.matching.Pattern;
import com.facebook.presto.metadata.FunctionAndTypeManager;
import com.facebook.presto.spi.plan.AggregationNode;
import com.facebook.presto.spi.plan.Assignments;
import com.facebook.presto.spi.plan.DataOrganizationSpecification;
import com.facebook.presto.spi.plan.FilterNode;
import com.facebook.presto.spi.plan.Ordering;
import com.facebook.presto.spi.plan.OrderingScheme;
import com.facebook.presto.spi.plan.ProjectNode;
import com.facebook.presto.spi.relation.ConstantExpression;
import com.facebook.presto.spi.relation.RowExpression;
import com.facebook.presto.spi.relation.VariableReferenceExpression;
import com.facebook.presto.sql.planner.iterative.Rule;
import com.facebook.presto.sql.planner.plan.TopNRowNumberNode;
import com.facebook.presto.sql.relational.FunctionResolution;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.facebook.presto.SystemSessionProperties.isRewriteMinMaxByToTopNEnabled;
import static com.facebook.presto.common.function.OperatorType.EQUAL;
import static com.facebook.presto.common.type.BigintType.BIGINT;
import static com.facebook.presto.sql.planner.plan.AssignmentUtils.identityAssignments;
import static com.facebook.presto.sql.planner.plan.Patterns.aggregation;
import static com.facebook.presto.sql.relational.Expressions.comparisonExpression;
import static com.google.common.collect.ImmutableMap.toImmutableMap;

public class MinMaxByToWindowFunction
implements Rule<AggregationNode>
{
private static final Pattern<AggregationNode> PATTERN = aggregation().matching(x -> !x.getHashVariable().isPresent() && !x.getGroupingKeys().isEmpty() && x.getGroupingSetCount() == 1 && x.getStep().equals(AggregationNode.Step.SINGLE));
private final FunctionResolution functionResolution;

public MinMaxByToWindowFunction(FunctionAndTypeManager functionAndTypeManager)
{
this.functionResolution = new FunctionResolution(functionAndTypeManager.getFunctionAndTypeResolver());
}

@Override
public boolean isEnabled(Session session)
{
return isRewriteMinMaxByToTopNEnabled(session);
}

@Override
public Pattern<AggregationNode> getPattern()
{
return PATTERN;
}

@Override
public Result apply(AggregationNode node, Captures captures, Context context)
{
Map<VariableReferenceExpression, AggregationNode.Aggregation> maxByAggregations = node.getAggregations().entrySet().stream()
.filter(x -> functionResolution.isMaxByFunction(x.getValue().getFunctionHandle()) && x.getValue().getArguments().get(0).getType() instanceof MapType)
.collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
Map<VariableReferenceExpression, AggregationNode.Aggregation> minByAggregations = node.getAggregations().entrySet().stream()
.filter(x -> functionResolution.isMinByFunction(x.getValue().getFunctionHandle()) && x.getValue().getArguments().get(0).getType() instanceof MapType)
.collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
boolean isMaxByAggregation;
Map<VariableReferenceExpression, AggregationNode.Aggregation> candidateAggregation;
if (maxByAggregations.isEmpty() && !minByAggregations.isEmpty()) {
isMaxByAggregation = false;
candidateAggregation = minByAggregations;
}
else if (!maxByAggregations.isEmpty() && minByAggregations.isEmpty()) {
isMaxByAggregation = true;
candidateAggregation = maxByAggregations;
}
else {
return Result.empty();
}
boolean allMaxOrMinByWithSameField = candidateAggregation.values().stream().map(x -> x.getArguments().get(1)).distinct().count() == 1;
if (!allMaxOrMinByWithSameField) {
return Result.empty();
}
VariableReferenceExpression orderByVariable = (VariableReferenceExpression) candidateAggregation.values().stream().findFirst().get().getArguments().get(1);
Map<VariableReferenceExpression, AggregationNode.Aggregation> remainingAggregations = node.getAggregations().entrySet().stream().filter(x -> !candidateAggregation.containsKey(x.getKey()))
.collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
boolean remainingEmptyOrMinOrMaxOnOrderBy = remainingAggregations.isEmpty() || (remainingAggregations.size() == 1
&& remainingAggregations.values().stream().allMatch(x -> (isMaxByAggregation ? functionResolution.isMaxFunction(x.getFunctionHandle()) : functionResolution.isMinFunction(x.getFunctionHandle())) && x.getArguments().size() == 1 && x.getArguments().get(0).equals(orderByVariable)));
if (!remainingEmptyOrMinOrMaxOnOrderBy) {
return Result.empty();
}

List<VariableReferenceExpression> partitionKeys = node.getGroupingKeys();
OrderingScheme orderingScheme = new OrderingScheme(ImmutableList.of(new Ordering(orderByVariable, isMaxByAggregation ? SortOrder.DESC_NULLS_LAST : SortOrder.ASC_NULLS_LAST)));
DataOrganizationSpecification dataOrganizationSpecification = new DataOrganizationSpecification(partitionKeys, Optional.of(orderingScheme));
VariableReferenceExpression rowNumberVariable = context.getVariableAllocator().newVariable("row_number", BIGINT);
TopNRowNumberNode topNRowNumberNode =
new TopNRowNumberNode(node.getSourceLocation(),
context.getIdAllocator().getNextId(),
node.getStatsEquivalentPlanNode(),
node.getSource(),
dataOrganizationSpecification,
rowNumberVariable,
1,
false,
Optional.empty());
RowExpression equal = comparisonExpression(functionResolution, EQUAL, rowNumberVariable, new ConstantExpression(1L, BIGINT));
FilterNode filterNode = new FilterNode(node.getSourceLocation(), context.getIdAllocator().getNextId(), node.getStatsEquivalentPlanNode(), topNRowNumberNode, equal);
Map<VariableReferenceExpression, RowExpression> assignments = ImmutableMap.<VariableReferenceExpression, RowExpression>builder()
.putAll(node.getAggregations().entrySet().stream().collect(toImmutableMap(Map.Entry::getKey, x -> x.getValue().getArguments().get(0)))).build();

ProjectNode projectNode = new ProjectNode(node.getSourceLocation(), context.getIdAllocator().getNextId(), node.getStatsEquivalentPlanNode(), filterNode,
Assignments.builder().putAll(assignments).putAll(identityAssignments(node.getGroupingKeys())).build(), ProjectNode.Locality.LOCAL);
return Result.ofPlanNode(projectNode);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,16 @@ public FunctionHandle countFunction(Type valueType)
return functionAndTypeResolver.lookupFunction("count", fromTypes(valueType));
}

public boolean isMaxByFunction(FunctionHandle functionHandle)
{
return functionAndTypeResolver.getFunctionMetadata(functionHandle).getName().equals(functionAndTypeResolver.qualifyObjectName(QualifiedName.of("max_by")));
}

public boolean isMinByFunction(FunctionHandle functionHandle)
{
return functionAndTypeResolver.getFunctionMetadata(functionHandle).getName().equals(functionAndTypeResolver.qualifyObjectName(QualifiedName.of("min_by")));
}

@Override
public boolean isMaxFunction(FunctionHandle functionHandle)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@ public void testDefaults()
.setAddExchangeBelowPartialAggregationOverGroupId(false)
.setInnerJoinPushdownEnabled(false)
.setInEqualityJoinPushdownEnabled(false)
.setRewriteMinMaxByToTopNEnabled(false)
.setPrestoSparkExecutionEnvironment(false));
}

Expand Down Expand Up @@ -458,6 +459,7 @@ public void testExplicitPropertyMappings()
.put("eager-plan-validation-thread-pool-size", "2")
.put("optimizer.inner-join-pushdown-enabled", "true")
.put("optimizer.inequality-join-pushdown-enabled", "true")
.put("optimizer.rewrite-minBy-maxBy-to-topN-enabled", "true")
.put("presto-spark-execution-environment", "true")
.put("single-node-execution-enabled", "true")
.put("native-execution-scale-writer-threads-enabled", "true")
Expand Down Expand Up @@ -669,6 +671,7 @@ public void testExplicitPropertyMappings()
.setExcludeInvalidWorkerSessionProperties(true)
.setAddExchangeBelowPartialAggregationOverGroupId(true)
.setInEqualityJoinPushdownEnabled(true)
.setRewriteMinMaxByToTopNEnabled(true)
.setInnerJoinPushdownEnabled(true)
.setPrestoSparkExecutionEnvironment(true);
assertFullMapping(properties, expected);
Expand Down
Loading
Loading