sbroeder commented on code in PR #5382:
URL: https://github.com/apache/calcite/pull/5382#discussion_r4624765221


##########
core/src/main/java/org/apache/calcite/rel/rules/AggregateUnionNullBranchRule.java:
##########
@@ -77,61 +108,144 @@ protected AggregateUnionNullBranchRule(Config config) {
     final Aggregate aggregate = call.rel(0);
     final Union union = call.rel(1);
     final RelMetadataQuery mq = call.getMetadataQuery();
-    final RelBuilder relBuilder = call.builder();
 
+    // A branch is irrelevant if every aggregate call ignores NULL inputs, for
+    // example SUM, MIN, MAX, AVG or COUNT(x), and reads only columns that the
+    // branch produces as constant NULL.
     final List<RelNode> inputs = union.getInputs();
-    final List<Boolean> irrelevant = new ArrayList<>();
+    final boolean[] irrelevant = new boolean[inputs.size()];
     boolean anyIrrelevant = false;
-    for (RelNode input : inputs) {
-      final ImmutableBitSet nullColumns = nullColumns(mq, input);
-      final boolean ignored = aggregate.getAggCallList().stream()
+    for (int i = 0; i < irrelevant.length; i++) {
+      final ImmutableBitSet nullColumns = nullColumns(mq, inputs.get(i));
+      irrelevant[i] = aggregate.getAggCallList().stream()
           .allMatch(c -> ignoresRowsWithNullColumns(c, nullColumns));
-      irrelevant.add(ignored);
-      anyIrrelevant |= ignored;
+      anyIrrelevant |= irrelevant[i];
     }
     if (!anyIrrelevant) {
       return;
     }
 
-    final List<RelNode> newInputs = new ArrayList<>();
     if (aggregate.getGroupSet().isEmpty()) {
-      for (int i = 0; i < inputs.size(); i++) {
-        if (!irrelevant.get(i)) {
-          newInputs.add(inputs.get(i));
-        }
-      }
-      if (newInputs.isEmpty()) {
-        newInputs.add(inputs.get(0));
-      }
-      if (newInputs.size() == inputs.size()) {
-        return;
-      }
+      // Without GROUP BY, an irrelevant branch cannot change the result.
+      removeIrrelevantBranches(call, aggregate, union, irrelevant);
     } else {
-      boolean changed = false;
-      for (int i = 0; i < inputs.size(); i++) {
-        final RelNode input = inputs.get(i);
-        final RelNode simplified =
-            irrelevant.get(i) ? removeRedundantGroupBy(input, relBuilder) : 
input;
-        changed |= simplified != input;
-        newInputs.add(simplified);
-      }
-      if (!changed) {
-        return;
-      }
+      // With GROUP BY, an irrelevant branch still contributes group keys.
+      simplifyIrrelevantBranches(call, aggregate, union, irrelevant);
     }
+  }
 
-    relBuilder.pushAll(newInputs);
-    relBuilder.union(true, newInputs.size());
+  /** Handles an aggregate without GROUP BY.
+   * Branches that cannot contribute are removed. */
+  private static void removeIrrelevantBranches(RelOptRuleCall call,
+      Aggregate aggregate, Union union, boolean[] irrelevant) {
+    final List<RelNode> inputs = union.getInputs();
+    final List<RelNode> newInputs = new ArrayList<>();
+    for (int i = 0; i < inputs.size(); i++) {
+      // Drop the branches that cannot contribute.
+      if (!irrelevant[i]) {
+        newInputs.add(inputs.get(i));
+      }
+    }
     if (newInputs.size() == inputs.size()) {
-      // Same number of branches: only the branches themselves changed.
-      relBuilder.convert(union.getRowType(), false);
-      call.transformTo(
-          aggregate.copy(aggregate.getTraitSet(), 
ImmutableList.of(relBuilder.build())));
+      return;
+    }
+    final RelBuilder relBuilder = call.builder();
+    if (newInputs.isEmpty()) {
+      // Every branch is irrelevant, so the aggregate sees no contributing
+      // rows. A global aggregate returns exactly one row, whose value for
+      // each call is a constant: 0 for COUNT and SUM0, NULL for the others.
+      relBuilder.values(ImmutableList.of(constantRow(aggregate, 
relBuilder.getRexBuilder())),
+          aggregate.getRowType());
+      call.transformTo(relBuilder.build());
       call.getPlanner().prune(aggregate);
       return;
     }
-    // Branches were removed. Re-derive the aggregate over the remaining input
-    // so that the types are inferred and only cast if they differ.
+    relBuilder.pushAll(newInputs);
+    relBuilder.union(true, newInputs.size());
+    // The removed branches may have determined the type of the union,
+    // for example, a BIGINT column that the remaining branch has as SMALLINT.
+    // Cast back, so that the aggregate runs at its original input type.
+    castToTypesOf(union, relBuilder);
+    relBuilder.hints(aggregate.getHints());
+    relBuilder.aggregate(relBuilder.groupKey(aggregate.getGroupSet()),
+        aggregateCalls(aggregate, relBuilder));
+    relBuilder.convert(aggregate.getRowType(), false);
+    call.transformTo(relBuilder.build());
+    call.getPlanner().prune(aggregate);
+  }
+
+  /** Handles an aggregate with GROUP BY: irrelevant branches still contribute
+   * group keys, so they are kept, but a redundant GROUP BY inside them is
+   * removed. */
+  private static void simplifyIrrelevantBranches(RelOptRuleCall call,
+      Aggregate aggregate, Union union, boolean[] irrelevant) {
+    final List<RelNode> inputs = union.getInputs();
+    final RelBuilder relBuilder = call.builder();
+    final List<RelNode> newInputs = new ArrayList<>();
+    boolean changed = false;
+    for (int i = 0; i < inputs.size(); i++) {
+      final RelNode input = inputs.get(i);
+      // The branch is kept, but a pure GROUP BY inside it is redundant: its
+      // duplicate rows cannot change the enclosing aggregate, so replace it by
+      // a projection of the grouping columns.
+      final RelNode simplified =
+          irrelevant[i] ? removeRedundantGroupBy(input, relBuilder) : input;
+      changed |= simplified != input;
+      newInputs.add(simplified);
+    }
+    if (!changed) {
+      return;
+    }
+    // Same number of branches: only the branches themselves changed.
+    relBuilder.pushAll(newInputs);
+    relBuilder.union(true, newInputs.size());
+    relBuilder.convert(union.getRowType(), false);
+    call.transformTo(
+        aggregate.copy(aggregate.getTraitSet(), 
ImmutableList.of(relBuilder.build())));
+    call.getPlanner().prune(aggregate);
+  }
+
+  /** Returns the single row produced by {@code aggregate} when it has no
+   * GROUP BY and no row contributes: 0 for COUNT and SUM0, NULL otherwise. */
+  private static List<RexLiteral> constantRow(Aggregate aggregate, RexBuilder 
rexBuilder) {
+    final List<RexLiteral> literals = new ArrayList<>();
+    final List<RelDataTypeField> fields = 
aggregate.getRowType().getFieldList();
+    for (int i = 0; i < aggregate.getAggCallList().size(); i++) {
+      final SqlKind kind = 
aggregate.getAggCallList().get(i).getAggregation().getKind();
+      final RelDataType type = fields.get(aggregate.getGroupCount() + 
i).getType();
+      literals.add(
+          kind == SqlKind.COUNT || kind == SqlKind.SUM0

Review Comment:
   Good question. The rule only prunes for SUM, SUM0, MIN, MAX, AVG and 
COUNT(col). Anything else, including ARRAY_AGG and user-defined aggregates, 
which normally have kind OTHER_FUNCTION, is never treated as ignorable and the 
plan is left unchanged. I added testAggregateUnionNullBranchArrayAgg for this. 
In 7f6e6ce9607d7608cb21d6a723a0770581e35fc6 I also made the value on no rows 
logic explicit where two helpers now drive both the eligibility check and the 
constant row, and constantRow fails fast on a kind it doesn't know instead of 
defaulting to NULL. AggregateValuesRule makes the same kind based assumption. 
   
   However, a user-defined aggregate that is declared with a standard kind, 
like SUM, with different empty input semantics would still be mishandled. I 
don't know how likely that is, but if you'd like, I can add a Config hook so a 
user can override which calls are prunable. I held off because it widens the 
rule's API.



-- 
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]

Reply via email to