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


##########
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:
   It is partially overrideable already. The rule is public with a protected 
constructor, so it can be subclassed, and Config lets you choose which 
Aggregate and Union classes it matches. But the logic that decides which calls 
are prunable, and what they return on empty input, is in private static 
helpers, so it can't be overridden today.
   
   I see two ways to open it up. I could turn those helpers into protected 
instance methods that a subclass can override, but then their signatures become 
part of the API we have to maintain. Or, if you have a use case in mind, I can 
add a Config option that supplies the prunable check and the empty-input value, 
defaulting to the current behavior. I held off on both because they widen the 
rule's API. Let me know if you'd like either one.



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