xiangfu0 commented on code in PR #20365:
URL: https://github.com/apache/pinot/pull/20365#discussion_r4685270722


##########
pinot-query-planner/src/main/java/org/apache/pinot/calcite/rel/rules/PinotAggregateFunctionRewriteRule.java:
##########
@@ -76,12 +98,55 @@ public void onMatch(RelOptRuleCall call) {
       return;
     }
 
-    call.transformTo(aggRel.copy(aggRel.getTraitSet(), input, 
aggRel.getGroupSet(), aggRel.getGroupSets(),
-        rewrittenCalls));
+    RelNode newAgg = aggRel.copy(aggRel.getTraitSet(), input, 
aggRel.getGroupSet(), aggRel.getGroupSets(),
+        rewrittenCalls);
+    if (!anyCoalesce) {
+      call.transformTo(newAgg);
+      return;
+    }
+
+    // Rewriting SUM0 to SUMINT/SUMLONG changes empty-input behavior from 0 to 
NULL under null handling, so wrap
+    // each rewritten SUM0 call in CASE(IS NOT NULL(sum), sum, 0) to preserve 
SUM0's non-null empty-is-zero contract.
+    RexBuilder rexBuilder = aggRel.getCluster().getRexBuilder();
+    int groupCount = aggRel.getGroupCount();
+    List<RexNode> projects = new ArrayList<>(groupCount + numCalls);
+    for (int i = 0; i < groupCount; i++) {
+      projects.add(rexBuilder.makeInputRef(newAgg, i));
+    }
+    for (int i = 0; i < numCalls; i++) {
+      RexNode ref = rexBuilder.makeInputRef(newAgg, groupCount + i);
+      if (coalesceToZero[i]) {
+        RelDataType originalType = originalCalls.get(i).getType();
+        RexNode isNotNull = 
rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL, ref);
+        RexNode zero = rexBuilder.makeZeroLiteral(originalType);
+        projects.add(rexBuilder.makeCall(originalType, 
SqlStdOperatorTable.CASE, List.of(isNotNull, ref, zero)));
+      } else {
+        projects.add(ref);
+      }
+    }
+    call.transformTo(LogicalProject.create(newAgg, List.of(), projects, 
aggRel.getRowType(), Set.of()));
+  }
+
+  /// Returns whether rewriting a `SUM0` call to `SUMINT`/`SUMLONG` can 
produce `NULL` and therefore requires a
+  /// `CASE(IS NOT NULL(sum), sum, 0)` wrapper to preserve `SUM0`'s non-null 
empty-is-zero contract.
+  ///
+  /// When the aggregate has no empty group, no filter, and a non-nullable 
operand, every emitted group has at least
+  /// one non-null value, so `SUMINT`/`SUMLONG` cannot return `NULL` and no 
wrapper `Project` is needed (preserving
+  /// `SortAggregate` group-trim matching).
+  private static boolean needsSum0NullCoalesce(AggregateCall call, RelNode 
input, boolean hasEmptyGroup) {
+    if (call.getAggregation().getKind() != SqlKind.SUM0) {
+      return false;
+    }
+    if (hasEmptyGroup || call.hasFilter()) {
+      return true;
+    }
+    List<Integer> argList = call.getArgList();
+    return !argList.isEmpty() && 
input.getRowType().getFieldList().get(argList.get(0)).getType().isNullable();

Review Comment:
   This shortcut trusts Calcite's nullability, but on a table without 
`enableColumnBasedNullHandling` the operand is typed NOT NULL even though the 
segment can hold nulls and `enableNullHandling=true` skips them. So with 
`autoRewriteAggregationType=true`, `SUMLONG` still returns NULL for an all-null 
group, while the same query without the option now returns 0 through 
`Sum0AggregationFunction`.
   
   A performance option shouldn't change the result, so whichever way the 
default-mode behavior is decided, the two paths should agree. A 
`ResourceBasedQueriesTest` case that runs the query with the option on and off 
against a table without column-based null handling would pin it.



##########
pinot-core/src/main/java/org/apache/pinot/core/query/aggregation/function/Sum0AggregationFunction.java:
##########
@@ -0,0 +1,163 @@
+/**
+ * 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.core.query.aggregation.function;
+
+import java.util.List;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.query.aggregation.AggregationResultHolder;
+import org.apache.pinot.core.query.aggregation.DoubleAggregationResultHolder;
+import 
org.apache.pinot.core.query.aggregation.groupby.DoubleGroupByResultHolder;
+import org.apache.pinot.core.query.aggregation.groupby.GroupByResultHolder;
+import org.apache.pinot.segment.spi.AggregationFunctionType;
+
+
+/// Aggregation function for Calcite's `$SUM0` operator, which sums non-null 
values like [SumAggregationFunction] but
+/// returns `0.0` (rather than `null`) when no non-null rows are aggregated.
+///
+/// Null input values are still skipped when null handling is enabled, so null 
rows never contribute column default
+/// values to the sum. Because the empty-input result and the additive 
identity are both `0.0`, primitive double result
+/// holders are used in both null-handling modes.
+///
+/// This class is stateless and thread-safe.
+public class Sum0AggregationFunction extends SumAggregationFunction {

Review Comment:
   Because this reports `getType() == SUM0`, every MSE `SUM` leaf now shows up 
as `$sum0(...)` in explain, and anything keyed on `AggregationFunctionType.SUM` 
stops matching it, which is why the star-tree mapping had to change. I didn't 
find another place in this repo that depends on it, but it deserves a line in 
the description for anyone with plugins that match on the function type.
   
   Optional: `updateAggregationResultHolder` and the four group-by methods are 
copies of the parent's loops with a primitive holder. Overriding only the three 
`extract*` methods to map null to 0 would give the same results in about 20 
lines, at the cost of boxing in the result holder. Feel free to keep it as is 
if the primitive holder is intentional.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to