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


##########
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);

Review Comment:
   convert is what castToTypesOf calls, so we are using the builder. The helper 
exists because convert(union.getRowType(), false) also adds a cast when the 
types differ only in nullability. After a branch is removed, the remaining 
branch is often NOT NULL while the union column is nullable, since the removed 
branch was the NULL one. That produced no op casts such as 
Project(M=[CAST($1):INTEGER]) in the existing plan tests. The helper keeps the 
union's type but takes nullability from the input, so a cast is added only when 
a type really differs, as in the SMALLINT/BIGINT case in 
testAggregateUnionNullBranchTypeNarrowing, and the execution test in 
RelBuilderTest. I added a comment in 7f6e6ce9607d7608cb21d6a723a0770581e35fc6 
explaining this.
   



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