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


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/spm/matcher/SPMAstCheckVisitor.java:
##########
@@ -0,0 +1,423 @@
+// 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.spm.matcher;
+
+import org.apache.doris.nereids.analyzer.UnboundFunction;
+import org.apache.doris.nereids.analyzer.UnboundSlot;
+import org.apache.doris.nereids.analyzer.UnboundStar;
+import org.apache.doris.nereids.spm.SPMPlanTreeSupport;
+import org.apache.doris.nereids.spm.placeholder.SpmConstList;
+import org.apache.doris.nereids.spm.placeholder.SpmConstVar;
+import org.apache.doris.nereids.trees.expressions.BinaryOperator;
+import org.apache.doris.nereids.trees.expressions.CompoundPredicate;
+import org.apache.doris.nereids.trees.expressions.DereferenceExpression;
+import org.apache.doris.nereids.trees.expressions.Exists;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.InPredicate;
+import org.apache.doris.nereids.trees.expressions.InSubquery;
+import org.apache.doris.nereids.trees.expressions.Match;
+import org.apache.doris.nereids.trees.expressions.ScalarSubquery;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+import org.apache.doris.nereids.trees.expressions.SubqueryExpr;
+import org.apache.doris.nereids.trees.expressions.WindowExpression;
+import org.apache.doris.nereids.trees.expressions.WindowFrame;
+import org.apache.doris.nereids.trees.expressions.literal.Literal;
+import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * Compares bind and user expressions and records user expressions under 
scalar or IN-list marker ids. Concrete
+ * expression classes and operator metadata are checked before recursively 
comparing children. SlotReference uses
+ * its name; UnboundSlot uses its digest, which preserves qualification. 
Unordered predicate matching restores
+ * captured values after a failed tentative pairing.
+ */
+public class SPMAstCheckVisitor extends ExpressionVisitor<Boolean, 
SPMAstCheckVisitor.CheckContext> {
+
+    /**
+     * Match context: carries the user-side expression and the placeholder 
value
+     * extraction result.
+     */
+    public static class CheckContext {
+        /** The user-side expression corresponding to the current bind-side 
node. */
+        private final Expression userExpr;
+        /** Placeholder id -> actual value (extraction result). */
+        private final Map<Long, Expression> placeholderValues;
+
+        public CheckContext(Expression userExpr, Map<Long, Expression> 
placeholderValues) {
+            this.userExpr = userExpr;
+            this.placeholderValues = 
PlaceholderBindings.track(placeholderValues);
+        }
+    }
+
+    /**
+     * Match entry point.
+     *
+     * Parameter bindExpr: the bindSql-side expression
+     * Parameter userExpr: the user-query-side expression
+     * Parameter placeholderValues: the placeholder value extraction result 
(filled in here)
+     * Returns: whether the structures match
+     */
+    public boolean checkExpression(Expression bindExpr, Expression userExpr,
+            Map<Long, Expression> placeholderValues) {
+        return bindExpr.accept(this, new CheckContext(userExpr, 
placeholderValues));
+    }
+
+    /** Cheap necessary conditions only; keeps the existing unordered search 
order intact. */
+    public static boolean mayMatch(Expression bind, Expression user) {
+        if (bind instanceof SpmConstVar) {
+            return true;
+        }
+        if (bind instanceof InPredicate ? !(user instanceof InPredicate) : 
bind.getClass() != user.getClass()) {
+            return false;
+        }
+        if (bind instanceof UnboundFunction) {
+            UnboundFunction left = (UnboundFunction) bind;
+            UnboundFunction right = (UnboundFunction) user;
+            if (!left.getName().equalsIgnoreCase(right.getName())
+                    || left.isDistinct() != right.isDistinct()
+                    || !Objects.equals(left.getDbName(), right.getDbName())) {
+                return false;
+            }
+        }
+        if (bind instanceof SlotReference || bind instanceof UnboundSlot) {
+            return sameSlotName(bind, user);
+        }
+        if ((bind instanceof BinaryOperator && !(bind instanceof 
CompoundPredicate)
+                || bind instanceof InPredicate) && !bind.children().isEmpty() 
&& !user.children().isEmpty()) {
+            Expression first = bind.child(0);
+            if (first instanceof SlotReference || first instanceof 
UnboundSlot) {
+                Expression other = user.child(0);
+                return first.getClass() == other.getClass()
+                        && sameSlotName(first, other);
+            }
+        }
+        return true;
+    }
+
+    @Override
+    public Boolean visit(Expression bindExpr, CheckContext context) {
+        Expression userExpr = context.userExpr;
+
+        // placeholder: extract the value (do not compare inner children).
+        if (bindExpr instanceof SpmConstVar) {
+            SpmConstVar placeholder = (SpmConstVar) bindExpr;
+            return recordPlaceholderValue(placeholder.getId(), userExpr, 
context);
+        }
+
+        // Type mismatch -> no match
+        if (bindExpr.getClass() != userExpr.getClass()) {
+            return false;
+        }
+
+        // Identity fields that live OUTSIDE children must be compared 
explicitly:
+        // UnboundStar: the REPLACE payload (a leaf with no children - a 
baseline
+        //   captured with "* REPLACE(k + 1 AS k)" must not replay its captured
+        //   expression for a query using "* REPLACE(k + 2 AS k)")
+        // UnboundFunction: the name / DISTINCT flag / database qualifier 
(abs(k) must not
+        //   match sqrt(k), count(k) must not match count(distinct k), db1.f 
must not
+        //   match db2.f)
+        // WindowExpression: the frame (ROWS 1 PRECEDING must not replay as 2 
PRECEDING;
+        //   WindowFrame is not an expression child, so neither the placeholder
+        //   construction nor the generic child comparison sees its bound 
offsets)
+        if (bindExpr instanceof UnboundStar) {
+            // The REPLACE / EXCEPT payloads are kept OUTSIDE children. 
Compare them
+            // STRUCTURALLY rather than by toSql text: the payload may own a 
SUBQUERY
+            // whose relations are namespace-qualified on the user side while 
the stored
+            // bind tree stays the raw parse (relation NAMES are deliberately 
not part of
+            // Level 3 - the digest pre-filter owns the namespace), so text 
equality
+            // rejected a valid baseline whose own text contains
+            // "* REPLACE((SELECT max(v) FROM u) AS k)" (the namespace rebuild 
qualified
+            // the user's payload to internal.db.u). Everything else stays 
EXACT: the
+            // qualifier, and the payload literals (they are NOT parameterized 
inside a
+            // star, so accepting a value variant would replay the captured 
one).
+            UnboundStar bindStar = (UnboundStar) bindExpr;
+            UnboundStar userStar = (UnboundStar) userExpr;
+            if (!Objects.equals(bindStar.getQualifier(), 
userStar.getQualifier())) {
+                return false;
+            }
+            if (!samePayloadExpressions(bindStar.getExceptedSlots(), 
userStar.getExceptedSlots(),
+                    context)) {
+                return false;
+            }
+            return samePayloadExpressions(bindStar.getReplacedAlias(),
+                    userStar.getReplacedAlias(), context);
+        }
+        if (bindExpr instanceof UnboundFunction) {
+            UnboundFunction bindFunction = (UnboundFunction) bindExpr;
+            UnboundFunction userFunction = (UnboundFunction) userExpr;
+            // the NAME is compared case-insensitively: the digest upper-cases 
it, so a
+            // case-only spelling difference is the SAME function and must stay
+            // matchable; a genuinely different name (or DISTINCT flag) must 
never match,
+            // or the replay would evaluate another function
+            if 
(!bindFunction.getName().equalsIgnoreCase(userFunction.getName())
+                    || bindFunction.isDistinct() != userFunction.isDistinct()
+                    || !Objects.equals(bindFunction.getDbName(), 
userFunction.getDbName())) {
+                return false;
+            }
+        }
+        if (bindExpr instanceof WindowExpression) {
+            WindowFrame bindFrame = ((WindowExpression) 
bindExpr).getWindowFrame().orElse(null);
+            WindowFrame userFrame = ((WindowExpression) 
userExpr).getWindowFrame().orElse(null);
+            if ((bindFrame == null) != (userFrame == null)) {
+                return false;
+            }
+            if (bindFrame != null
+                    && !Objects.equals(bindFrame.computeToSql(), 
userFrame.computeToSql())) {
+                return false;
+            }
+        }
+        // Match: the analyzer (the tokenizer named in "USING ANALYZER...") 
decides how the
+        // pattern is read and is stored outside children; 
BinaryOperator.toDigest
+        // omits it as well. Two MATCH variants with different analyzers must 
not match:
+        // the replay keeps the baseline analyzer and can return different 
matches.
+        if (bindExpr instanceof Match
+                && !Objects.equals(((Match) bindExpr).getAnalyzer(),
+                        ((Match) userExpr).getAnalyzer())) {
+            return false;
+        }
+
+        // A WHERE clause is collected into ONE n-ary AND (OR) node, whose 
operands are an
+        // UNORDERED multiset: the bind side renders placeholders while the 
user side
+        // carries the literal text, so a positional comparison rejects a 
valid baseline
+        // whenever the literal values reverse the textual order. Match the 
operands
+        // transactionally: a tentative pairing rolls its extractions back on 
failure.
+        if (bindExpr instanceof CompoundPredicate) {
+            List<Expression> bindChildren = bindExpr.children();
+            List<Expression> userChildren = userExpr.children();
+            if (bindChildren.size() != userChildren.size()) {
+                return false;
+            }
+            List<Expression> remaining = new ArrayList<>(userChildren);
+            for (Expression bindChild : bindChildren) {
+                int matched = -1;
+                // the operand pairing is an UNORDERED search: a greedy 
pairing can
+                // succeed here and still break a LATER use of the same 
placeholder id
+                // (a filter constraining the same id differently) - the retry 
driver
+                // re-runs the check with a different starting point (see 
MatchAttempt)
+                int offset = MatchAttempt.offset(remaining.size());
+                for (int i = 0; i < remaining.size(); i++) {
+                    int candidate = (offset + i) % remaining.size();
+                    if (!mayMatch(bindChild, remaining.get(candidate))) {
+                        continue;
+                    }
+                    PlaceholderBindings bindings = (PlaceholderBindings) 
context.placeholderValues;
+                    int checkpoint = bindings.checkpoint();
+                    if (checkExpression(bindChild, remaining.get(candidate),
+                            context.placeholderValues)) {
+                        matched = candidate;
+                        break;
+                    }
+                    bindings.rollback(checkpoint);
+                }
+                if (matched < 0) {
+                    return false;
+                }
+                remaining.remove(matched);
+            }
+            return true;
+        }
+
+        // Column references are compared by name (a = 100 must not match b = 
42)
+        if (bindExpr instanceof SlotReference || bindExpr instanceof 
UnboundSlot) {
+            return sameSlotName(bindExpr, userExpr);
+        }
+
+        // An unparameterized bind literal, such as a LIKE escape character or 
a star replacement value, must
+        // equal the user literal. Otherwise replay would retain a captured 
value from a position the builder
+        // intentionally leaves concrete.
+        if (bindExpr instanceof Literal && userExpr instanceof Literal) {
+            return bindExpr.getDataType().equals(userExpr.getDataType()) && 
bindExpr.equals(userExpr);
+        }
+
+        // Child count mismatch -> no match
+        if (bindExpr.children().size() != userExpr.children().size()) {
+            return false;
+        }
+        // Compare children recursively
+        for (int i = 0; i < bindExpr.children().size(); i++) {

Review Comment:
   [P1] Compare lambda parameter mappings during replay matching
   
   Capture the first query, then execute the second with SPM enabled:
   ```sql
   SELECT array_map((a,b,x,`c, d`)->x,array(1),array(2),array(3),array(4)) AS c;
   SELECT array_map((`a, b`,x,c,d)->x,array(1),array(2),array(3),array(4)) AS c;
   ```
   Both parse as `OneRow[ArrayMap(Lambda(body=x), A1,A2,A3,A4) AS c]`, with 
four parameter names stored outside the children. `Lambda.toDigest()` joins 
those names with comma-space, making their digests identical, while this loop 
compares only the equal body `x`. The caller is therefore accepted even though 
`x` binds the third array in the capture and the second in the caller. Raw 
replay reconstructs the captured name vector and returns `[3]` instead of 
`[2]`; decompiler fallback does not protect this path. Compare the ordered 
lambda argument vectors before recursive matching, and cover this direct replay 
case. The existing manual resolved-alias check does not run here.



##########
regression-test/suites/spm/test_spm_review_round2.groovy:
##########
@@ -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.
+
+suite("test_spm_review_round2", "spm") {
+
+    // SQL-level regression for the frozen-SQL / matching fixes.
+    //
+    // Covered here (end-to-end through CREATE BASELINE + EXPLAIN hit + replay 
result):
+    //  - constant UNION branches survive the freeze (a dropped SELECT 1 row)
+    //  - FROM-less projection aliases survive (SELECT 1 AS a keeps its header)
+    //  - SUM(DISTINCT x) restores DISTINCT through the stage fold
+    //  - a different explicit alias / derived-table LIMIT / partition 
selection must
+    //    NOT match (no replay of the captured slice / partition)
+    //  - special-character column identifiers stay quoted (no subtraction at 
replay)
+    //  - case-only join-column collisions stay qualified (frozen SQL stays 
analyzable)
+    //  - LIKE on SHOW BASELINE PLANS has real % / _ wildcard semantics
+    //  - SET-ing an invalid capture regex fails at SET time and never persists
+
+    // SPM regression pins the fallback switch CLOSED: a rewritten-plan 
failure must
+    // surface as an error, never silently re-run the original query.
+    sql """set enable_spm_rewrite = true"""
+    sql """set enable_spm_fallback = false"""
+
+    // ==================== setup: tables (drop before use, keep after) 
====================
+    sql """DROP TABLE IF EXISTS spm_r2_t1"""
+    sql """DROP TABLE IF EXISTS spm_r2_t2"""
+    sql """DROP TABLE IF EXISTS spm_r2_part"""
+    sql """DROP TABLE IF EXISTS spm_r2_special"""
+    sql """DROP TABLE IF EXISTS spm_r2_case1"""
+    sql """DROP TABLE IF EXISTS spm_r2_case2"""
+
+    sql """
+        CREATE TABLE spm_r2_t1 (k1 INT, k2 INT)
+        DUPLICATE KEY(k1)
+        DISTRIBUTED BY HASH(k1) BUCKETS 1
+        PROPERTIES("replication_num" = "1")
+    """
+    // k1 = 1 appears twice so SUM(DISTINCT k1) and SUM(k1) differ
+    sql """INSERT INTO spm_r2_t1 VALUES (1, 10), (1, 10), (2, 20), (3, 30)"""
+    sql """
+        CREATE TABLE spm_r2_t2 (k1 INT, k2 INT)
+        DUPLICATE KEY(k1)
+        DISTRIBUTED BY HASH(k1) BUCKETS 1
+        PROPERTIES("replication_num" = "1")
+    """
+    sql """INSERT INTO spm_r2_t2 VALUES (1, 100), (2, 200)"""
+    sql """
+        CREATE TABLE spm_r2_part (k1 INT)
+        PARTITION BY RANGE(k1)
+        (PARTITION p1 VALUES [("-2147483648"), ("0")), PARTITION p2 VALUES 
[("0"), ("100")))
+        DISTRIBUTED BY HASH(k1) BUCKETS 1
+        PROPERTIES("replication_num" = "1")
+    """
+    sql """INSERT INTO spm_r2_part VALUES (5), (6)"""
+    sql """
+        CREATE TABLE spm_r2_special (`a-b` INT, a INT, b INT, k INT)
+        DUPLICATE KEY(`a-b`)
+        DISTRIBUTED BY HASH(a) BUCKETS 1
+        PROPERTIES("replication_num" = "1")
+    """
+    sql """INSERT INTO spm_r2_special VALUES (100, 1, 2, 5)"""
+    sql """
+        CREATE TABLE spm_r2_case1 (a INT)
+        DUPLICATE KEY(a)
+        DISTRIBUTED BY HASH(a) BUCKETS 1
+        PROPERTIES("replication_num" = "1")
+    """
+    sql """INSERT INTO spm_r2_case1 VALUES (1)"""
+    sql """
+        CREATE TABLE spm_r2_case2 (A INT)
+        DUPLICATE KEY(A)
+        DISTRIBUTED BY HASH(A) BUCKETS 1
+        PROPERTIES("replication_num" = "1")
+    """
+    sql """INSERT INTO spm_r2_case2 VALUES (1)"""
+
+    // ==================== cleanup: drop this suite's leftover baselines 
====================
+    // Global baselines are cluster-wide state: every SHOW / drop is scoped to 
this
+    // suite's tables (spm_r2_), so concurrent SPM suites are never touched.
+    def ownBaselines = {
+        sql("""SHOW BASELINE PLANS""").findAll { 
it[1].toString().contains("spm_r2_") }
+    }
+    def dropOwnBaselines = {
+        ownBaselines().each { row ->
+            sql """DROP BASELINE PLAN ${row[0]}"""
+        }
+    }
+    // The DROP is durable and fenced, but a PARALLEL SPM suite can still 
observe a just-deleted
+    // row through a snapshot read that started before the DROP published (the 
internal table's
+    // delete visibility lags its commit), so retry the cleanup for a bounded 
time instead of
+    // asserting on a single instant: this is a cleanliness guard, not a 
functional assertion.
+    long cleanupDeadline = System.currentTimeMillis() + 10000
+    while (!ownBaselines().isEmpty() && System.currentTimeMillis() < 
cleanupDeadline) {
+        dropOwnBaselines()
+        Thread.sleep(200)
+    }
+    assertEquals(0, ownBaselines().size(), "no spm_r2_ baseline should be left 
after cleanup")
+
+    def explainOf = { String query -> sql("""EXPLAIN ${query}""").toString() }
+    def createBaseline = { String text ->
+        (sql("""CREATE GLOBAL BASELINE PLAN '${text}' WITH '${text}'""")[0][0] 
as Long)
+    }
+
+    // ==================== explicit output alias: preserved / not matched 
(review 13) ====================
+    String aliasSql = "select k1 as x from spm_r2_t1 where k1 = 1"
+    long aliasId = createBaseline(aliasSql)
+    assertTrue(explainOf(aliasSql).contains("SPM baseline hit: id=${aliasId}"),
+            "the same explicit alias must hit the baseline: " + 
explainOf(aliasSql))
+    // the replay keeps the captured result header (SELECT 1 AS x)
+    order_qt_alias_same """select k1 as x from spm_r2_t1 where k1 = 1"""
+
+    String aliasMissSql = "select k1 as y from spm_r2_t1 where k1 = 1"
+    assertFalse(explainOf(aliasMissSql).contains("SPM baseline hit"),
+            "a different explicit alias must not replay the captured header: " 
+ explainOf(aliasMissSql))
+    order_qt_alias_other """select k1 as y from spm_r2_t1 where k1 = 1"""
+
+    // ==================== derived-table LIMIT: not matched (review 2) 
====================
+    String derivedBind = "select * from (select k1 from spm_r2_t1 where k1 < 
100 limit 1) x" +
+            " join spm_r2_t2 on x.k1 = spm_r2_t2.k1"
+    long derivedId = createBaseline(derivedBind)
+    assertTrue(explainOf(derivedBind).contains("SPM baseline hit: 
id=${derivedId}"),
+            "the identical derived-table LIMIT must hit: " + 
explainOf(derivedBind))
+
+    String derivedMiss = "select * from (select k1 from spm_r2_t1 where k1 < 
100 limit 2) x" +
+            " join spm_r2_t2 on x.k1 = spm_r2_t2.k1"
+    assertFalse(explainOf(derivedMiss).contains("SPM baseline hit"),
+            "a different derived-table LIMIT must not replay the captured 
slice: " + explainOf(derivedMiss))
+    // correct result slice: LIMIT 2 (a replayed LIMIT 1 would return a single 
row)
+    order_qt_derived_limit_miss """select x.k1 from (select k1 from spm_r2_t1 
where k1 < 100 limit 2) x
+        join spm_r2_t2 on x.k1 = spm_r2_t2.k1 order by x.k1"""
+
+    // ==================== partition selection: not matched (review 10) 
====================
+    String partBind = "select * from spm_r2_part partition(p2) where k1 = 5"
+    long partId = createBaseline(partBind)
+    assertTrue(explainOf(partBind).contains("SPM baseline hit: id=${partId}"),
+            "the identical partition selection must hit: " + 
explainOf(partBind))
+    order_qt_partition_hit """select * from spm_r2_part partition(p2) where k1 
= 5"""
+
+    String partMiss = "select * from spm_r2_part partition(p1) where k1 = 5"
+    assertFalse(explainOf(partMiss).contains("SPM baseline hit"),
+            "a different partition selection must not replay the captured 
partition: " + explainOf(partMiss))
+    // p1 is empty: a wrongly replayed p2 baseline would return the row 5 here
+    order_qt_partition_miss """select * from spm_r2_part partition(p1) where 
k1 = 5"""
+
+    // ==================== constant UNION branch survives the freeze (review 
1) ====================
+    String unionSql = "select 1 as c union all select k1 as c from spm_r2_t1 
where k1 = 3"
+    long unionId = createBaseline(unionSql)
+    assertTrue(explainOf(unionSql).contains("SPM baseline hit: id=${unionId}"),
+            "the UNION query must hit its baseline: " + explainOf(unionSql))
+    // both rows must come back: a dropped constant branch would return only 
k1 = 3
+    order_qt_union_constant """select c from (select 1 as c union all select 
k1 as c from spm_r2_t1 where k1 = 3) t

Review Comment:
   [P2] Execute the captured SQL in the replay result checks
   
   `unionSql` captures a root UNION, but this result check adds an outer 
projection, derived-table alias and sort. Similarly, `distinctSql` has no ORDER 
BY while `order_qt_distinct_sum` adds one. Both changes produce different 
whole-query digests, so these result statements miss the only corresponding 
baselines and run ordinary planning. The EXPLAIN assertions use the original 
strings and cannot detect wrong replay results; `enable_spm_fallback=false` 
does not detect a miss either. Pass `unionSql` and `distinctSql` directly to 
`order_qt` (which sorts returned rows externally), and verify hits for the 
exact executed SQL.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java:
##########
@@ -4754,22 +4808,98 @@ private LogicalPlan withJoinRelations(LogicalPlan 
input, RelationContext ctx) {
                 joinType = JoinType.CROSS_JOIN;
             }
             Expression matchCondition = null;
+            List<Expression> inlineMarkConjuncts = null;
             if (join.matchCondition() != null) {
-                if (!isAsofJoin) {
+                if (isAsofJoin) {
+                    matchCondition = 
typedVisit(join.matchCondition().valueExpression());
+                    if (!(matchCondition instanceof LessThan
+                            || matchCondition instanceof LessThanEqual
+                            || matchCondition instanceof GreaterThan
+                            || matchCondition instanceof GreaterThanEqual)) {
+                        throw new ParseException("ASOF JOIN's MATCH_CONDITION 
must be <, <=, >, >=", join);
+                    }
+                } else if (isMarkJoin) {
+                    // The grammar's optional matchCondition appears BEFORE 
markJoinSpec*, and
+                    // both productions match the same MATCH_CONDITION ( 
valueExpression )
+                    // text, so the FIRST MARK_CONDITION of a MARK join is 
parsed as
+                    // matchCondition. Route it by the parsed join type: a 
MARK join binds it
+                    // as its mark conjuncts, every other join keeps rejecting 
it.
+                    inlineMarkConjuncts = ExpressionUtils.extractConjunction(
+                            
typedVisit(join.matchCondition().valueExpression()));
+                    for (Expression conjunct : inlineMarkConjuncts) {
+                        if (!(conjunct instanceof EqualTo)) {
+                            throw new ParseException(
+                                    "MARK_CONDITION of a MARK join must be 
equality conjunct(s)", join);
+                        }
+                    }
+                } else {
                     throw new ParseException("only ASOF JOIN support 
MATCH_CONDITION", join);
                 }
-                matchCondition = 
typedVisit(join.matchCondition().valueExpression());
-                if (!(matchCondition instanceof LessThan
-                        || matchCondition instanceof LessThanEqual
-                        || matchCondition instanceof GreaterThan
-                        || matchCondition instanceof GreaterThanEqual)) {
-                    throw new ParseException("ASOF JOIN's MATCH_CONDITION must 
be <, <=, >, >=", join);
-                }
             } else {
                 if (isAsofJoin) {
                     throw new ParseException("ASOF JOIN must specify 
MATCH_CONDITION", join);
                 }
             }
+
+            // MARK join specifiers: MARK_CONDITION(<equality conjuncts>, 
optional)
+            // and MARK_SLOT <name>. MARK_SLOT names the referenceable 
three-valued mark
+            // output column; MARK_CONDITION (when present) must be equality 
conjuncts.
+            // A MARK join is a LEFT/RIGHT SEMI/ANTI join, or a CROSS join (a 
mark slot
+            // with no hash/other/mark conjunct at all - the folded 
uncorrelated
+            // EXISTS / NOT EXISTS boolean output; CROSS MARK JOIN ... 
MARK_SLOT <name>).
+            if (isMarkJoin && !(joinType == JoinType.LEFT_SEMI_JOIN
+                    || joinType == JoinType.RIGHT_SEMI_JOIN
+                    || joinType == JoinType.LEFT_ANTI_JOIN
+                    || joinType == JoinType.RIGHT_ANTI_JOIN

Review Comment:
   [P2] Normalize unsupported RIGHT ANTI MARK joins before dispatch
   
   The newly accepted form fails for ordinary supported settings:
   ```sql
   SET disable_join_reorder=true;
   SELECT r.k,m FROM l RIGHT ANTI MARK JOIN r MARK_SLOT m ON l.k=r.k;
   ```
   This produces `Project(r.k,m) -> RightAntiMark(l.k=r.k) -> Scan(l), 
Scan(r)`. `ConvertRightJoinToLeftJoin` skips normalization when reordering is 
disabled, and CBO commutation is disabled too. Hash implementation and 
shuffle-property derivation accept the tree, so translation sends 
RIGHT_ANTI_JOIN with `is_mark=true`; `HashJoinBuildSinkOperatorX::init` then 
unconditionally returns “Hash join does not support right anti mark join.” An 
explicit distribution hint also prevents normalization. Make this required 
normalization independent of optional join reordering, or reject the 
unsupported form during analysis, and test with reordering disabled.



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