github-actions[bot] commented on code in PR #62607:
URL: https://github.com/apache/doris/pull/62607#discussion_r3110594183


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/AbstractMaterializedViewWindowRule.java:
##########
@@ -104,20 +117,141 @@ protected Plan rewriteQueryByView(MatchMode matchMode, 
StructInfo queryStructInf
                 viewToQuerySlotMapping,
                 ImmutableMap.of(), cascadesContext
         );
-        // Can not rewrite, bail out
+        // If generic rewrite fails, try roll up from query expressions.
         if (expressionsRewritten.isEmpty()) {
-            materializationContext.recordFailReason(queryStructInfo,
-                    "Rewrite expressions by view in window scan fail",
-                    () -> String.format("expressionToRewritten is %s,\n 
mvExprToMvScanExprMapping is %s,\n"
-                                    + "targetToSourceMapping = %s", 
queryStructInfo.getExpressions(),
-                            
materializationContext.getShuttledExprToScanExprMapping(),
-                            viewToQuerySlotMapping));
-            return null;
+            expressionsRewritten = 
rollupWindowAggregateFunctions(queryStructInfo.getExpressions(),
+                    queryStructInfo.getTopPlan(), 
mvExprToMvScanExprQueryBased, true, false);
+            if (expressionsRewritten.isEmpty()) {
+                materializationContext.recordFailReason(queryStructInfo,
+                        "Rewrite expressions by view in window scan fail",
+                        () -> String.format("expressionToRewritten is %s,\n 
mvExprToMvScanExprMapping is %s,\n"
+                                        + "targetToSourceMapping = %s", 
queryStructInfo.getExpressions(),
+                                
materializationContext.getShuttledExprToScanExprMapping(),
+                                viewToQuerySlotMapping));
+                return null;
+            }
         }
         return new LogicalProject<>(
                 expressionsRewritten.stream()
                         .map(expression -> expression instanceof 
NamedExpression ? expression : new Alias(expression))
                         .map(NamedExpression.class::cast)
                         .collect(Collectors.toList()), tempRewrittenPlan);
     }
+
+    private static List<Expression> rollupWindowAggregateFunctions(List<? 
extends Expression> expressions,
+            Plan queryTopPlan, Map<Expression, Expression> 
mvExprToMvScanExprQueryBased,
+            boolean needShuttle, boolean strictSlotRewrite) {
+        WindowAggregateRollupContext context = new 
WindowAggregateRollupContext(queryTopPlan,
+                mvExprToMvScanExprQueryBased, strictSlotRewrite);
+        List<? extends Expression> inputExpressions = needShuttle
+                ? ExpressionUtils.shuttleExpressionWithLineage(expressions, 
queryTopPlan)
+                : expressions;
+        List<Expression> rewrittenExpressions = inputExpressions.stream()
+                .map(expression -> 
expression.accept(WindowAggregateRollupRewriter.INSTANCE, context))
+                .collect(Collectors.toList());
+        return context.isValid() ? rewrittenExpressions : ImmutableList.of();
+    }
+
+    private static Function rollupWindowAggregateFunction(AggregateFunction 
queryAggregateFunction,
+            Expression queryAggregateFunctionShuttled, Map<Expression, 
Expression> mvExprToMvScanExprQueryBased) {
+        for (Map.Entry<Expression, Expression> expressionEntry : 
mvExprToMvScanExprQueryBased.entrySet()) {
+            Expression viewExpression = expressionEntry.getKey();
+            // Window mapping keys may be full WindowExpression while rollup 
handlers match aggregate functions.
+            if (viewExpression instanceof WindowExpression) {
+                viewExpression = ((WindowExpression) 
viewExpression).getFunction();
+            }
+            Pair<Expression, Expression> mvExprToMvScanExprQueryBasedPair = 
Pair.of(viewExpression,
+                    expressionEntry.getValue());
+            for (AggFunctionRollUpHandler rollUpHandler : 
AbstractMaterializedViewAggregateRule.ROLL_UP_HANDLERS) {
+                if (!rollUpHandler.canRollup(queryAggregateFunction, 
queryAggregateFunctionShuttled,
+                        mvExprToMvScanExprQueryBasedPair, 
mvExprToMvScanExprQueryBased)) {
+                    continue;
+                }
+                Function rollupFunction = 
rollUpHandler.doRollup(queryAggregateFunction,
+                        queryAggregateFunctionShuttled, 
mvExprToMvScanExprQueryBasedPair,
+                        mvExprToMvScanExprQueryBased);
+                if (rollupFunction != null) {
+                    return rollupFunction;
+                }
+            }
+        }
+        return null;
+    }
+
+    private static class WindowAggregateRollupRewriter
+            extends DefaultExpressionRewriter<WindowAggregateRollupContext> {
+
+        private static final WindowAggregateRollupRewriter INSTANCE = new 
WindowAggregateRollupRewriter();
+
+        @Override
+        public Expression visitWindow(WindowExpression windowExpression, 
WindowAggregateRollupContext context) {
+            if (!context.isValid()) {
+                return windowExpression;
+            }
+            Expression rewrittenWindowExpr = 
context.getMvExprToMvScanExprQueryBased().get(windowExpression);
+            if (rewrittenWindowExpr != null) {
+                return rewrittenWindowExpr;
+            }
+            Expression function = windowExpression.getFunction();
+            if (!(function instanceof AggregateFunction)) {
+                return super.visitWindow(windowExpression, context);
+            }
+            Expression queryFunctionShuttled = 
ExpressionUtils.shuttleExpressionWithLineage(function,
+                    context.getQueryTopPlan());
+            Function rewrittenFunction = 
rollupWindowAggregateFunction((AggregateFunction) function,
+                    queryFunctionShuttled, 
context.getMvExprToMvScanExprQueryBased());
+            if (rewrittenFunction == null) {
+                context.setValid(false);
+                return windowExpression;
+            }
+            return 
super.visitWindow(windowExpression.withFunction(rewrittenFunction), context);
+        }
+

Review Comment:
   Blocking: `rewrittenFunction` is built on top of 
`expressionEntry.getValue()`, which in this new path is the MV's window-result 
slot. Wrapping it back into `windowExpression.withFunction(rewrittenFunction)` 
therefore re-applies the same `OVER (...)` to an already-windowed value. That 
only happens to be harmless for idempotent set-style states such as HLL; for 
non-idempotent combinators like `sum_union` / `sum_merge` it changes the 
result. The rewrite described in the PR body should collapse to the scalar 
`xx_merge(mv_col)` once you've selected the MV window column, not 
`xx_merge(mv_col) OVER (...)`.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/AbstractMaterializedViewWindowRule.java:
##########
@@ -104,20 +117,141 @@ protected Plan rewriteQueryByView(MatchMode matchMode, 
StructInfo queryStructInf
                 viewToQuerySlotMapping,
                 ImmutableMap.of(), cascadesContext
         );
-        // Can not rewrite, bail out
+        // If generic rewrite fails, try roll up from query expressions.
         if (expressionsRewritten.isEmpty()) {
-            materializationContext.recordFailReason(queryStructInfo,
-                    "Rewrite expressions by view in window scan fail",
-                    () -> String.format("expressionToRewritten is %s,\n 
mvExprToMvScanExprMapping is %s,\n"
-                                    + "targetToSourceMapping = %s", 
queryStructInfo.getExpressions(),
-                            
materializationContext.getShuttledExprToScanExprMapping(),
-                            viewToQuerySlotMapping));
-            return null;
+            expressionsRewritten = 
rollupWindowAggregateFunctions(queryStructInfo.getExpressions(),
+                    queryStructInfo.getTopPlan(), 
mvExprToMvScanExprQueryBased, true, false);
+            if (expressionsRewritten.isEmpty()) {
+                materializationContext.recordFailReason(queryStructInfo,
+                        "Rewrite expressions by view in window scan fail",
+                        () -> String.format("expressionToRewritten is %s,\n 
mvExprToMvScanExprMapping is %s,\n"
+                                        + "targetToSourceMapping = %s", 
queryStructInfo.getExpressions(),
+                                
materializationContext.getShuttledExprToScanExprMapping(),
+                                viewToQuerySlotMapping));
+                return null;
+            }
         }
         return new LogicalProject<>(
                 expressionsRewritten.stream()
                         .map(expression -> expression instanceof 
NamedExpression ? expression : new Alias(expression))
                         .map(NamedExpression.class::cast)
                         .collect(Collectors.toList()), tempRewrittenPlan);
     }
