This is an automated email from the ASF dual-hosted git repository.

yujun777 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/master by this push:
     new 7b817faf48f [refactor](fe) Remove the aggregate state coercion flag 
(#70499)
7b817faf48f is described below

commit 7b817faf48f377fb90ce1faaad7974afd7c7938f
Author: feiniaofeiafei <[email protected]>
AuthorDate: Wed Nov 18 17:46:44 2026 +0800

    [refactor](fe) Remove the aggregate state coercion flag (#70499)
    
    Nereids initially allows a cast between aggregate states with the same
    function name and argument count. During rewriting, a state producer
    such as `avg_state(i)` can cast its raw input and rebuild its state. A
    combine aggregate or a slot holding its output keeps its original
    signature.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: #66942 (introduced the combine combinator and its coercion
    flag)
    PR Type: Refactor
    
    Problem Summary: `AggStateType` carried a producer-specific flag so that
    combine casts could fail during binding. Remove the flag and validate
    the actual state type after the opportunity to rewrite its producer.
    Fast VALUES planning and load expression translation now perform the
    final check as well.
    
    ### Details
    
    - **Moves vs. logic changes:** Remove the combine-specific constructor
    parameter, binding check and error. Reuse the bound-cast validator in
    load translation. Apply the final check to single rows and to constant
    rows held inside a VALUES union.
    - **Behavior change:** Incompatible combine casts now reach the final
    cast check and report the source and target types in the ordinary
    `cannot cast` error. Matching combine states pass. A compatible state
    producer can still widen its input.
    - **Compatibility:** FE planning change. No changes to catalog, wire or
    storage formats.
    - **Performance impact:** The fast VALUES expression rewrite also visits
    union constant rows. Performance was not benchmarked.
    - **Rollback:** Revert this commit.
---
 .../nereids/load/NereidsLoadPlanInfoCollector.java |  3 +-
 .../rules/expression/ExpressionRewrite.java        |  3 +-
 .../nereids/rules/expression/check/CheckCast.java  | 41 +++++---------
 .../expression/rules/ConvertAggStateCast.java      |  2 +-
 .../nereids/rules/rewrite/CheckDataTypes.java      | 12 +++++
 .../functions/combinator/CombineCombinator.java    |  5 +-
 .../commands/insert/InsertIntoValuesAnalyzer.java  |  6 ++-
 .../apache/doris/nereids/types/AggStateType.java   | 15 +-----
 .../doris/nereids/util/TypeCoercionUtils.java      |  3 --
 .../combinator/CombineCombinatorTest.java          | 20 +++----
 .../trees/plans/ExplainInsertCommandTest.java      | 62 ++++++++++++++++++++++
 .../agg_state/avg/test_agg_state_avg.groovy        |  4 +-
 12 files changed, 110 insertions(+), 66 deletions(-)

diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/load/NereidsLoadPlanInfoCollector.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/load/NereidsLoadPlanInfoCollector.java
index 93a075c35f8..ec7724b7ef7 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/load/NereidsLoadPlanInfoCollector.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/load/NereidsLoadPlanInfoCollector.java
@@ -47,6 +47,7 @@ import 
org.apache.doris.nereids.glue.translator.PlanTranslatorContext;
 import org.apache.doris.nereids.parser.NereidsParser;
 import org.apache.doris.nereids.properties.PhysicalProperties;
 import org.apache.doris.nereids.rules.analysis.ExpressionAnalyzer;
+import org.apache.doris.nereids.rules.expression.check.CheckCast;
 import org.apache.doris.nereids.rules.expression.rules.ConvertAggStateCast;
 import org.apache.doris.nereids.rules.expression.rules.PartitionPruner;
 import 
org.apache.doris.nereids.rules.expression.rules.PartitionPruner.PartitionTableType;
@@ -359,7 +360,7 @@ public class NereidsLoadPlanInfoCollector extends 
DefaultPlanVisitor<Void, PlanT
                     output = TypeCoercionUtils.castIfNotSameType(output, 
targetType);
                 }
                 if (output instanceof Cast && 
output.getDataType().isAggStateType()) {
-                    output = ConvertAggStateCast.convert((Cast) output);
+                    output = 
CheckCast.validate(ConvertAggStateCast.convert((Cast) output));
                 }
             }
             Expr expr = ExpressionTranslator.translate(output, context);
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/ExpressionRewrite.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/ExpressionRewrite.java
index e9a1477d35c..336138dd7ff 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/ExpressionRewrite.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/ExpressionRewrite.java
@@ -377,7 +377,8 @@ public class ExpressionRewrite implements 
RewriteRuleFactory {
         }
     }
 
