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

englefly 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 684972df7af [fix](nereids) Include lateral ON predicates in physical 
generate expressions (#70918)
684972df7af is described below

commit 684972df7af9b343d70a9df5b6e220d8721f361f
Author: minghong <[email protected]>
AuthorDate: Thu Nov 26 12:56:45 2026 +0800

    [fix](nereids) Include lateral ON predicates in physical generate 
expressions (#70918)
    
    ### Background
    
    Nereids represents a lateral UNNEST join as a generate operator with a
    list of generators and the join's ON predicates. Physical plan visitors
    use the operator's expression list to inspect expressions it evaluates.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: #58228 (introduced lateral UNNEST conjuncts), #70516 (review
    identified the missing expressions)
    PR Type: Bugfix
    
    Problem Summary:
    
    For `JOIN LATERAL UNNEST(xs) AS t(x) ON assert_true(x > 0, 'bad')`, the
    physical generate expression list omits the assertion. A visitor that
    relies on the list to detect non-movable expressions can miss it.
    Include the ON predicates in the expression list and validate them
    against the child and generated columns.
    
    ### Details
    
    - **Frequency:** Always when an expression visitor reads a physical
    generate with a lateral ON predicate.
    - **Root cause:** `PhysicalGenerate.getExpressions()` enumerates the
    generators. The ON predicates are stored separately in `getConjuncts()`
    and are translated into the execution plan.
    - **Why existing tests missed it:** `GenerateConjunctRewriteTest`
    exercises logical ExprId rewriting. `TopnLazyMaterializeTest` covered
    lateral predicate inputs through a special case in lazy materialization.
    The `nereids_unnest_fn` and `topn_lazy_order_by_alias` SQL suites
    exercise join results and materialization plans. The physical expression
    list was untested.
    - **Fix:** Include the ON predicates in the physical expression list.
    Validate generator arguments against child outputs and validate ON
    predicates against child and generated outputs. Use the physical
    generate's input-slot set to keep the predicate's child columns
    materialized.
    - **Other paths and branches:** `LogicalGenerate` already includes ON
    predicates. The omission was introduced by #58228 and is present on
    branches 4.1 and 4.2. The checked 3.1 and 4.0 branches have no lateral
    ON conjuncts on `PhysicalGenerate`.
    - **Behavior change:** Physical plan validation reports unavailable
    slots in lateral ON predicates. The error identifies the slot and the
    IDs available for that expression.
    
    ### Testing
    
    - `PhysicalGenerateTest` passed locally. It asserts that the list
    contains both the generator and the assertion, then checks valid and
    unavailable ON slots. The baseline expression list was checked in source
    and contains only the generator.
    - `GenerateConjunctRewriteTest` and
    
`TopnLazyMaterializeTest.testLateralGenerateConjunctKeepsItsAliasSourceMaterialized`
    passed in the same FE unit test run.
    - FE core Checkstyle passed with zero violations.
    
    ### Release note
    
    Physical plan checks now account for lateral UNNEST join predicates.
    
    ### Check List (For Author)
    
    - Behavior changed: Yes (see Details)
    - Does this need documentation: No
    - Pre-submission status: Ready
    
    ### AI Disclosure
    
    - Tool: OpenAI Codex (GPT-6)
    - Generated: Code, tests, and PR description
    - Human review: not stated
---
 .../doris/nereids/processor/post/Validator.java    | 30 +++++++---
 .../post/materialize/LazyMaterializeTopN.java      | 12 ----
 .../trees/plans/physical/PhysicalGenerate.java     | 20 ++++++-
 .../postprocess/TopnLazyMaterializeTest.java       | 11 ++--
 .../trees/plans/physical/PhysicalGenerateTest.java | 65 ++++++++++++++++++++++
 5 files changed, 111 insertions(+), 27 deletions(-)

diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/Validator.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/Validator.java
index 926e12cd279..38d078d7d88 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/Validator.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/Validator.java
@@ -26,12 +26,14 @@ import 
org.apache.doris.nereids.trees.expressions.literal.BooleanLiteral;
 import org.apache.doris.nereids.trees.plans.Plan;
 import org.apache.doris.nereids.trees.plans.algebra.Aggregate;
 import org.apache.doris.nereids.trees.plans.physical.PhysicalFilter;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalGenerate;
 import org.apache.doris.nereids.trees.plans.physical.PhysicalProject;
 import org.apache.doris.nereids.util.LazyCompute;
 
 import com.google.common.base.Preconditions;
 
 import java.util.BitSet;
+import java.util.List;
 import java.util.function.Supplier;
 
 /**
@@ -63,9 +65,7 @@ public class Validator extends PlanPostProcessor {
         return plan;
     }
 
-    /**
-     * Check all slot must from children.
-     */
+    /** Validates expression slots against the child outputs and, for lateral 
ON, generated outputs. */
     public static void checkAllSlotFromChildren(Plan plan) {
         if (plan.arity() == 0) {
             return;
@@ -85,16 +85,32 @@ public class Validator extends PlanPostProcessor {
             return ids;
         });
 
-        for (Expression expression : plan.getExpressions()) {
+        if (plan instanceof PhysicalGenerate) {
+            PhysicalGenerate<?> generate = (PhysicalGenerate<?>) plan;
+            checkSlots(generate, generate.getGenerators(), childrenOutputIds);
+            checkSlots(generate, generate.getConjuncts(), LazyCompute.of(() -> 
{
+                BitSet ids = childrenOutputIds.get();
+                for (Slot slot : generate.getGeneratorOutput()) {
+                    ids.set(slot.getExprId().asInt());
+                }
+                return ids;
+            }));
+            return;
+        }
+        checkSlots(plan, plan.getExpressions(), childrenOutputIds);
+    }
+
+    private static void checkSlots(Plan plan, List<? extends Expression> 
expressions, Supplier<BitSet> outputIds) {
+        for (Expression expression : expressions) {
             expression.anyMatch(e -> {
                 if (e instanceof Slot) {
                     Slot slot = (Slot) e;
                     if (slot.getName().startsWith("mv") || slot instanceof 
SlotNotFromChildren) {
                         return false;
                     }
-                    if 
(!childrenOutputIds.get().get(slot.getExprId().asInt())) {
-                        throw new AnalysisException("A expression contains 
slot not from children\n"
-                                + "Slot: " + slot + "  Children Output:" + 
childrenOutputIds.get() + "\n"
+                    if (!outputIds.get().get(slot.getExprId().asInt())) {
+                        throw new AnalysisException("An expression references 
an unavailable slot\n"
+                                + "Slot: " + slot + "  Available Output IDs: " 
+ outputIds.get() + "\n"
                                 + "Plan: " + plan.treeString() + "\n");
                     }
                 }
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/materialize/LazyMaterializeTopN.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/materialize/LazyMaterializeTopN.java
index 11cd45d9115..904ac8f02a9 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/materialize/LazyMaterializeTopN.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/materialize/LazyMaterializeTopN.java
@@ -37,20 +37,17 @@ import 
org.apache.doris.nereids.trees.plans.algebra.CatalogRelation;
 import org.apache.doris.nereids.trees.plans.algebra.Relation;
 import org.apache.doris.nereids.trees.plans.physical.PhysicalCatalogRelation;
 import org.apache.doris.nereids.trees.plans.physical.PhysicalFilter;
-import org.apache.doris.nereids.trees.plans.physical.PhysicalGenerate;
 import org.apache.doris.nereids.trees.plans.physical.PhysicalLazyMaterialize;
 import org.apache.doris.nereids.trees.plans.physical.PhysicalProject;
 import org.apache.doris.nereids.trees.plans.physical.PhysicalSetOperation;
 import org.apache.doris.nereids.trees.plans.physical.PhysicalTVFRelation;
 import org.apache.doris.nereids.trees.plans.physical.PhysicalTopN;
-import org.apache.doris.nereids.util.PlanUtils;
 import org.apache.doris.qe.SessionVariable;
 
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.collect.BiMap;
 import com.google.common.collect.HashBiMap;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Sets;
 import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;
 
@@ -367,15 +364,6 @@ public class LazyMaterializeTopN extends PlanPostProcessor 
{
                 && 
MaterializeProbeVisitor.isIndexLazyFilter((PhysicalFilter<?>) plan)) {
             indexLazySlots.addAll(plan.getInputSlots());
         }
-        if (plan instanceof PhysicalGenerate) {
-            // PhysicalGenerate.getExpressions() exposes the generators only, 
while the lateral conjuncts
-            // are preserved by the implementation rule and executed by the 
generate itself. Generator
-            // outputs are produced by the generate, never by the child, 
exactly like LogicalGenerate.
-            PhysicalGenerate<?> generate = (PhysicalGenerate<?>) plan;
-            consumedSlots.addAll(Sets.difference(
-                    PlanUtils.fastGetInputSlots(generate.getConjuncts()),
-                    new HashSet<>(generate.getGeneratorOutput())));
-        }
         for (Plan child : plan.children()) {
             collectConsumedSlots(child, consumedSlots, indexLazySlots);
         }
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/PhysicalGenerate.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/PhysicalGenerate.java
index 8546c9b325b..888a7b08a91 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/PhysicalGenerate.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/PhysicalGenerate.java
@@ -29,15 +29,19 @@ import org.apache.doris.nereids.trees.plans.Plan;
 import org.apache.doris.nereids.trees.plans.PlanType;
 import org.apache.doris.nereids.trees.plans.algebra.Generate;
 import org.apache.doris.nereids.trees.plans.visitor.PlanVisitor;
+import org.apache.doris.nereids.util.PlanUtils;
 import org.apache.doris.nereids.util.Utils;
 import org.apache.doris.statistics.model.Statistics;
 
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Sets;
 
 import java.util.List;
 import java.util.Objects;
 import java.util.Optional;
+import java.util.Set;
 
 /**
  * PhysicalGenerate
@@ -82,7 +86,21 @@ public class PhysicalGenerate<CHILD_TYPE extends Plan> 
extends PhysicalUnary<CHI
 
     @Override
     public List<? extends Expression> getExpressions() {
-        return generators;
+        if (conjuncts.isEmpty()) {
+            return generators;
+        }
+        return 
ImmutableList.<Expression>builderWithExpectedSize(generators.size() + 
conjuncts.size())
+                .addAll(generators)
+                .addAll(conjuncts)
+                .build();
+    }
+
+    @Override
+    public Set<Slot> getInputSlots() {
+        if (conjuncts.isEmpty()) {
+            return PlanUtils.fastGetInputSlots(generators);
+        }
+        return Sets.difference(PlanUtils.fastGetInputSlots(getExpressions()), 
ImmutableSet.copyOf(generatorOutput));
     }
 
     public List<Expression> getConjuncts() {
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/postprocess/TopnLazyMaterializeTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/postprocess/TopnLazyMaterializeTest.java
index 010d3749758..0ecdb28fd13 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/postprocess/TopnLazyMaterializeTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/postprocess/TopnLazyMaterializeTest.java
@@ -260,10 +260,8 @@ public class TopnLazyMaterializeTest extends SSBTestBase {
         boolean feDebug = connectContext.getSessionVariable().feDebug;
         connectContext.getSessionVariable().feDebug = false;
         try {
-            // The generate conjunct reads `x`, which is an alias of lazy_col. 
PhysicalGenerate exposes
-            // only its generators through getInputSlots(), so the conjunct 
inputs have to be resolved
-            // explicitly: otherwise lazy_col is pruned from the scan while 
`lazy_col AS x` below the
-            // generate still reads it. Only other_col (read by nothing below 
the TopN) stays lazy.
+            // The generate conjunct reads `x`, which is an alias of lazy_col. 
Only other_col stays lazy
+            // because nothing below the TopN reads it.
             PhysicalPlan plan = postProcess("select s.y, s.w from (select 
lazy_col as x, lazy_col as y, "
                     + "other_col as w, arr, sort_col from 
lazy_materialize_lateral_tbl) s "
                     + "left join lateral unnest(s.arr) tt(tag) on tt.tag = s.x 
"
@@ -274,9 +272,8 @@ public class TopnLazyMaterializeTest extends SSBTestBase {
             Assertions.assertEquals(ImmutableList.of(ImmutableList.of(2)),
                     materializeNodes.get(0).getLazyBaseColumnIndices(), 
plan.treeString());
 
-            // The conjunct reads the bare lazy_col, which the same Project 
also aliases as `y`. Probing
-            // `y` resolves through that alias to lazy_col and no operator 
below the TopN stops the probe
-            // for the bare slot, so lazy_col has to stay materialized for the 
conjunct as well.
+            // The conjunct also keeps lazy_col materialized when it reads the 
bare slot and the
+            // Project returns that column under the alias `y`.
             plan = postProcess("select s.y, s.w from (select lazy_col as y, 
other_col as w, arr, sort_col, "
                     + "lazy_col from lazy_materialize_lateral_tbl) s "
                     + "left join lateral unnest(s.arr) tt(tag) on tt.tag = 
s.lazy_col "
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/physical/PhysicalGenerateTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/physical/PhysicalGenerateTest.java
new file mode 100644
index 00000000000..2c3838a5305
--- /dev/null
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/physical/PhysicalGenerateTest.java
@@ -0,0 +1,65 @@
+// 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.trees.plans.physical;
+
+import org.apache.doris.nereids.exceptions.AnalysisException;
+import org.apache.doris.nereids.processor.post.Validator;
+import org.apache.doris.nereids.properties.DataTrait;
+import org.apache.doris.nereids.properties.LogicalProperties;
+import org.apache.doris.nereids.trees.expressions.Alias;
+import org.apache.doris.nereids.trees.expressions.GreaterThan;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+import org.apache.doris.nereids.trees.expressions.functions.generator.Unnest;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.AssertTrue;
+import org.apache.doris.nereids.trees.expressions.literal.ArrayLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.IntegerLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.StringLiteral;
+import org.apache.doris.nereids.trees.plans.RelationId;
+import org.apache.doris.nereids.types.IntegerType;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+class PhysicalGenerateTest {
+    @Test
+    void testLateralConjunctExpressionsAndSlots() {
+        Alias array = new Alias(new ArrayLiteral(ImmutableList.of(new 
IntegerLiteral(1))), "xs");
+        Alias threshold = new Alias(new IntegerLiteral(0), "threshold");
+        LogicalProperties childProperties = new LogicalProperties(
+                () -> ImmutableList.of(array.toSlot(), threshold.toSlot()), () 
-> DataTrait.EMPTY_TRAIT);
+        PhysicalOneRowRelation child = new PhysicalOneRowRelation(
+                new RelationId(1), ImmutableList.of(array, threshold), 
childProperties);
+        Unnest generator = new Unnest(array.toSlot());
+        Slot x = new SlotReference("x", IntegerType.INSTANCE);
+        AssertTrue conjunct = new AssertTrue(new GreaterThan(x, 
threshold.toSlot()), new StringLiteral("bad"));
+        PhysicalGenerate<?> generate = new 
PhysicalGenerate<>(ImmutableList.of(generator),
+                ImmutableList.of(x), ImmutableList.of(conjunct), null, child);
+
+        Assertions.assertEquals(ImmutableList.of(generator, conjunct), 
generate.getExpressions());
+        Assertions.assertEquals(ImmutableSet.of(array.toSlot(), 
threshold.toSlot()), generate.getInputSlots());
+        Assertions.assertDoesNotThrow(() -> 
Validator.checkAllSlotFromChildren(generate));
+
+        Slot missing = new SlotReference("missing", IntegerType.INSTANCE);
+        PhysicalGenerate<?> invalid = new 
PhysicalGenerate<>(generate.getGenerators(), generate.getGeneratorOutput(),
+                ImmutableList.of(new GreaterThan(x, missing)), null, child);
+        Assertions.assertThrows(AnalysisException.class, () -> 
Validator.checkAllSlotFromChildren(invalid));
+    }
+}


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

Reply via email to