+
+    private static List<Expression> rollupWindowAggregateFunctions(List<? 
extends Expression> expressions,
+            Plan queryTopPlan, Map<Expression, Expression> 
mvExprToMvScanExprQueryBased,
+            boolean needShuttle, boolean strictSlotRewrite) {
+        WindowAggregateRollupContext context = new 
WindowAggregateRollupContext(queryTopPlan,
+                mvExprToMvScanExprQueryBased, strictSlotRewrite);
+        List<? extends Expression> inputExpressions = needShuttle
+                ? ExpressionUtils.shuttleExpressionWithLineage(expressions, 
queryTopPlan)
+                : expressions;
+        List<Expression> rewrittenExpressions = inputExpressions.stream()
+                .map(expression -> 
expression.accept(WindowAggregateRollupRewriter.INSTANCE, context))
+                .collect(Collectors.toList());
+        return context.isValid() ? rewrittenExpressions : ImmutableList.of();
+    }
+
+    private static Function rollupWindowAggregateFunction(AggregateFunction 
queryAggregateFunction,
+            Expression queryAggregateFunctionShuttled, Map<Expression, 
Expression> mvExprToMvScanExprQueryBased) {
+        for (Map.Entry<Expression, Expression> expressionEntry : 
mvExprToMvScanExprQueryBased.entrySet()) {
+            Expression viewExpression = expressionEntry.getKey();
+            // Window mapping keys may be full WindowExpression while rollup 
handlers match aggregate functions.
+            if (viewExpression instanceof WindowExpression) {
+                viewExpression = ((WindowExpression) 
viewExpression).getFunction();
+            }
+            Pair<Expression, Expression> mvExprToMvScanExprQueryBasedPair = 
Pair.of(viewExpression,

Review Comment:
   Blocking: this strips the candidate MV output from a full `WindowExpression` 
down to just its aggregate function before choosing 
`expressionEntry.getValue()`. If the MV has two window outputs like 
`xx_union(...) OVER (PARTITION BY a ORDER BY dt)` and `xx_union(...) OVER 
(PARTITION BY b ORDER BY dt)`, both candidates collapse to the same 
`xx_union(...)` here, so the rewriter can bind the query to the wrong MV 
column. The window spec needs to stay part of the match, or you need an 
explicit equality check for partition keys, order keys, and frame before using 
the candidate slot.



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