ankitsultana commented on code in PR #15658:
URL: https://github.com/apache/pinot/pull/15658#discussion_r2071687778


##########
pinot-query-planner/src/main/java/org/apache/pinot/query/planner/physical/v2/opt/rules/AggregatePushdownRule.java:
##########
@@ -0,0 +1,290 @@
+/**
+ * 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.query.planner.physical.v2.opt.rules;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import org.apache.calcite.plan.RelTraitSet;
+import org.apache.calcite.rel.RelCollation;
+import org.apache.calcite.rel.RelCollations;
+import org.apache.calcite.rel.RelFieldCollation;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.Aggregate;
+import org.apache.calcite.rel.core.AggregateCall;
+import org.apache.calcite.rel.core.Exchange;
+import org.apache.calcite.rel.core.Project;
+import org.apache.calcite.rel.core.Union;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexInputRef;
+import org.apache.calcite.rex.RexLiteral;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.sql.SqlAggFunction;
+import org.apache.calcite.sql.SqlFunctionCategory;
+import org.apache.calcite.sql.SqlKind;
+import org.apache.calcite.sql.type.OperandTypes;
+import org.apache.calcite.sql.type.ReturnTypes;
+import org.apache.calcite.sql.type.SqlOperandTypeChecker;
+import org.apache.calcite.sql.type.SqlReturnTypeInference;
+import org.apache.calcite.util.ImmutableBitSet;
+import org.apache.pinot.calcite.rel.hint.PinotHintOptions;
+import org.apache.pinot.calcite.rel.hint.PinotHintStrategyTable;
+import org.apache.pinot.calcite.rel.rules.PinotRuleUtils;
+import org.apache.pinot.calcite.rel.traits.PinotExecStrategyTrait;
+import org.apache.pinot.common.function.sql.PinotSqlAggFunction;
+import org.apache.pinot.query.context.PhysicalPlannerContext;
+import org.apache.pinot.query.planner.physical.v2.PRelNode;
+import org.apache.pinot.query.planner.physical.v2.PinotDataDistribution;
+import org.apache.pinot.query.planner.physical.v2.mapping.DistMappingGenerator;
+import org.apache.pinot.query.planner.physical.v2.mapping.PinotDistMapping;
+import org.apache.pinot.query.planner.physical.v2.nodes.PhysicalAggregate;
+import org.apache.pinot.query.planner.physical.v2.nodes.PhysicalExchange;
+import org.apache.pinot.query.planner.physical.v2.opt.PRelOptRule;
+import org.apache.pinot.query.planner.physical.v2.opt.PRelOptRuleCall;
+import org.apache.pinot.query.planner.plannode.AggregateNode.AggType;
+import org.apache.pinot.segment.spi.AggregationFunctionType;
+
+
+/**
+ * Does the following:
+ * 1. Converts agg calls to their proper forms.
+ * 2. Adds aggregate under Exchange, if exchange is an input.
+ * 3. Handles leafReturnFinalResult thing.
+ */
+public class AggregatePushdownRule extends PRelOptRule {
+  private final PhysicalPlannerContext _context;
+
+  public AggregatePushdownRule(PhysicalPlannerContext context) {
+    _context = context;
+  }
+
+  @Override
+  public boolean matches(PRelOptRuleCall call) {
+    return call._currentNode instanceof Aggregate;
+  }
+
+  @Override
+  public PRelNode onMatch(PRelOptRuleCall call) {
+    Aggregate aggRel = (Aggregate) call._currentNode;
+    Preconditions.checkState(aggRel instanceof PhysicalAggregate, "Expected 
PhysicalAggregate, got %s", aggRel);
+    boolean hasGroupBy = !aggRel.getGroupSet().isEmpty();
+    RelCollation withinGroupCollation = extractWithinGroupCollation(aggRel);
+    Map<String, String> hintOptions =
+        PinotHintStrategyTable.getHintOptions(aggRel.getHints(), 
PinotHintOptions.AGGREGATE_HINT_OPTIONS);
+    if (hintOptions == null) {
+      hintOptions = Map.of();
+    }
+    boolean isInputExchange = call._currentNode.unwrap().getInput(0) 
instanceof Exchange;
+    if (!isInputExchange || withinGroupCollation != null || (hasGroupBy && 
Boolean.parseBoolean(
+        
hintOptions.get(PinotHintOptions.AggregateOptions.IS_SKIP_LEAF_STAGE_GROUP_BY))))
 {
+      return skipPartialAggregate(call._currentNode);
+    }
+    return addPartialAggregate((PhysicalAggregate) call._currentNode, 
hintOptions, _context.getNodeIdGenerator());
+  }
+
+  private static PRelNode skipPartialAggregate(PRelNode aggPRelNode) {
+    PhysicalAggregate aggRel = (PhysicalAggregate) aggPRelNode.unwrap();
+    List<AggregateCall> newAggCalls = buildAggCalls(aggRel, AggType.DIRECT, 
false);
+    return new PhysicalAggregate(aggRel.getCluster(), aggRel.getTraitSet(), 
aggRel.getHints(), aggRel.getGroupSet(),
+        aggRel.groupSets, newAggCalls, aggRel.getNodeId(), 
aggRel.getPRelInput(0),
+        aggRel.getPinotDataDistributionOrThrow(), aggRel.isLeafStage(), 
AggType.DIRECT,
+        false /* leaf return final agg */, aggRel.getCollations(), 
aggRel.getLimit());
+  }
+
+  private static PRelNode addPartialAggregate(PhysicalAggregate aggPRelNode, 
Map<String, String> hintOptions,
+      Supplier<Integer> idGenerator) {
+    // Old: Aggregate (o0) > Exchange (o1) > Input (o2)
+    // New: Aggregate (n0) > Exchange (n1) > Aggregate (n2) > Input (o2)
+    boolean leafReturnFinalResult =
+        
Boolean.parseBoolean(hintOptions.get(PinotHintOptions.AggregateOptions.IS_LEAF_RETURN_FINAL_RESULT));
+    // init old PRelNodes
+    PhysicalAggregate o0 = aggPRelNode;
+    PhysicalExchange o1 = (PhysicalExchange) o0.getPRelInput(0);
+    PRelNode o2 = o1.getPRelInput(0);
+    // Create n2
+    PhysicalAggregate n2 = new PhysicalAggregate(o0.getCluster(), 
RelTraitSet.createEmpty(), List.of() /* hints */,
+        o0.getGroupSet(), o0.groupSets, buildAggCalls(o0, AggType.LEAF, 
leafReturnFinalResult), idGenerator.get(),
+        o2, null /* data dist */, o2.isLeafStage(), AggType.LEAF, 
leafReturnFinalResult, aggPRelNode.getCollations(),
+        aggPRelNode.getLimit());
+    PinotDistMapping mapFromInputToPartialAgg = 
DistMappingGenerator.compute(o2.unwrap(), n2, null);
+    PinotDataDistribution leafAggDataDistribution = 
o2.getPinotDataDistributionOrThrow().apply(
+        mapFromInputToPartialAgg);
+    n2 = (PhysicalAggregate) n2.with(n2.getPRelInputs(), 
leafAggDataDistribution);
+    // Create n1.
+    List<Integer> newDistKeys = 
mapFromInputToPartialAgg.getMappedKeys(o1.getDistributionKeys()).get(0);
+    RelCollation newCollation = o1.getRelCollation() == null ? null
+        : PinotDistMapping.apply(o1.getRelCollation(), 
mapFromInputToPartialAgg);
+    PhysicalExchange n1 = new PhysicalExchange(o1.getNodeId(), n2,
+        o1.getPinotDataDistributionOrThrow().apply(mapFromInputToPartialAgg), 
newDistKeys, o1.getExchangeStrategy(),
+        newCollation, PinotExecStrategyTrait.getDefaultExecStrategy());
+    return convertAggFromIntermediateInput(aggPRelNode, n1, AggType.FINAL, 
leafReturnFinalResult,
+        PinotDistMapping.apply(RelCollations.of(o0.getCollations()), 
mapFromInputToPartialAgg).getFieldCollations(),
+        aggPRelNode.getLimit(), idGenerator);
+  }
+
+  // TODO: Currently it only handles one WITHIN GROUP collation across all 
AggregateCalls.

Review Comment:
   Good catch. Similar to the other comment, this is taken as is from existing 
code: 
https://github.com/apache/pinot/blob/55eb236edce5a74d17ca93a6c86a45f6a95f9b69/pinot-query-planner/src/main/java/org/apache/pinot/calcite/rel/rules/PinotAggregateExchangeNodeInsertRule.java#L250
   
   Ideally we should throw an error but not sure if we do that right now. cc: 
@Jackie-Jiang 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscr...@pinot.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscr...@pinot.apache.org
For additional commands, e-mail: commits-h...@pinot.apache.org

Reply via email to