924060929 commented on code in PR #69304:
URL: https://github.com/apache/doris/pull/69304#discussion_r4778816110


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/types/AggStateType.java:
##########
@@ -128,6 +173,11 @@ public boolean equals(Object o) {
         }
 
         AggStateType rhs = (AggStateType) o;
+        // A sink must not treat version 21 state bytes as legacy state bytes.
+        // Keep the cast so that the STATE producer can use the target codec.
+        if (beExecVersion != rhs.beExecVersion) {

Review Comment:
   [P1] Architectural concern: according to the BE changes, `bitmap_intersect` 
(with nullable input) is the only function whose persisted `AGG_STATE` bytes 
change at version 21 (`[0]` no-input marker), while other aggregate functions 
remain byte-compatible across v19/v20/v21.
   
   Making `AggStateType.equals()` version-sensitive for **all** functions and 
rejecting all v21 -> v19/20 casts forces FE to introduce a 450-line 
`PushDownAggStateCast` rule that manually penetrates 14+ operators 
(re-implementing set-op lowering, volatile extraction, early CTE inlining, and 
multi-output `LogicalApply`), while still leaving unexhausted gaps 
(materialized CTEs, `Nullable`/`NonNullable` wrappers, window functions, future 
operators).
   
   Consider either:
   1. Scoping downgrade incompatibility to functions whose persisted bytes 
actually differ (i.e. nullable `bitmap_intersect`), or
   2. Handling `CAST(AggState@v21 AS AggState@v19)` on the BE side (zero-copy 
passthrough for byte-compatible functions; convert or reject `[0]` for 
`bitmap_intersect`), so FE only needs to persist/propagate `beExecVersion` 
without optimizer-wide cast pushdown.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PullUpProjectUnderApply.java:
##########
@@ -60,12 +58,9 @@ public Rule build() {
                     Plan newCorrelate = apply.withChildren(apply.left(), 
project.child());
                     List<NamedExpression> newProjects = new 
ArrayList<>(apply.left().getOutput());
                     if (apply.isScalar()) {
-                        // unnest correlated scalar subquery may add count(*) 
and any_value() to project list
-                        // the previous SubqueryToApply rule will make sure of 
it. So the output column
-                        // may be 1 or 2, we add a check here.
-                        int size = project.getProjects().size();
-                        Preconditions.checkState(size == 1 || size == 2,
-                                "ScalarSubquery should only have one or two 
output column");
+                        // Analysis already checks the SQL result width. 
Decorrelation
+                        // adds COUNT/ANY_VALUE outputs, and state codec 
rewrites can
+                        // add more internal outputs. Keep all of them in this 
project.

Review Comment:
   [P2] Removing the `size == 1 || size == 2` check here (and exposing extra 
columns in `LogicalApply.computeOutput()`) weakens a long-standing 
scalar-subquery invariant relied upon by subquery unnesting rules, which can 
mask unrelated planner bugs.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownAggStateCast.java:
##########
@@ -0,0 +1,449 @@
+// 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.hint.DistributeHint;
+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.IsNull;
+import org.apache.doris.nereids.trees.expressions.NamedExpression;
+import org.apache.doris.nereids.trees.expressions.NullSafeEqual;
+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.expressions.functions.combinator.UnionCombinator;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.If;
+import org.apache.doris.nereids.trees.expressions.literal.NullLiteral;
+import org.apache.doris.nereids.trees.plans.DistributeType;
+import org.apache.doris.nereids.trees.plans.JoinType;
+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.LogicalExcept;
+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.LogicalIntersect;
+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.LogicalRepeat;
+import org.apache.doris.nereids.trees.plans.logical.LogicalSetOperation;
+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;
+import java.util.Optional;
+
+/** Move codec-only state casts to STATE or COMBINE before its bytes are 
written. */
+public class PushDownAggStateCast extends OneRewriteRuleFactory {
+    @Override
+    public Rule build() {
+        // The rewriter owns the rules for each boundary. Do not repeat its 
supported
+        // nodes in this pattern: a missing node here can hide a valid 
producer path.
+        return logicalProject(any())
+                .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, NamedExpression> addedOutputs = new 
LinkedHashMap<>();
+        private final Map<Expression, Alias> postAggregateOutputs = new 
LinkedHashMap<>();
+        private final Map<Integer, StateCastRewriter> children = new 
HashMap<>();
+        private StateCastRewriter normalizedSetOperation;
+
+        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() {
+            if (normalizedSetOperation != null) {
+                return normalizedSetOperation.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;
+                aggregate = 
aggregate.withAggOutput(ImmutableList.<NamedExpression>builder()
+                        
.addAll(aggregate.getOutputExpressions()).addAll(addedOutputs.values()).build());
+                if (postAggregateOutputs.isEmpty()) {
+                    return aggregate;
+                }
+                // The aggregate can already be normalized. Keep scalar NULL 
masks
+                // in a project above it. Putting IF around ANY_VALUE in its 
output
+                // would give the aggregate result slot IF's nullable type 
instead
+                // of ANY_VALUE's type, and could omit the mask during 
translation.
+                return new 
LogicalProject<>(ImmutableList.<NamedExpression>builder()
+                        
.addAll(aggregate.getOutput()).addAll(postAggregateOutputs.values()).build(), 
aggregate);
+            }
+            if (rewritten instanceof LogicalRepeat) {
+                LogicalRepeat<?> repeat = (LogicalRepeat<?>) rewritten;
+                // These are payload slots, not grouping keys. Keep the 
grouping
+                // sets and their IDs unchanged. The aggregate masks a grouped
+                // result with the original key's SQL NULL after ANY_VALUE.
+                return 
repeat.withAggOutput(ImmutableList.<NamedExpression>builder()
+                        
.addAll(repeat.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 LogicalSetOperation) {
+                return retargetSetOperationSlot((Cast) expression);
+            }
+            if (plan instanceof LogicalApply) {
+                LogicalApply<?, ?> apply = (LogicalApply<?, ?>) plan;
+                if (apply.isScalar() && apply.isNeedAddSubOutputToProjects()
+                        && 
apply.right().getOutputSet().contains(expression.child(0))) {
+                    Cast inputCast = new Cast(expression.child(0), target);
+                    Expression converted = child(1).retargetSlot(inputCast);
+                    if (converted.equals(inputCast)) {
+                        return expression;
+                    }
+                    Preconditions.checkState(converted instanceof Slot);
+                    // Keep both codecs in the same scalar subquery. A second
+                    // subquery could read another row or repeat a volatile 
input.
+                    // All derived outputs become SQL NULL when it returns no 
rows.
+                    return ((Slot) converted).withNullable(true);
+                }
+            }
+            if (plan instanceof LogicalRepeat && 
plan.getOutputSet().contains(expression.child(0))) {
+                Cast inputCast = new Cast(expression.child(0), target);
+                Expression converted = child(0).retargetSlot(inputCast);
+                if (converted.equals(inputCast)) {
+                    return expression;
+                }
+                Preconditions.checkState(converted instanceof Slot);
+                // Two grouping aliases can share one converted payload slot.
+                return addedOutputs.computeIfAbsent(converted, ignored -> 
(Slot) converted).toSlot();
+            }
+            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. Generated slots are not 
child
+                // slots; their casts keep the 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)
+                        && !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.
+                    Slot result = addedOutputs.computeIfAbsent(new 
AnyValue(converted), Alias::new).toSlot();
+                    if (aggregate.getSourceRepeat().isPresent()) {
+                        // GROUPING SETS ((s), ()) sets s to SQL NULL for the 
total.
+                        // The extra payload passes through Repeat unchanged, 
so
+                        // mask its result with the original key. This also 
keeps
+                        // a real SQL NULL key NULL. Do not add a new grouping 
key:
+                        // that would change GROUPING_ID and duplicate-set IDs.
+                        Expression mask = new If(new 
IsNull(expression.child(0)), new NullLiteral(target), result);
+                        return postAggregateOutputs.computeIfAbsent(mask, 
Alias::new).toSlot();
+                    }
+                    return result;
+                }
+                if (input instanceof UnionCombinator || input instanceof 
AnyValue) {
+                    Cast inputCast = new Cast(input.child(0), target);
+                    Expression converted = 
child(0).rewriteExpression(inputCast);
+                    if (converted.equals(inputCast)) {
+                        return expression;
+                    }
+                    // Both aggregates return their input state's codec. 
Change the
+                    // raw STATE lineage and retain the aggregate. UNION still 
merges
+                    // the rows. ANY_VALUE still selects a row and preserves 
SQL NULL.
+                    // SubqueryToApply uses ANY_VALUE with COUNT to check 
scalar rows;
+                    // keep that COUNT and its assertion unchanged.
+                    return 
addedOutputs.computeIfAbsent(input.withChildren(converted), 
Alias::new).toSlot();

Review Comment:
   [P1] `input.withChildren(converted)` runs under 
`MoreFieldsThread.keepFunctionSignature(true)` (set by `Rewriter.execute()`), 
so `AnyValue` and `UnionCombinator` reuse their cached `originSignature` with 
the old `AggStateType` version (e.g., v21).
   
   `AnyValue` does not override `getDataType()` and returns 
`getSignature().returnType`, so the rewritten `AnyValue(converted@19)` still 
exposes `state@21` while the outer `Cast` has already been removed. Wrap this 
rebuild in `MoreFieldsThread.keepFunctionSignature(false, () -> 
input.withChildren(converted))` just like `ConvertAggStateCast` / 
`CombineCombinator` / `StateCombinator` do.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/jobs/executor/Rewriter.java:
##########
@@ -432,10 +434,15 @@ public class Rewriter extends AbstractBatchJobExecutor {
                     // plan nodes.
                     custom(RuleType.BIND_SCORE_TO_OLAP_SCAN, 
BindScoreToOlapScan::new),
                     custom(RuleType.FOLD_CONSTANT_FOR_SQL_CACHE, 
FoldConstantForSqlCache::new),
+                    // Expose eligible CTE producers before validating sink 
codec casts.
+                    // For example, a v19 sink must reach SUM_STATE behind a 
v21 CTE
+                    // consumer. Keep the existing materialization and 
volatility rules.
+                    custom(RuleType.PULL_UP_CTE_ANCHOR, PullUpCteAnchor::new),

Review Comment:
   [P1] Inserting `PULL_UP_CTE_ANCHOR` and `CTE_INLINE` at the beginning of 
`NORMALIZE_PLAN_JOBS` affects all CTE queries globally and breaks two 
invariants:
   
   1. **Correlated subquery + materialized CTE**: 
`PullUpCteAnchor.visitLogicalApply` pulls `LogicalCTEProducer` out of 
`LogicalApply.right()` before `Subquery unnesting` runs. If a materialized CTE 
inside a correlated subquery references outer `correlationSlot`s, 
`CorrelateApplyToUnCorrelateApply` can no longer see those correlated 
references under `LogicalApply`.
   2. **Stale `cteIdToConsumers` entries**: `CTEInline` appends consumers to 
`StatementContext.cteIdToConsumers` without clearing. Running it before 
`NORMALIZE_PLAN_JOBS` registers pre-normalization `LogicalCTEConsumer` 
instances that can be rewritten or eliminated later, leaving stale entries for 
`RuntimeFilterGenerator` and `CostModel`.
   
   Please do not alter the global CTE rewrite phase order for `AGG_STATE` cast 
pushdown.



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