hello-stephen commented on code in PR #68936:
URL: https://github.com/apache/doris/pull/68936#discussion_r4784215634


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/DecomposeRepeatWithPreAggregation.java:
##########
@@ -168,27 +222,61 @@ public Plan visitLogicalAggregate(LogicalAggregate<? 
extends Plan> aggregate, Di
         Set<Expression> needRemovedExprSet = getNeedAddNullExpressions(repeat, 
newGroupingSets, maxGroupIndex);
         Map<AggregateFunction, Slot> aggFuncToSlot = new HashMap<>();
         LogicalAggregate<Plan> topAgg = constructAgg(aggregate, 
originToConsumerMap, newRepeat, groupingFunctionSlots,
-                aggFuncToSlot);
+                aggFuncToSlot, combiners);
         LogicalProject<Plan> project = constructProject(aggregate, 
originToConsumerMap, needRemovedExprSet,
                 groupingFunctionSlots, newRepeat.getGroupingId().get(), 
topAgg, aggFuncToSlot);
-        LogicalPlan directChild = getDirectChild(directConsumer, 
groupingFunctionsValues, maxGroupIndex);
+        LogicalPlan directChild = getDirectChild(directConsumer, 
producer.child().getOutputExpressions(),
+                groupingFunctionsValues, maxGroupIndex);
         return constructUnion(project, directChild, aggregate);
     }
 
