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


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownAggStateCast.java:
##########
@@ -0,0 +1,318 @@
+// 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.agg.AnyValue;
+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.LogicalApply;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalGenerate;
+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,
+                LogicalGenerate.class, LogicalApply.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);
+            }
+            if ((plan instanceof LogicalGenerate || plan instanceof 
LogicalApply)
+                    && 
plan.child(0).getOutputSet().contains(expression.child(0))) {
+                // Both plans forward child 0 slots unchanged. Add the target 
state
+                // to that child and keep the original slots for other 
consumers.
+                // Generate still emits the same rows. For example,
+                // EXPLODE_SPLIT('a,b', ',') emits two copies of each state. 
Apply keeps its
+                // subquery and correlation inputs. Do not follow generated 
slots
+                // or Apply's right slots: a scalar subquery with no rows can 
return
+                // SQL NULL. These casts must keep their normal compatibility 
checks.
+                return child(0).retargetSlot(expression);
+            }
+            Expression input = inputs.get(expression.child(0));
+            if (plan instanceof LogicalAggregate) {
+                LogicalAggregate<?> aggregate = (LogicalAggregate<?>) plan;
+                if (input instanceof Slot && 
aggregate.getGroupByExpressions().contains(input)
+                        && aggregate.getSourceRepeat().isEmpty() && 
!target.canUpgradeStoredStateFrom(source)) {
+                    Cast inputCast = new Cast(input, target);
+                    Expression converted = child(0).retargetSlot(inputCast);
+                    if (converted.equals(inputCast)) {
+                        return expression;
+                    }
+                    Preconditions.checkState(converted instanceof Slot);
+                    // DISTINCT becomes an aggregate over its original output 
slots.
+                    // Keep those keys: an older codec can merge distinct 
empty states.
+                    // Each original group has one target value, including SQL 
NULL.
+                    // ANY_VALUE carries it without adding or changing a 
grouping key.
+                    // A legal forward stored cast can stay above the group. 
Do not
+                    // move it: a newer producer can distinguish values that 
the old
+                    // grouping key treats as equal. Grouping sets also stay 
unchanged
+                    // because their NULL extension does not apply to 
ANY_VALUE inputs.
+                    return addedOutputs.computeIfAbsent(new 
AnyValue(converted), Alias::new).toSlot();
+                }
+                if (!(input instanceof CombineCombinator)) {
+                    return expression;
+                }
+                Cast converted = ConvertAggStateCast.convert(new Cast(input, 
target));
+                if (converted.child() == input) {
+                    return expression;
+                }
+                // Keep the original output for other consumers. Equal 
target-codec
+                // casts share a new producer, even in different conditional 
branches.
+                return addedOutputs.computeIfAbsent(converted.child(), 
Alias::new).toSlot();
+            }
+            if (input == null || 
input.containsType(NoneMovableFunction.class)) {
+                // A scan or DISTINCT is a boundary. Non-movable expressions 
must
+                // stay at their original location. Volatile inputs are shared 
below.
+                return expression;
+            }
+            Cast inputCast = new Cast(input, target);
+            Expression converted = plan instanceof LogicalOneRowRelation
+                    ? ConvertAggStateCast.convert(inputCast) : 
child(0).rewriteExpression(inputCast);
+            if (converted.equals(inputCast)) {
+                // A stored slot has no raw-input producer to retarget. Keep 
its cast
+                // at the original level, where normal compatibility 
validation applies.
+                return expression;
+            }
+            return addedOutputs.computeIfAbsent(converted, 
Alias::new).toSlot();
+        }
+
+        private Expression retargetUnionSlot(Cast cast) {
+            LogicalUnion union = (LogicalUnion) plan;
+            // An extra output can change which rows DISTINCT removes.
+            if (union.getQualifier() != Qualifier.ALL) {

Review Comment:
   [P2] Preserve legacy-sink writes through UNION DISTINCT
   
   With query codec 21, a pre-upgrade sink whose `s` is `AGG_STATE<SUM(BIGINT 
NULL)>` uses codec 20. For `src.v BIGINT NULL`, this previously valid insert 
retains the following reduced plan inferred from the source:
   
   ```sql
   INSERT INTO old_sink
   SELECT k, sum_state(v) FROM src
   UNION
   SELECT k, sum_state(v + 1) FROM src;
   ```
   
   ```text
   Project(k, Cast(u@21 AS state@20))
     UnionDistinct(k, u@21)
       Project(k, sum_state(v)@21)
       Project(k, sum_state(v + 1)@21)
   ```
   
   This guard leaves the cast unchanged, and `CheckCast` rejects 21-to-20 
during the initial normalization, before `BuildAggForUnion` can expose a 
grouping boundary. Both raw producers can emit codec 20; this is not an 
incompatible stored-state copy. Preserve the original DISTINCT comparison keys 
while carrying a target-codec result before validation, and add a legacy-sink 
INSERT/UNION regression. The new `testUnionKeepsDistinctBoundary` only asserts 
that this rule does nothing.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownAggStateCast.java:
##########
@@ -0,0 +1,318 @@
+// 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.agg.AnyValue;
+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.LogicalApply;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalGenerate;
+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,
+                LogicalGenerate.class, LogicalApply.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);
+            }
+            if ((plan instanceof LogicalGenerate || plan instanceof 
LogicalApply)
+                    && 
plan.child(0).getOutputSet().contains(expression.child(0))) {
+                // Both plans forward child 0 slots unchanged. Add the target 
state
+                // to that child and keep the original slots for other 
consumers.
+                // Generate still emits the same rows. For example,
+                // EXPLODE_SPLIT('a,b', ',') emits two copies of each state. 
Apply keeps its
+                // subquery and correlation inputs. Do not follow generated 
slots
+                // or Apply's right slots: a scalar subquery with no rows can 
return
+                // SQL NULL. These casts must keep their normal compatibility 
checks.
+                return child(0).retargetSlot(expression);
+            }
+            Expression input = inputs.get(expression.child(0));
+            if (plan instanceof LogicalAggregate) {
+                LogicalAggregate<?> aggregate = (LogicalAggregate<?>) plan;
+                if (input instanceof Slot && 
aggregate.getGroupByExpressions().contains(input)
+                        && aggregate.getSourceRepeat().isEmpty() && 
!target.canUpgradeStoredStateFrom(source)) {
+                    Cast inputCast = new Cast(input, target);
+                    Expression converted = child(0).retargetSlot(inputCast);
+                    if (converted.equals(inputCast)) {
+                        return expression;
+                    }
+                    Preconditions.checkState(converted instanceof Slot);
+                    // DISTINCT becomes an aggregate over its original output 
slots.
+                    // Keep those keys: an older codec can merge distinct 
empty states.
+                    // Each original group has one target value, including SQL 
NULL.
+                    // ANY_VALUE carries it without adding or changing a 
grouping key.
+                    // A legal forward stored cast can stay above the group. 
Do not
+                    // move it: a newer producer can distinguish values that 
the old
+                    // grouping key treats as equal. Grouping sets also stay 
unchanged
+                    // because their NULL extension does not apply to 
ANY_VALUE inputs.
+                    return addedOutputs.computeIfAbsent(new 
AnyValue(converted), Alias::new).toSlot();
+                }
+                if (!(input instanceof CombineCombinator)) {

Review Comment:
   [P2] Retarget UNION aggregate producers to the sink codec
   
   At query version 21, inserting `sum_union(sum_state(v))` into an existing 
codec-20 `AGG_STATE<SUM(BIGINT NULL)>` column leaves this reduced normalized 
plan (`v BIGINT NULL`):
   
   ```text
   Project(k, Cast(s@21 AS state@20))
     Aggregate(group by k; sum_union(t@21) AS s@21)
       Project(k, sum_state(v)@21 AS t)
         Scan(src)
   ```
   
   `UnionCombinator` returns its input state's type, but this branch only 
handles `CombineCombinator`; `ConvertAggStateCast` has no UNION case either. 
Strict `CheckCast` therefore rejects the previously valid INSERT. 
`test_agg_state_union_batch.groovy` already establishes that UNION-of-STATE is 
supported and remains a `sum_union` plan. Follow the raw STATE lineage through 
this aggregate so it can emit the sink codec, retain rejection for genuinely 
incompatible stored inputs, and cover this mixed-version INSERT.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownAggStateCast.java:
##########
@@ -0,0 +1,318 @@
+// 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.agg.AnyValue;
+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.LogicalApply;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalGenerate;
+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,
+                LogicalGenerate.class, LogicalApply.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);
+            }
+            if ((plan instanceof LogicalGenerate || plan instanceof 
LogicalApply)
+                    && 
plan.child(0).getOutputSet().contains(expression.child(0))) {

Review Comment:
   [P2] Retarget STATE returned by a scalar subquery
   
   With query codec 21 and a codec-20 `AGG_STATE<SUM(BIGINT NULL)>` sink, this 
previously valid write still fails (`src.v BIGINT NULL`):
   
   ```sql
   INSERT INTO old_sink
   SELECT d.k,
          coalesce((SELECT sum_state(v) FROM src LIMIT 1),
                   sum_state(nullable(cast(0 AS bigint))))
   FROM dim d;
   ```
   
   Reduced analyzed plan inferred from the source:
   
   ```text
   Project(k, Cast(Coalesce(s@21, STATE(0)@21) AS state@20))
     Apply(scalar)
       Scan(dim)
       Limit(1)
         Project(sum_state(v)@21 AS s)
           Scan(src)
   ```
   
   The conditional rewrite pushes casts into COALESCE, but this condition 
follows only APPLY's left outputs. The right result retains its 21-to-20 cast, 
which `CheckCast` rejects before subquery unnesting. COALESCE supplies a 
non-NULL state when the subquery is empty, so sink nullability does not 
invalidate this example. Retarget the right-side raw producer while preserving 
scalar NULL-for-empty and single-column semantics. The earlier APPLY report 
concerned a left producer below a WHERE filter; this is a different result path.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownAggStateCast.java:
##########
@@ -0,0 +1,318 @@
+// 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.agg.AnyValue;
+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.LogicalApply;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalGenerate;
+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,
+                LogicalGenerate.class, LogicalApply.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);
+            }
+            if ((plan instanceof LogicalGenerate || plan instanceof 
LogicalApply)
+                    && 
plan.child(0).getOutputSet().contains(expression.child(0))) {
+                // Both plans forward child 0 slots unchanged. Add the target 
state
+                // to that child and keep the original slots for other 
consumers.
+                // Generate still emits the same rows. For example,
+                // EXPLODE_SPLIT('a,b', ',') emits two copies of each state. 
Apply keeps its
+                // subquery and correlation inputs. Do not follow generated 
slots
+                // or Apply's right slots: a scalar subquery with no rows can 
return
+                // SQL NULL. These casts must keep their normal compatibility 
checks.
+                return child(0).retargetSlot(expression);
+            }
+            Expression input = inputs.get(expression.child(0));
+            if (plan instanceof LogicalAggregate) {
+                LogicalAggregate<?> aggregate = (LogicalAggregate<?>) plan;
+                if (input instanceof Slot && 
aggregate.getGroupByExpressions().contains(input)
+                        && aggregate.getSourceRepeat().isEmpty() && 
!target.canUpgradeStoredStateFrom(source)) {

Review Comment:
   [P2] Preserve legacy-sink writes with grouping-set state keys
   
   At query codec 21, this previously valid insert into a codec-20 
`AGG_STATE<SUM(BIGINT NULL)>` sink retains a rejected codec cast (`src.v BIGINT 
NULL`):
   
   ```sql
   INSERT INTO old_sink
   SELECT 1, coalesce(s, sum_state(nullable(cast(0 AS bigint))))
   FROM (SELECT sum_state(v) s FROM src) q
   GROUP BY GROUPING SETS ((s), ());
   ```
   
   Reduced normalized plan inferred from the source:
   
   ```text
   Project(1, Cast(Coalesce(s@21, STATE(0)@21) AS state@20))
     Aggregate(group by s, grouping_id; output s; sourceRepeat present)
       Repeat((s), (); null-extend s for ())
         Project(sum_state(v)@21 AS s)
   ```
   
   `NormalizeRepeat` sets `sourceRepeat`, so this guard skips the grouped slot 
and the following COMBINE-only check cannot retarget it. Strict `CheckCast` 
then fails. BIGINT-backed states permit grouping equality, and the scalar 
fallback keeps the sink value nonnullable. Preserve the original grouping keys 
and apply the same grouping-set NULL extension to the target-codec state before 
validation; simply removing this guard would let ANY_VALUE bypass that 
extension. Add legacy-sink GROUPING SETS coverage.



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