-    private class LogicalSetOperationRewrite extends OneRewriteRuleFactory {
+    /** Rewrite set-operation inputs, including constant rows stored directly 
in a union. */
+    public class LogicalSetOperationRewrite extends OneRewriteRuleFactory {
         @Override
         public Rule build() {
             return logicalSetOperation().thenApply(ctx -> {
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/check/CheckCast.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/check/CheckCast.java
index c7a2e7a6eb0..f06493bc6c7 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/check/CheckCast.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/check/CheckCast.java
@@ -366,22 +366,20 @@ public class CheckCast implements 
ExpressionPatternRuleFactory {
     @Override
     public List<ExpressionPatternMatcher<? extends Expression>> buildRules() {
         return ImmutableList.of(
-                matchesType(Cast.class).thenApply(ctx -> {
-                    Cast cast = ctx.expr;
-                    DataType originalType = cast.child().getDataType();
-                    DataType targetType = cast.getDataType();
-                    if (!check(originalType, targetType, 
SessionVariable.enableStrictCast())) {
-                        if (requiresExactAggStateMatch(originalType, 
targetType)) {
-                            throw new 
AnalysisException(exactAggStateMatchError(originalType, targetType));
-                        }
-                        throw new AnalysisException("cannot cast " + 
originalType.toSql()
-                                + " to " + targetType.toSql());
-                    }
-                    return cast;
-                }).toRule(ExpressionRuleType.CHECK_CAST)
+                
matchesType(Cast.class).then(CheckCast::validate).toRule(ExpressionRuleType.CHECK_CAST)
         );
     }
 
+    /** Validate a bound cast after expression rewrites. */
+    public static Cast validate(Cast cast) {
+        DataType source = cast.child().getDataType();
+        DataType target = cast.getDataType();
+        if (!check(source, target, SessionVariable.enableStrictCast())) {
+            throw new AnalysisException("cannot cast " + source.toSql() + " to 
" + target.toSql());
+        }
+        return cast;
+    }
+
     public static boolean checkWithLooseAggState(DataType originalType, 
DataType targetType, boolean isStrictMode) {
         return check(originalType, targetType, isStrictMode, true);
     }
@@ -418,8 +416,7 @@ public class CheckCast implements 
ExpressionPatternRuleFactory {
         if (looseAggState && originalType instanceof AggStateType && 
targetType instanceof AggStateType) {
             AggStateType originalAggState = (AggStateType) originalType;
             AggStateType targetAggState = (AggStateType) targetType;
-            if (originalAggState.isLooseTypeCoercionAllowed()
-                    && 
originalAggState.getFunctionName().equalsIgnoreCase(targetAggState.getFunctionName())
+            if 
(originalAggState.getFunctionName().equalsIgnoreCase(targetAggState.getFunctionName())
                     && originalAggState.getSubTypes().size() == 
targetAggState.getSubTypes().size()) {
                 return true;
             }
@@ -484,20 +481,6 @@ public class CheckCast implements 
ExpressionPatternRuleFactory {
         }
     }
 
-    /** Whether the source AggState only allows an exact target type. */
-    public static boolean requiresExactAggStateMatch(DataType originalType, 
DataType targetType) {
-        return originalType instanceof AggStateType
-                && targetType instanceof AggStateType
-                && !((AggStateType) originalType).isLooseTypeCoercionAllowed()
-                && !originalType.equals(targetType);
-    }
-
-    /** Build the analysis error for a non-exact aggregate combine state cast. 
*/
-    public static String exactAggStateMatchError(DataType originalType, 
DataType targetType) {
-        return "Aggregate combine state requires an exact AggState type match: 
cannot cast "
-                + originalType.toSql() + " to " + targetType.toSql();
-    }
-
     /**
      * check if sourceType contains the given targetType
      *
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/rules/ConvertAggStateCast.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/rules/ConvertAggStateCast.java
index fda66e42bd1..ef861444936 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/rules/ConvertAggStateCast.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/rules/ConvertAggStateCast.java
@@ -51,7 +51,7 @@ public class ConvertAggStateCast implements 
ExpressionPatternRuleFactory {
     }
 
     /** convert */
-    public static Expression convert(Cast cast) {
+    public static Cast convert(Cast cast) {
         Expression child = cast.child();
         DataType originalType = child.getDataType();
         DataType targetType = cast.getDataType();
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/CheckDataTypes.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/CheckDataTypes.java
index 4bfa8fb954a..f1396c07e61 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/CheckDataTypes.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/CheckDataTypes.java
@@ -20,6 +20,8 @@ package org.apache.doris.nereids.rules.rewrite;
 import org.apache.doris.nereids.exceptions.AnalysisException;
 import org.apache.doris.nereids.exceptions.UnboundException;
 import org.apache.doris.nereids.jobs.JobContext;
+import org.apache.doris.nereids.rules.expression.check.CheckCast;
+import org.apache.doris.nereids.trees.expressions.Cast;
 import org.apache.doris.nereids.trees.expressions.Expression;
 import 
org.apache.doris.nereids.trees.expressions.visitor.DefaultExpressionVisitor;
 import org.apache.doris.nereids.trees.plans.Plan;
@@ -99,6 +101,16 @@ public class CheckDataTypes implements CustomRewriter {
             return expr;
         }
 
+        @Override
+        public Expression visitCast(Cast cast, Void unused) {
+            // Expression normalization skips guarded MERGE branches. Check 
the surviving state
+            // signatures here, where traversal only inspects types and never 
evaluates a branch.
+            if (cast.getDataType().isAggStateType() && 
cast.child().getDataType().isAggStateType()) {
+                CheckCast.validate(cast);
+            }
+            return visit(cast, unused);
+        }
+
         private void checkTypes(DataType dataType) {
             if (dataType instanceof ArrayType) {
                 checkTypes(((ArrayType) dataType).getItemType());
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/combinator/CombineCombinator.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/combinator/CombineCombinator.java
index 9b62fa30688..22fd8bde2b2 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/combinator/CombineCombinator.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/combinator/CombineCombinator.java
@@ -84,15 +84,12 @@ public class CombineCombinator extends AggregateFunction
     }
 
     private static AggStateType createReturnType(List<Expression> arguments, 
AggregateFunction nested) {
-        // The raw arguments determine the nested signature. Retargeting this 
state through a loose
-        // AggState cast would make FE metadata disagree with the state 
produced by the aggregate.
         return new AggStateType(nested.getName(),
                 arguments.stream().map(ExpressionTrait::getDataType)
                         .collect(ImmutableList.toImmutableList()),
                 arguments.stream().map(ExpressionTrait::nullable)
                         .collect(ImmutableList.toImmutableList()),
-                
BuiltinAggregateFunctions.INSTANCE.aggFuncNameNullableMap.get(nested.getName()),
-                false);
+                
BuiltinAggregateFunctions.INSTANCE.aggFuncNameNullableMap.get(nested.getName()));
     }
 
     @Override
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/insert/InsertIntoValuesAnalyzer.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/insert/InsertIntoValuesAnalyzer.java
index aee33ba5774..22d044720f0 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/insert/InsertIntoValuesAnalyzer.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/insert/InsertIntoValuesAnalyzer.java
@@ -27,6 +27,7 @@ import org.apache.doris.nereids.rules.RuleType;
 import org.apache.doris.nereids.rules.analysis.BindSink;
 import org.apache.doris.nereids.rules.expression.ExpressionRewrite;
 import org.apache.doris.nereids.rules.expression.ExpressionRewriteRule;
+import org.apache.doris.nereids.rules.expression.check.CheckCast;
 import org.apache.doris.nereids.rules.expression.rules.ConvertAggStateCast;
 import org.apache.doris.nereids.rules.expression.rules.FoldConstantRuleOnFE;
 import org.apache.doris.nereids.rules.rewrite.MergeProjectable;
@@ -64,6 +65,7 @@ public class InsertIntoValuesAnalyzer extends 
AbstractBatchJobExecutor {
                     // we should replace the `test.my_key` to real key
                     new 
RewriteInsertIntoExpressions(ExpressionRewrite.bottomUp(
                             ConvertAggStateCast.INSTANCE,
+                            CheckCast.INSTANCE,
                             FoldConstantRuleOnFE.PATTERN_MATCH_INSTANCE
                     ))
             )
@@ -83,6 +85,7 @@ public class InsertIntoValuesAnalyzer extends 
AbstractBatchJobExecutor {
 
                     new 
RewriteInsertIntoExpressions(ExpressionRewrite.bottomUp(
                             ConvertAggStateCast.INSTANCE,
+                            CheckCast.INSTANCE,
                             FoldConstantRuleOnFE.PATTERN_MATCH_INSTANCE
                     ))
             )
@@ -131,7 +134,8 @@ public class InsertIntoValuesAnalyzer extends 
AbstractBatchJobExecutor {
         public List<Rule> buildRules() {
             return ImmutableList.of(
                     new ProjectExpressionRewrite().build(),
-                    new OneRowRelationExpressionRewrite().build()
+                    new OneRowRelationExpressionRewrite().build(),
+                    new LogicalSetOperationRewrite().build()
             );
         }
     }
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/types/AggStateType.java 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/types/AggStateType.java
index 46c245cfefa..9f014d35c74 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/types/AggStateType.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/types/AggStateType.java
@@ -64,8 +64,6 @@ public class AggStateType extends DataType {
     private final List<DataType> subTypes;
     private final List<Boolean> subTypeNullables;
     private final boolean returnNullable;
-    // Planning-only coercion policy; it is not part of the serialized 
AggState type identity.
-    private final boolean looseTypeCoercionAllowed;
 
     /**
      * Constructor for AggStateType
@@ -76,12 +74,6 @@ public class AggStateType extends DataType {
      */
     public AggStateType(String functionName, List<DataType> subTypes,
             List<Boolean> subTypeNullables, boolean returnNullable) {
-        this(functionName, subTypes, subTypeNullables, returnNullable, true);
-    }
-
-    /** Constructor with a planning-time type coercion policy. */
-    public AggStateType(String functionName, List<DataType> subTypes,
-            List<Boolean> subTypeNullables, boolean returnNullable, boolean 
looseTypeCoercionAllowed) {
         // be only supports lowercase function names
         Objects.requireNonNull(functionName, "functionName should not be 
null");
         functionName = functionName.toLowerCase(Locale.ROOT);
@@ -92,7 +84,6 @@ public class AggStateType extends DataType {
         Preconditions.checkState(subTypes.size() == subTypeNullables.size(),
                 "AggStateType' subTypes.size()!=subTypeNullables.size()");
         this.returnNullable = returnNullable;
-        this.looseTypeCoercionAllowed = looseTypeCoercionAllowed;
     }
 
     public List<DataType> getSubTypes() {
@@ -107,10 +98,6 @@ public class AggStateType extends DataType {
         return functionName;
     }
 
-    public boolean isLooseTypeCoercionAllowed() {
-        return looseTypeCoercionAllowed;
-    }
-
     @Override
     public Type toCatalogDataType() {
         List<Type> types = 
subTypes.stream().map(DataType::toCatalogDataType).collect(Collectors.toList());
@@ -121,7 +108,7 @@ public class AggStateType extends DataType {
     public DataType conversion() {
         return new AggStateType(functionName,
                 
subTypes.stream().map(DataType::conversion).collect(Collectors.toList()),
-                subTypeNullables, returnNullable, looseTypeCoercionAllowed);
+                subTypeNullables, returnNullable);
     }
 
     @Override
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/util/TypeCoercionUtils.java 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/util/TypeCoercionUtils.java
index 61f3dd4c2fa..73777eada4f 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/util/TypeCoercionUtils.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/util/TypeCoercionUtils.java
@@ -606,9 +606,6 @@ public class TypeCoercionUtils {
         if (canCastTo(input, target)) {
             return;
         }
-        if (CheckCast.requiresExactAggStateMatch(input, target)) {
-            throw new 
AnalysisException(CheckCast.exactAggStateMatchError(input, target));
-        }
         throw new AnalysisException("can not cast from origin type " + input + 
" to target type=" + target);
     }
 
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/expressions/functions/combinator/CombineCombinatorTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/expressions/functions/combinator/CombineCombinatorTest.java
index 97c3b4c58eb..125cc7ad6ea 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/expressions/functions/combinator/CombineCombinatorTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/expressions/functions/combinator/CombineCombinatorTest.java
@@ -146,17 +146,17 @@ class CombineCombinatorTest {
                 ImmutableList.of(IntegerType.INSTANCE), 
ImmutableList.of(true), true);
 
         Assertions.assertTrue(CheckCast.checkWithLooseAggState(exactType, 
exactType, false));
-        Assertions.assertFalse(CheckCast.checkWithLooseAggState(exactType, 
differentSubtype, false));
-        Assertions.assertFalse(CheckCast.checkWithLooseAggState(exactType, 
differentNullability, false));
-        Assertions.assertTrue(CheckCast.checkWithLooseAggState(
-                StateCombinator.create(new Avg(argument)).getDataType(), 
differentSubtype, false));
-
-        AnalysisException exception = 
Assertions.assertThrows(AnalysisException.class,
-                () -> PlanChecker.from(MemoTestUtils.createConnectContext())
-                        .analyze("select cast(avg_combine(cast(1 as int)) "
-                                + "as agg_state<avg(bigint not null)>)"));
+        Assertions.assertTrue(CheckCast.checkWithLooseAggState(exactType, 
differentSubtype, false));
+        Assertions.assertTrue(CheckCast.checkWithLooseAggState(exactType, 
differentNullability, false));
+        Assertions.assertTrue(CheckCast.check(exactType, exactType, false));
+        Assertions.assertFalse(CheckCast.check(exactType, differentSubtype, 
false));
+        Assertions.assertFalse(CheckCast.check(exactType, 
differentNullability, false));
+
+        PlanChecker checker = 
PlanChecker.from(MemoTestUtils.createConnectContext())
+                .analyze("select cast(avg_combine(cast(1 as int)) as 
agg_state<avg(bigint not null)>)");
+        AnalysisException exception = 
Assertions.assertThrows(AnalysisException.class, checker::rewrite);
         Assertions.assertTrue(exception.getMessage().contains(
-                "Aggregate combine state requires an exact AggState type 
match"));
+                "cannot cast agg_state<avg("));
     }
 
     @Test
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/ExplainInsertCommandTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/ExplainInsertCommandTest.java
index 329d854052f..cf3036948ba 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/ExplainInsertCommandTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/ExplainInsertCommandTest.java
@@ -28,6 +28,7 @@ import org.apache.doris.nereids.properties.PhysicalProperties;
 import org.apache.doris.nereids.trees.expressions.StatementScopeIdGenerator;
 import org.apache.doris.nereids.trees.plans.commands.ExplainCommand;
 import 
org.apache.doris.nereids.trees.plans.commands.ExplainCommand.ExplainLevel;
+import 
org.apache.doris.nereids.trees.plans.commands.insert.FastInsertIntoValuesPlanner;
 import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
 import org.apache.doris.nereids.trees.plans.physical.PhysicalPlan;
 import org.apache.doris.nereids.util.MemoTestUtils;
@@ -137,6 +138,67 @@ public class ExplainInsertCommandTest extends 
TestWithFeService {
         Assertions.assertEquals(9, 
getOutputFragment(sql).getOutputExprs().size());
     }
 
+    @Test
+    public void testInsertAggStateCasts() throws Exception {
+        boolean enabled = connectContext.getSessionVariable().enableAggState;
+        connectContext.getSessionVariable().enableAggState = true;
+        try {
+            createTable("create table values_avg (k int, s 
agg_state<avg(bigint not null)> generic) "
+                    + "aggregate key(k) distributed by hash(k) buckets 1 
properties('replication_num'='1')");
+            String insert = "insert into values_avg ";
+            getOutputFragment("explain " + insert + "select 1, 
avg_combine(cast(1 as bigint))");
+            AnalysisException mismatch = 
Assertions.assertThrows(AnalysisException.class,
+                    () -> getOutputFragment("explain " + insert + "select 1, 
avg_combine(cast(1 as int))"));
+            Assertions.assertTrue(mismatch.getMessage().contains("cannot cast 
agg_state<avg("), mismatch.getMessage());
+
+            String valid = "(1, avg_state(cast(1 as int)))";
+            String invalid = "(2, if(rand() < 0.5, avg_state(cast(2 as int)), 
avg_state(cast(3 as int))))";
+            for (boolean batch : new boolean[] {false, true}) {
+                planFastValues(insert + "values " + valid, batch);
+                for (String rows : new String[] {invalid, valid + "," + 
invalid}) {
+                    AnalysisException error = 
Assertions.assertThrows(AnalysisException.class,
+                            () -> planFastValues(insert + "values " + rows, 
batch));
+                    Assertions.assertTrue(error.getMessage().contains("cannot 
cast agg_state<avg("), error.getMessage());
+                }
+            }
+        } finally {
+            connectContext.getSessionVariable().enableAggState = enabled;
+        }
+    }
+
+    @Test
+    public void testMergeGuardedAggStateCast() throws Exception {
+        boolean enableAggState = 
connectContext.getSessionVariable().enableAggState;
+        String disabled = String.join(",", 
connectContext.getSessionVariable().getDisableNereidsRuleNames());
+        try {
+            // The mock tables have no rowsets. Keep their scans and the 
guarded assignment in the plan.
+            
connectContext.getSessionVariable().setDisableNereidsRules(disabled + 
",PRUNE_EMPTY_PARTITION");
+            connectContext.getSessionVariable().enableAggState = true;
+            createTable("create table merge_min_target (k int, v bigint) "
+                    + "unique key(k) distributed by hash(k) buckets 1 "
+                    + "properties('replication_num'='1', 
'enable_unique_key_merge_on_write'='true')");
+            createTable("create table merge_min_src (k int, d double not null, 
b bigint not null) "
+                    + "duplicate key(k) distributed by hash(k) buckets 1 
properties('replication_num'='1')");
+            String merge = "explain merge into merge_min_target t using "
+                    + "(select k, min_combine(%s) as s from merge_min_src 
group by k) q on t.k=q.k "
+                    + "when matched and t.k >= 0 then update set 
v=min_finalize(cast(q.s as "
+                    + "agg_state<min(bigint not null)>)) when matched then 
update set v=t.v";
+            getOutputFragment(String.format(merge, "b"));
+            AnalysisException error = 
Assertions.assertThrows(AnalysisException.class,
+                    () -> getOutputFragment(String.format(merge, "d")));
+            Assertions.assertTrue(error.getMessage().contains("cannot cast 
agg_state<min("), error.getMessage());
+        } finally {
+            
connectContext.getSessionVariable().setDisableNereidsRules(disabled);
+            connectContext.getSessionVariable().enableAggState = 
enableAggState;
+        }
+    }
+
+    private void planFastValues(String sql, boolean batch) throws Exception {
+        StatementContext context = 
MemoTestUtils.createStatementContext(connectContext, sql);
+        LogicalPlan logical = (LogicalPlan) ((Explainable) 
parser.parseSingle(sql)).getExplainPlan(connectContext);
+        new FastInsertIntoValuesPlanner(context, true, 
batch).planWithLock(logical, PhysicalProperties.ANY);
+    }
+
     @Test
     public void testInsertIntoRowTtlTable() throws Exception {
         String sql = "explain insert into row_ttl_dup(k, event_time, v) values"
diff --git 
a/regression-test/suites/datatype_p0/agg_state/avg/test_agg_state_avg.groovy 
b/regression-test/suites/datatype_p0/agg_state/avg/test_agg_state_avg.groovy
index e798b5d926c..a8a855f608a 100644
--- a/regression-test/suites/datatype_p0/agg_state/avg/test_agg_state_avg.groovy
+++ b/regression-test/suites/datatype_p0/agg_state/avg/test_agg_state_avg.groovy
@@ -97,14 +97,14 @@ suite("test_agg_state_avg") {
             select cast(avg_combine(cast(1 as int))
                 as agg_state<avg(bigint not null)>)
         """
-        exception "Aggregate combine state requires an exact AggState type 
match"
+        exception "cannot cast agg_state<avg("
     }
     test {
         sql """
             insert into a_table
             select 100, avg_combine(cast(1 as bigint))
         """
-        exception "Aggregate combine state requires an exact AggState type 
match"
+        exception "cannot cast agg_state<avg("
     }
     sql """
         insert into a_table


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to