+    private Map<AggregateFunction, CombineCombinator> constructCombiners(
+            LogicalAggregate<? extends Plan> aggregate) {
+        LogicalRepeat<?> repeat = (LogicalRepeat<?>) aggregate.child();
+        // Repeat makes grouping keys nullable. State types must use the 
actual input nullability.
+        Map<Slot, Slot> inputSlots = new HashMap<>();
+        for (Slot slot : repeat.child().getOutput()) {
+            inputSlots.put(slot, slot);
+        }
+        Map<AggregateFunction, CombineCombinator> combiners = new HashMap<>();
+        for (AggregateFunction function : aggregate.getAggregateFunctions()) {
+            if (RESULT_ROLLUP_FUNCTIONS.contains(function.getClass())) {
+                continue;
+            }
+            AggregateFunction nested = (AggregateFunction) 
ExpressionUtils.replace(function, inputSlots);
+            combiners.put(function, new CombineCombinator(nested.children(), 
nested));
+        }
+        return combiners;
+    }
+
     /**
      * Get the direct child plan for the union operation.
-     * If the output contains internal grouping id or grouping function slots, 
wrap the consumer with a project
-     * that adds the values of the internal grouping id and grouping scalar 
functions for the maximum grouping set.
+     * Project ordinary result slots unchanged, finalize states introduced by 
this rule, and add
+     * the internal grouping id and grouping scalar function values for the 
maximum grouping set.
+     * canOptimize rejects original aggregate combinators, so every 
CombineCombinator in the producer
+     * was introduced by constructCombiners and must be finalized here.
      *
      * @param directConsumer the CTE consumer for the direct path
+     * @param producerOutputs producer expressions identifying serialized 
states to finalize
      * @param groupingFunctionsValues internal grouping id and grouping scalar 
function values for all grouping sets
      * @param maxGroupIndex index of the maximum grouping set
      * @return the direct child plan, possibly wrapped with a project
      */
     private LogicalPlan getDirectChild(LogicalCTEConsumer directConsumer,
-            List<List<Long>> groupingFunctionsValues, int maxGroupIndex) {
+            List<NamedExpression> producerOutputs, List<List<Long>> 
groupingFunctionsValues, int maxGroupIndex) {
         ImmutableList.Builder<NamedExpression> builder = 
ImmutableList.builder();
-        builder.addAll(directConsumer.getOutput());
+        List<Slot> consumerOutputs = directConsumer.getOutput();
+        for (int i = 0; i < producerOutputs.size(); i++) {
+            NamedExpression output = producerOutputs.get(i);
+            Slot slot = consumerOutputs.get(i);
+            if (output instanceof Alias && output.child(0) instanceof 
CombineCombinator) {

Review Comment:
   [P1] Finalize guarded AVG states before the union
   
   Create a view over `SELECT a,b,c,AVG(v) AS mean FROM t GROUP BY 
ROLLUP(a,b,c)` with `v DECIMAL(18,2)` and `enable_decimal256=true`, then query 
the view with `enable_decimal256=false`. View binding puts a 
`SessionVarGuardExpr` around `AVG(v)`. `constructProducer` replaces the inner 
call and leaves `Alias(guard(avg_combine(v)))`. This check only sees the guard, 
so the maximum grouping set sends the raw `AGG_STATE` slot into the decimal 
column of the union. The other branch uses `avg_merge`, and 
`UnionSinkOperatorX::prepare` rejects the direct branch's type.
   
   Preserve the saved settings through combine, merge, and finalize, or leave 
guarded aggregates on the original Repeat path. Cover the view query with 
differing session settings.



##########
regression-test/suites/nereids_rules_p0/mv/grouping_sets/grouping_sets.groovy:
##########
@@ -298,7 +298,7 @@ suite("materialized_view_grouping_sets") {
             CUBE (o_orderstatus, o_orderpriority);
             """
     order_qt_query5_0_before "${query5_0}"
-    async_mv_rewrite_success(db, mv5_0, query5_0, "mv5_0")
+    async_mv_rewrite_success_without_check_chosen(db, mv5_0, query5_0, "mv5_0")

Review Comment:
   [P3] Keep the grouping-set MV execution checks
   
   The replacement helper accepts `mv5_0 not chose`, and the same change 
applies to eight other cases. The following result checks can therefore pass by 
rerunning the base-table query without exercising the MV plan. These queries 
use `COUNT(DISTINCT ...)`, and the MV alternative rolls it up with 
`BitmapUnionCount`. Both are excluded by the rewrite's eligibility checks. Keep 
the chosen assertion or make the result checks run with the MV selected.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/DecomposeRepeatWithPreAggregation.java:
##########
@@ -70,34 +107,43 @@
 import java.util.TreeMap;
 
 /**
- * This rule will rewrite grouping sets. eg:
- *      select a, b, c, d, e sum(f) from t group by rollup(a, b, c, d, e);
- * rewrite to:
- *    with cte1 as (select a, b, c, d, e, sum(f) x from t group by rollup(a, 
b, c, d, e))
- *      select * fom cte1
- *      union all
- *      select a, b, c, d, null, sum(x) x from t group by rollup(a, b, c, d)
+ * Pre-aggregate the grouping set that contains all other grouping sets and 
share it through a CTE.
+ * SUM, SUM0, MIN, MAX, ANY_VALUE and COUNT use their final results for 
further aggregation;
+ * COUNT results are rolled up by SUM;
+ * other eligible built-in aggregates use combine/merge/finalize to preserve 
their intermediate states.
+ * Both kinds of aggregate can share the same producer, Repeat and union.
+ *
+ * For example, SUM(d), COUNT(d) and AVG(d) over ROLLUP(a,b,c) are rewritten 
as:
  *
- * LogicalAggregate(gby: a,b,c,d,e,grouping_id 
output:a,b,c,d,e,grouping_id,sum(f))
- *   +--LogicalRepeat(grouping sets: 
(a,b,c,d,e),(a,b,c,d),(a,b,c),(a,b),(a),())
- * ->
  * LogicalCTEAnchor
  *   +--LogicalCTEProducer(cte)
- *     +--LogicalAggregate(gby: a,b,c,d,e; aggFunc: sum(f) as x)
+ *     +--LogicalAggregate(gby: a,b,c; aggFunc: sum(d) as s, count(d) as n, 
avg_combine(d) as x)
  *   +--LogicalUnionAll
- *     +--LogicalProject(a,b,c,d, null as e, sum(x))
- *       +--LogicalAggregate(gby:a,b,c,d,grouping_id; aggFunc: sum(x))
- *         +--LogicalRepeat(grouping sets: (a,b,c,d),(a,b,c),(a,b),(a),())
+ *     +--LogicalProject(a,b, null as c, sum_result, count_result, avg_result, 
grouping_id)
+ *       +--LogicalAggregate(gby: a,b,grouping_id;
+ *             aggFunc: sum(s) as sum_result, sum(n) as count_result, 
avg_merge(x) as avg_result)
+ *         +--LogicalRepeat(grouping sets: (a,b),(a),())
  *           +--LogicalCTEConsumer(aggregateConsumer)
- *     +--LogicalCTEConsumer(directConsumer)
+ *     +--LogicalProject(a,b,c, s, n, avg_finalize(x), grouping_id constant)
+ *       +--LogicalCTEConsumer(directConsumer)
+ *
+ * The direct branch needs no aggregation: it passes through ordinary results 
and finalizes states
+ * introduced by this rule. Existing aggregate combinators (such as 
avg_combine) are not eligible;
+ * if any original aggregate function is unsupported or DISTINCT, the entire 
aggregate is left unchanged.
  */
 public class DecomposeRepeatWithPreAggregation extends 
DefaultPlanRewriter<DistinctSelectorContext>
         implements CustomRewriter {
     public static final DecomposeRepeatWithPreAggregation INSTANCE = new 
DecomposeRepeatWithPreAggregation();
-    private static final Set<Class<? extends AggregateFunction>> 
SUPPORT_AGG_FUNCTIONS =
+    private static final Set<Class<? extends AggregateFunction>> 
RESULT_ROLLUP_FUNCTIONS =
             ImmutableSet.of(Sum.class, Sum0.class, Min.class, Max.class, 
AnyValue.class, Count.class);
     private static final int DECOMPOSE_REPEAT_THRESHOLD = 3;
     private static final int BALANCE_MULTIPLIER = 128;
+    private static final Set<Class<? extends AggregateFunction>> 
AGG_STATE_REPEAT_REWRITE_WHITELIST = ImmutableSet.of(
+            Avg.class, Variance.class, Corr.class, CorrWelford.class, 
Covar.class, CovarSamp.class, AvgWeighted.class,
+            BoolAnd.class, BoolOr.class, BoolXor.class, GroupBitAnd.class, 
GroupBitOr.class, GroupBitXor.class,
+            RegrAvgx.class, RegrAvgy.class, RegrCount.class, 
RegrIntercept.class, RegrR2.class, RegrSlope.class,
+            RegrSxx.class, RegrSyy.class, RegrSxy.class, Sem.class, 
Skew.class, Stddev.class, StddevSamp.class,

Review Comment:
   [P2] Preserve zero variance when merging the first state
   
   With `agg_phase=1`, use a table with `v DOUBLE NOT NULL` and rows `(a,b,c,v) 
= (1,1,1,1e155), (1,1,2,1e155)`. In `SELECT a,b,c,SEM(v),STDDEV_POP(v) FROM t 
GROUP BY ROLLUP(a,b,c)`, the ordinary aggregate returns 0 for both functions at 
`(1,1,NULL)`. The rewrite pre-aggregates two singleton states and feeds them to 
the subtotal's state merges. `AggregateFunctionSemData::merge` and the shared 
variance/stddev merge square the first delta of magnitude `1e155` before 
multiplying by the destination count of zero. The resulting `Inf * 0` produces 
NaN and contaminates the subtotal. Copy the first nonempty state into an empty 
accumulator before computing the delta, or exclude the affected functions until 
their merges handle that case.



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