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


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/rules/ConvertAggStateCast.java:
##########
@@ -60,6 +66,54 @@ public static Cast convert(Cast cast) {
             while (child instanceof Alias) {
                 child = ((Alias) child).child();
             }
+            if (child instanceof Cast && 
targetType.equals(child.child(0).getDataType())

Review Comment:
   [P2] Preserve compatible stored states through the UNION sink cast
   
   At planning version 21, let `stored19.s` and `sink20.s` have the same 
`AGG_STATE<SUM(BIGINT NULL)>` signature but metadata versions 19 and 20. For 
`INSERT INTO sink20 SELECT k,s FROM stored19 UNION ALL SELECT k,sum_state(v) 
FROM src`, common-type inference selects 21. Pushing the sink cast into UNION 
branches then gives this reduced stored branch:
   
   ```text
   Project(k, Cast(Cast(stored19.s@19 AS state@21) AS state@20))
     Scan(stored19)
   ```
   
   This condition only removes the intermediate cast when the outer target 
equals the deepest source. Since 20 differs from 19, the nested cast survives 
and strict `CheckCast` rejects 21-to-20, although direct 19-to-20 is explicitly 
supported by `canUpgradeStoredStateFrom` and the stored bytes are still version 
19. Allow this compatible forward source-to-target path without allowing actual 
stored version-21 bytes into an old sink, and test source 19 / sink 20 / query 
21.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownAggStateCast.java:
##########
@@ -0,0 +1,284 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.rewrite;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.rules.expression.rules.ConvertAggStateCast;
+import org.apache.doris.nereids.trees.expressions.Alias;
+import org.apache.doris.nereids.trees.expressions.Cast;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.NamedExpression;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+import org.apache.doris.nereids.trees.expressions.StatementScopeIdGenerator;
+import 
org.apache.doris.nereids.trees.expressions.functions.NoneMovableFunction;
+import 
org.apache.doris.nereids.trees.expressions.functions.combinator.CombineCombinator;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.algebra.SetOperation.Qualifier;
+import org.apache.doris.nereids.trees.plans.logical.LogicalAggregate;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalJoin;
+import org.apache.doris.nereids.trees.plans.logical.LogicalLimit;
+import org.apache.doris.nereids.trees.plans.logical.LogicalOneRowRelation;
+import org.apache.doris.nereids.trees.plans.logical.LogicalProject;
+import org.apache.doris.nereids.trees.plans.logical.LogicalSort;
+import org.apache.doris.nereids.trees.plans.logical.LogicalSubQueryAlias;
+import org.apache.doris.nereids.trees.plans.logical.LogicalUnion;
+import org.apache.doris.nereids.types.AggStateType;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/** Move codec-only state casts to STATE or COMBINE before its bytes are 
written. */
+public class PushDownAggStateCast extends OneRewriteRuleFactory {
+    @Override
+    public Rule build() {
+        return logicalProject(subTree(LogicalAggregate.class, 
LogicalFilter.class,
+                LogicalSort.class, LogicalLimit.class, LogicalProject.class, 
LogicalJoin.class,
+                LogicalSubQueryAlias.class, LogicalUnion.class, 
LogicalOneRowRelation.class))
+                .when(project -> project.getProjects().stream().anyMatch(
+                        expr -> expr.anyMatch(e -> e instanceof Cast
+                                && ((Cast) e).getDataType() instanceof 
AggStateType)))
+                .then(PushDownAggStateCast::rewrite)
+                .toRule(RuleType.PUSH_DOWN_AGG_STATE_CAST);
+    }
+
+    private static Plan rewrite(LogicalProject<Plan> project) {
+        StateCastRewriter rewriter = new StateCastRewriter(project.child());
+        List<NamedExpression> projects = project.getProjects().stream()
+                .map(expr -> (NamedExpression) 
rewriter.rewriteExpression(expr))
+                .collect(ImmutableList.toImmutableList());
+        Plan child = rewriter.rewrittenPlan();
+        return child == project.child() ? null : 
project.withProjects(projects).withChildren(child);
+    }
+
+    private static class StateCastRewriter {
+        private final Plan plan;
+        private final Map<Slot, Expression> inputs = new HashMap<>();
+        private final Map<Expression, Alias> addedOutputs = new 
LinkedHashMap<>();
+        private final Map<Integer, StateCastRewriter> children = new 
HashMap<>();
+
+        StateCastRewriter(Plan plan) {
+            this.plan = plan;
+            List<NamedExpression> outputs = ImmutableList.of();
+            if (plan instanceof LogicalAggregate) {
+                outputs = ((LogicalAggregate<?>) plan).getOutputExpressions();
+            } else if (plan instanceof LogicalProject && !((LogicalProject<?>) 
plan).isDistinct()) {
+                outputs = ((LogicalProject<?>) plan).getProjects();
+            } else if (plan instanceof LogicalOneRowRelation) {
+                outputs = ((LogicalOneRowRelation) plan).getProjects();
+            }
+            for (NamedExpression output : outputs) {
+                inputs.put(output.toSlot(), output instanceof Alias ? 
output.child(0) : output);
+            }
+        }
+
+        private StateCastRewriter child(int index) {
+            return children.computeIfAbsent(index, i -> new 
StateCastRewriter(plan.child(i)));
+        }
+
+        private Plan rewrittenPlan() {
+            boolean childrenChanged = false;
+            List<Plan> newChildren = new ArrayList<>(plan.children());
+            for (Map.Entry<Integer, StateCastRewriter> entry : 
children.entrySet()) {
+                Plan newChild = entry.getValue().rewrittenPlan();
+                newChildren.set(entry.getKey(), newChild);
+                childrenChanged |= newChild != plan.child(entry.getKey());
+            }
+            Plan rewritten = childrenChanged ? plan.withChildren(newChildren) 
: plan;
+            if (addedOutputs.isEmpty()) {
+                return rewritten;
+            }
+            if (rewritten instanceof LogicalUnion) {
+                LogicalUnion union = expandVolatileRows((LogicalUnion) 
rewritten);
+                // Add one codec cast per branch before CheckCast runs. Reuse 
the
+                // UNION mapping for regular children and constant rows. The 
current
+                // top-down job then visits the new child projects and their 
producers.
+                // Keep every original output for consumers that still need 
its codec.
+                return 
PushProjectThroughUnion.doPushProject(ImmutableList.<NamedExpression>builder()
+                        
.addAll(union.getOutput()).addAll(addedOutputs.values()).build(), union);
+            }
+            if (rewritten instanceof LogicalAggregate) {
+                LogicalAggregate<?> aggregate = (LogicalAggregate<?>) 
rewritten;
+                return 
aggregate.withAggOutput(ImmutableList.<NamedExpression>builder()
+                        
.addAll(aggregate.getOutputExpressions()).addAll(addedOutputs.values()).build());
+            }
+            // The old and new codec consumers must read the same volatile 
input.
+            // For example, materialize random() once before building both AVG 
states.
+            // The normal volatile-expression job runs after codec validation, 
too late
+            // for a sink cast. Reuse its extraction here before returning the 
plan.
+            AddProjectForVolatileExpression volatileRewriter = new 
AddProjectForVolatileExpression();
+            if (rewritten instanceof LogicalOneRowRelation) {
+                LogicalOneRowRelation row = (LogicalOneRowRelation) rewritten;
+                return 
volatileRewriter.rewriteOneRowRelation(row.withProjects(ImmutableList.<NamedExpression>builder()
+                        
.addAll(row.getProjects()).addAll(addedOutputs.values()).build()));
+            }
+            LogicalProject<?> projection = (LogicalProject<?>) rewritten;
+            List<NamedExpression> outputs = 
ImmutableList.<NamedExpression>builder()
+                    
.addAll(projection.getProjects()).addAll(addedOutputs.values()).build();
+            return volatileRewriter.rewriteExpressions(projection, outputs)
+                    .map(pair -> projection.withProjectsAndChild(pair.first, 
pair.second))
+                    .orElseGet(() -> projection.withProjects(outputs));
+        }
+
+        private LogicalUnion expandVolatileRows(LogicalUnion union) {
+            if (union.getConstantExprsList().stream().flatMap(List::stream)
+                    .noneMatch(Expression::containsVolatileExpression)) {
+                return union;
+            }
+            List<Plan> regularChildren = new ArrayList<>(union.children());
+            List<List<SlotReference>> regularOutputs = new 
ArrayList<>(union.getRegularChildrenOutputs());
+            List<List<NamedExpression>> constantRows = new ArrayList<>();
+            for (List<NamedExpression> row : union.getConstantExprsList()) {
+                if 
(row.stream().anyMatch(Expression::containsVolatileExpression)) {
+                    // A constant-row list cannot reference a separate input 
project.
+                    // Turn this row into a regular child so the same OneRow 
rewrite
+                    // can share its volatile inputs across all codec 
consumers.
+                    LogicalOneRowRelation child = new LogicalOneRowRelation(
+                            StatementScopeIdGenerator.newRelationId(), row);
+                    regularChildren.add(child);
+                    regularOutputs.add(child.getOutput().stream().map(slot -> 
(SlotReference) slot)
+                            .collect(ImmutableList.toImmutableList()));
+                } else {
+                    constantRows.add(row);
+                }
+            }
+            return union.withChildrenAndConstExprsList(regularChildren, 
regularOutputs, constantRows);
+        }
+
+        Expression rewriteExpression(Expression expression) {
+            return expression.rewriteUp(e -> {
+                if (!(e instanceof Cast) || !(e.getDataType() instanceof 
AggStateType)) {
+                    return e;
+                }
+                // Conditional casts now contain casts of their value slots. 
Visit
+                // those new casts too; the original rewriteUp has already 
passed them.
+                return ConvertAggStateCast.convert((Cast) 
e).rewriteUp(this::retargetSlot);
+            });
+        }
+
+        private Expression retargetSlot(Expression expression) {
+            if (!(expression instanceof Cast) || !(expression.getDataType() 
instanceof AggStateType)
+                    || !(expression.child(0) instanceof Slot)
+                    || !(expression.child(0).getDataType() instanceof 
AggStateType)) {
+                return expression;
+            }
+            AggStateType source = (AggStateType) 
expression.child(0).getDataType();
+            AggStateType target = (AggStateType) expression.getDataType();
+            // Only move a codec change. Leave other casts at their original 
location.
+            if (source.equals(target) || 
!source.hasSameAggregateSignature(target)) {
+                return expression;
+            }
+            if (plan instanceof LogicalFilter || plan instanceof LogicalSort 
|| plan instanceof LogicalLimit
+                    || plan instanceof LogicalSubQueryAlias) {
+                // JOIN children can still have subquery aliases at this 
stage. An
+                // alias changes slot names and qualifiers, but keeps their 
ExprIds.
+                return child(0).retargetSlot(expression);
+            }
+            if (plan instanceof LogicalJoin) {
+                return retargetJoinSlot((Cast) expression);
+            }
+            if (plan instanceof LogicalUnion) {
+                return retargetUnionSlot((Cast) expression);
+            }
+            Expression input = inputs.get(expression.child(0));
+            if (plan instanceof LogicalAggregate) {
+                if (!(input instanceof CombineCombinator)) {

Review Comment:
   [P2] Retarget STATE outputs used as DISTINCT grouping keys
   
   For a version-19 `AGG_STATE<SUM(BIGINT NULL)>` sink while planning at 21, 
`INSERT INTO old_sink SELECT DISTINCT k, sum_state(v) FROM src` produces this 
reduced normalized plan inferred from `ProjectWithDistinctToAggregate` and 
`NormalizeAggregate`:
   
   ```text
   Sink(old_sink.s@19)
     Project(k, Cast(s@21 AS state@19))
       Aggregate(group by k,s@21; outputs k,s@21)
         Project(k, sum_state(v)@21 AS s)
           Scan(src)
   ```
   
   STATE is scalar, and AGG_STATE with a BIGINT argument permits grouping 
equality. Here `input` is the grouped slot, so this guard returns without 
reaching the STATE producer. The immediately following strict `CheckCast` 
rejects the remaining 21-to-19 cast, breaking a previously valid INSERT after 
upgrade. Support the target codec across this grouping boundary while 
preserving the original DISTINCT keys, and cover INSERT SELECT DISTINCT into a 
legacy sink.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownAggStateCast.java:
##########
@@ -0,0 +1,284 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.rewrite;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.rules.expression.rules.ConvertAggStateCast;
+import org.apache.doris.nereids.trees.expressions.Alias;
+import org.apache.doris.nereids.trees.expressions.Cast;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.NamedExpression;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+import org.apache.doris.nereids.trees.expressions.StatementScopeIdGenerator;
+import 
org.apache.doris.nereids.trees.expressions.functions.NoneMovableFunction;
+import 
org.apache.doris.nereids.trees.expressions.functions.combinator.CombineCombinator;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.algebra.SetOperation.Qualifier;
+import org.apache.doris.nereids.trees.plans.logical.LogicalAggregate;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalJoin;
+import org.apache.doris.nereids.trees.plans.logical.LogicalLimit;
+import org.apache.doris.nereids.trees.plans.logical.LogicalOneRowRelation;
+import org.apache.doris.nereids.trees.plans.logical.LogicalProject;
+import org.apache.doris.nereids.trees.plans.logical.LogicalSort;
+import org.apache.doris.nereids.trees.plans.logical.LogicalSubQueryAlias;
+import org.apache.doris.nereids.trees.plans.logical.LogicalUnion;
+import org.apache.doris.nereids.types.AggStateType;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/** Move codec-only state casts to STATE or COMBINE before its bytes are 
written. */
+public class PushDownAggStateCast extends OneRewriteRuleFactory {
+    @Override
+    public Rule build() {
+        return logicalProject(subTree(LogicalAggregate.class, 
LogicalFilter.class,
+                LogicalSort.class, LogicalLimit.class, LogicalProject.class, 
LogicalJoin.class,
+                LogicalSubQueryAlias.class, LogicalUnion.class, 
LogicalOneRowRelation.class))

Review Comment:
   [P2] Resolve CTE producers before validating sink codec casts
   
   With `old_sink.s` created as `AGG_STATE<SUM(BIGINT NULL)>` at version 19 and 
planning at 21, `WITH c AS (SELECT k, sum_state(v) s FROM src) INSERT INTO 
old_sink SELECT k,s FROM c` has this reduced analyzed plan inferred from the 
source:
   
   ```text
   CTEAnchor
     Producer(Project(k, sum_state(v)@21 AS s), Scan(src))
     Sink(old_sink.s@19)
       Project(k, Cast(c.s@21 AS state@19))
         CTEConsumer(c)
   ```
   
   This rule cannot follow `LogicalCTEConsumer` to its producer. `Rewriter` 
runs `NORMALIZE_PLAN_JOBS` and strict `CheckCast` before `CTEInline`, so even a 
deterministic, single-use CTE throws `cannot cast agg_state` before it can 
inline. The same insert previously needed no codec cast. Resolve CTE lineage or 
inline eligible CTEs before final cast validation, and add a legacy-sink INSERT 
WITH regression.



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