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


##########
fe/fe-core/src/main/java/org/apache/doris/cloud/rpc/MetaServiceRpcRateLimiter.java:
##########
@@ -113,6 +118,10 @@ long acquire(String methodName, int permits) throws 
RpcException {
                     holder.burstSeconds,
                     waitMs);
         }
+        if (deadlineMillis != Long.MAX_VALUE
+                && nanosToWait >= 
TimeUnit.MILLISECONDS.toNanos(VersionHelper.remainingMillis(deadlineMillis))) {
+            throw new VersionHelper.VersionReadTimeoutException();

Review Comment:
   [P2] Avoid consuming RPC quota for deadline-rejected reads
   
   With `meta_service_rpc_rate_limit_dry_run=false`, a queued version RPC can 
require a 500ms wait while a cold SPM read has only 50ms remaining. 
`reservePermission` has already deducted its future permits before this new 
check throws; [the pinned AtomicRateLimiter 2.4.0 
implementation](https://github.com/resilience4j/resilience4j/blob/v2.4.0/resilience4j-ratelimiter/src/main/java/io/github/resilience4j/ratelimiter/internal/AtomicRateLimiter.java#L127-L143)
 commits reservations according to the configured limiter timeout, without this 
shorter caller deadline. No RPC is dispatched and the reservation is never 
returned. Repeated abandoned SPM reads can consume the next period's allowance 
and delay/reject ordinary partition-version RPCs sharing the same per-method 
limiter. Use deadline-aware admission that does not commit unusable 
reservations, or safely release them on this rejection; cover ordinary 
acquisition after a timed rejection.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/spm/SPMPlanTreeSupport.java:
##########
@@ -0,0 +1,9492 @@
+// 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;
+
+import org.apache.doris.analysis.TableScanParams;
+import org.apache.doris.catalog.Column;
+import org.apache.doris.catalog.OlapTable;
+import org.apache.doris.catalog.OlapTableWrapper;
+import org.apache.doris.catalog.TableIf;
+import org.apache.doris.catalog.View;
+import org.apache.doris.common.util.Util;
+import org.apache.doris.datasource.doris.RemoteOlapTable;
+import org.apache.doris.nereids.analyzer.UnboundAlias;
+import org.apache.doris.nereids.analyzer.UnboundFunction;
+import org.apache.doris.nereids.analyzer.UnboundInlineTable;
+import org.apache.doris.nereids.analyzer.UnboundOneRowRelation;
+import org.apache.doris.nereids.analyzer.UnboundRelation;
+import org.apache.doris.nereids.analyzer.UnboundSlot;
+import org.apache.doris.nereids.analyzer.UnboundStar;
+import org.apache.doris.nereids.analyzer.UnboundTVFRelation;
+import org.apache.doris.nereids.analyzer.UnboundVariable;
+import org.apache.doris.nereids.properties.OrderKey;
+import org.apache.doris.nereids.properties.SelectHint;
+import org.apache.doris.nereids.properties.SelectHintLeading;
+import org.apache.doris.nereids.properties.SelectHintSetVar;
+import org.apache.doris.nereids.properties.SelectHintUseMv;
+import org.apache.doris.nereids.rules.exploration.join.JoinReorderContext;
+import org.apache.doris.nereids.rules.expression.check.CheckCast;
+import org.apache.doris.nereids.spm.matcher.MatchAttempt;
+import org.apache.doris.nereids.spm.matcher.PlaceholderBindings;
+import org.apache.doris.nereids.spm.matcher.SPMAstCheckVisitor;
+import org.apache.doris.nereids.spm.matcher.SPMFrozenTreeReplacer;
+import org.apache.doris.nereids.spm.placeholder.SpmConstList;
+import org.apache.doris.nereids.spm.placeholder.SpmConstVar;
+import org.apache.doris.nereids.trees.TableSample;
+import org.apache.doris.nereids.trees.expressions.Alias;
+import org.apache.doris.nereids.trees.expressions.And;
+import org.apache.doris.nereids.trees.expressions.BinaryArithmetic;
+import org.apache.doris.nereids.trees.expressions.Cast;
+import org.apache.doris.nereids.trees.expressions.Exists;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.InSubquery;
+import org.apache.doris.nereids.trees.expressions.MarkJoinSlotReference;
+import org.apache.doris.nereids.trees.expressions.NamedExpression;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import org.apache.doris.nereids.trees.expressions.SubqueryExpr;
+import org.apache.doris.nereids.trees.expressions.Variable;
+import 
org.apache.doris.nereids.trees.expressions.functions.ComputePrecisionForArrayItemAgg;
+import org.apache.doris.nereids.trees.expressions.functions.Function;
+import org.apache.doris.nereids.trees.expressions.functions.generator.Unnest;
+import 
org.apache.doris.nereids.trees.expressions.functions.scalar.EncryptKeyRef;
+import org.apache.doris.nereids.trees.expressions.literal.IntegerLikeLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.Literal;
+import org.apache.doris.nereids.trees.expressions.literal.StringLiteral;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.algebra.InlineTable;
+import org.apache.doris.nereids.trees.plans.algebra.OneRowRelation;
+import org.apache.doris.nereids.trees.plans.logical.LogicalAggregate;
+import org.apache.doris.nereids.trees.plans.logical.LogicalCTE;
+import org.apache.doris.nereids.trees.plans.logical.LogicalCatalogRelation;
+import org.apache.doris.nereids.trees.plans.logical.LogicalCheckPolicy;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFileSink;
+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.LogicalHaving;
+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.LogicalPlan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalProject;
+import org.apache.doris.nereids.trees.plans.logical.LogicalQualify;
+import org.apache.doris.nereids.trees.plans.logical.LogicalRepeat;
+import org.apache.doris.nereids.trees.plans.logical.LogicalSelectHint;
+import org.apache.doris.nereids.trees.plans.logical.LogicalSetOperation;
+import org.apache.doris.nereids.trees.plans.logical.LogicalSink;
+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.LogicalTopN;
+import org.apache.doris.nereids.trees.plans.logical.LogicalUsingJoin;
+import org.apache.doris.nereids.trees.plans.logical.LogicalView;
+import org.apache.doris.nereids.trees.plans.logical.LogicalWindow;
+import org.apache.doris.nereids.trees.plans.visitor.PlanVisitor;
+import org.apache.doris.nereids.types.ArrayType;
+import org.apache.doris.nereids.types.DataType;
+import org.apache.doris.nereids.types.TimeStampTzType;
+import org.apache.doris.nereids.util.RelationUtil;
+import org.apache.doris.qe.ConnectContext;
+import org.apache.doris.qe.GlobalVariable;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.IdentityHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.function.Predicate;
+
+/**
+ * Shared SPM traversal, matching, metadata and replay-contract helpers. The 
expression transform handles supported
+ * plan expression positions and preserves query-block and projection scopes. 
CTE bodies are visited explicitly,
+ * and expression visitors recurse into expression-owned subquery plans.
+ *
+ * Structural matching collects marker replacements after the hash and 
canonical digest filters. Replay helpers
+ * qualify namespaces, restore labels and limits, preserve caller hints, and 
validate table and function metadata.
+ * Marker scans distinguish internal marker nodes from parsed frozen-SQL calls.
+ */
+public final class SPMPlanTreeSupport {
+
+    /**
+     * Marker of the per-table NULLABILITY section inside one fingerprint 
entry (see
+     * describeTableForFingerprint). An entry persisted before the section
+     * existed simply lacks it and is still accepted (legacyEntryOf), so the
+     * section can be introduced without invalidating already persisted 
baselines.
+     */
+    private static final String NULLABILITY_SECTION = "nullable:";
+
+    /**
+     * The marker appended by expandedOutputLabels behind the derivable prefix 
of
+     * a PARTLY derivable star expansion (see the star-expansion helper 
returned by
+     * alignRootOutputLabels). Kept in the constants block: a static field may
+     * not sit between methods (checkstyle DeclarationOrder).
+     */
+    private static final String OPEN_TAIL_LABEL = "\u0000spm-open-star-tail";
+
+    /** Expression transform used by transform. */
+    public interface ExprTransform {
+        Expression apply(Expression expr);
+
+        /**
+         * Called while the rebuild ENTERS a nested query block (a derived 
table / CTE body /
+         * subquery alias), with exitQueryBlock in a finally block. The 
placeholder
+         * builder gives every block its own identity so two literals of 
DIFFERENT blocks can
+         * never share one placeholder id: block 0 was previously shared by 
the outer query
+         * and every derived table, so equal filter literals there (e.g. an 
outer
+         * x = 1 and a derived-table x = 1 whose parent signatures coincide)
+         * merged into one id and a variant changing only one of the values 
could never
+         * match.
+         */
+        default void enterQueryBlock() {
+        }
+
+        /** Matching exit of enterQueryBlock. */
+        default void exitQueryBlock() {
+        }
+
+        /**
+         * Called while the rebuild enters ONE projection item (SELECT-list 
slot) of a
+         * projection-like list, with exitProjectionItem in a finally block. 
The
+         * item POSITION is part of a literal's placeholder identity: the 
literals of
+         * SELECT 1 AS x, 1 AS y have the same value, the same child position 
inside
+         * their Alias and (before the position existed) the same parent 
signature, so they
+         * shared one placeholder and a variant with different values per 
column could never
+         * match.
+         */
+        default void enterProjectionItem(int index) {
+        }
+
+        /** Matching exit of enterProjectionItem(int). */
+        default void exitProjectionItem() {
+        }
+
+        /** Supplies the GROUP BY expression lookup for the current clause 
window. */
+        default void 
setGroupByMirrorLookup(java.util.function.Function<String, Expression> lookup) {
+        }
+
+        /** Records a parameterized grouping expression that must survive as a 
frozen grouping column. */
+        default void noteParameterizedGroupingTarget(Expression target) {
+        }
+    }
+
+    /**
+     * An ExprTransform that also changes what its children see while the tree 
is rebuilt.
+     * Only namespace qualification is scope-sensitive: the set of CTE aliases 
visible in
+     * the query text grows when the rebuild enters a CTE body or a CTE's main 
query, so
+     * those two entry points receive a different transform than the 
surrounding tree.
+     * Plain transforms (parameterize / substitute) are not scope-aware and 
are passed
+     * through unchanged.
+     */
+    private interface ScopedTransform extends ExprTransform {
+        /** The transform to use for the main query of a CTE (sees every alias 
of it). */
+        ExprTransform enterCteMain(LogicalCTE<? extends Plan> cte);
+
+        /** The transform to use for the body of alias #aliasIndex (sees the 
earlier ones). */
+        ExprTransform enterCteAlias(LogicalCTE<? extends Plan> cte, int 
aliasIndex);
+    }
+
+    /** Re-descends into expression subquery plans so their hints are stripped 
as well. */
+    private static final ExprTransform SET_VAR_HINT_STRIP_EXPR = 
SPMPlanTreeSupport::stripSetVarHintsInExpression;
+
+    /**
+     * Expression transform of stripCheckPolicy: strips the policy markers from
+     * every plan an expression owns (IN / EXISTS / scalar subquery plans, the 
payloads of
+     * a * REPLACE(...), the ASOF MATCH_CONDITION).
+     */
+    private static final ExprTransform STRIP_POLICY_IN_EXPRESSION =
+            SPMPlanTreeSupport::stripPolicyOfExpression;
+
+    /** Derived contracts for one fixed tree version, confined to a rewrite 
attempt. */
+    static final class ReplayContracts {
+        private final Plan plan;
+        private boolean topComputed;
+        private long[] top;
+        private Map<String, Integer> caps;
+        private List<String> order;
+        private List<String> sortShape;
+
+        ReplayContracts(Plan plan) {
+            this.plan = plan;
+        }
+
+        long[] topLimit() {
+            if (!topComputed) {
+                top = topLevelLimitOf(plan);
+                topComputed = true;
+            }
+            return top;
+        }
+
+        Map<String, Integer> caps() {
+            if (caps == null) {
+                Map<String, Integer> collected = new HashMap<>();
+                collectRowLimits(plan, collected);
+                caps = Collections.unmodifiableMap(collected);
+            }
+            return caps;
+        }
+
+        List<String> order() {
+            if (order == null) {
+                order = Collections.unmodifiableList(rootOrderContract(plan));
+            }
+            return order;
+        }
+
+        List<String> sortShape() {
+            // L3 matching and CREATE checks own expression identity; frozen 
aliases can change key spelling.
+            if (sortShape == null) {
+                List<String> shape = new ArrayList<>();
+                for (String entry : order()) {
+                    int colon = entry.indexOf(':');
+                    shape.add(colon < 0 ? entry : entry.substring(0, colon));
+                }
+                sortShape = Collections.unmodifiableList(shape);
+            }
+            return sortShape;
+        }
+    }
+
+    private SPMPlanTreeSupport() {
+    }
+
+    /**
+     * Strips the SET_VAR hints of every plan one expression owns, recursing 
through the
+     * expression tree.
+     *
+     * The recursion is what makes the peel reach a subquery NESTED inside an 
item: a
+     * projection item is an UnboundAlias (or an arithmetic / function call 
around one),
+     * so testing only the expression handed to the transform left a scalar 
subquery carrying a
+     * SET_VAR hint inside it untouched - and the replayed analysis then 
applied the CREATOR's
+     * session variable to a caller that carried no hint at all.
+     *
+     * Parameter expression: the expression to peel
+     * Returns: the expression with every owned subquery plan stripped
+     */
+    private static Expression stripSetVarHintsInExpression(Expression 
expression) {
+        Expression result = expression;
+        if (expression instanceof SubqueryExpr) {
+            LogicalPlan subPlan = ((SubqueryExpr) expression).getQueryPlan();
+            LogicalPlan stripped = stripSetVarHints(subPlan);
+            if (stripped != null && stripped != subPlan) {
+                result = ((SubqueryExpr) expression).withSubquery(stripped);
+            }
+        }
+        if (result instanceof UnboundStar) {
+            // The REPLACE payloads live OUTSIDE children, so a subquery (with 
its own
+            // SET_VAR hint) behind one is reached only from here - the same 
payload omission
+            // the function-identity collector had.
+            UnboundStar star = (UnboundStar) result;
+            List<NamedExpression> replaced = star.getReplacedAlias();
+            if (!replaced.isEmpty()) {
+                List<NamedExpression> newReplaced = new 
ArrayList<>(replaced.size());
+                boolean payloadChanged = false;
+                for (NamedExpression payload : replaced) {
+                    Expression newPayload = 
stripSetVarHintsInExpression(payload);
+                    newReplaced.add(newPayload instanceof NamedExpression
+                            ? (NamedExpression) newPayload : payload);
+                    payloadChanged |= newPayload != payload;
+                }
+                if (payloadChanged) {
+                    result = new UnboundStar(star.getQualifier(), 
star.getExceptedSlots(),
+                            newReplaced, star.getIndexInSqlString());
+                }
+            }
+        }
+        List<Expression> children = result.children();
+        if (children.isEmpty()) {
+            return result;
+        }
+        List<Expression> newChildren = new ArrayList<>(children.size());
+        boolean changed = false;
+        for (Expression child : children) {
+            Expression newChild = stripSetVarHintsInExpression(child);
+            newChildren.add(newChild);
+            changed |= newChild != child;
+        }
+        return changed ? result.withChildren(newChildren) : result;
+    }
+
+    /**
+     * The top-level LIMIT / OFFSET a query tree exposes to its CALLER ({limit,
+     * offset}) or null when it has none. The descent follows the wrapper 
chain (result
+     * sink, sort,...) and STOPS at a projection: a limit BELOW a projection 
is not the
+     * caller-visible top-level limit - and mergeLimitNode cannot transfer the
+     * caller's values there either, which is exactly the situation the replay 
guard in
+     * SPMPlanner checks with this helper.
+     */
+    public static long[] topLevelLimitOf(Plan plan) {
+        Plan node = plan;
+        while (node != null && !(node instanceof LogicalLimit) && !(node 
instanceof LogicalTopN)
+                && !(node instanceof LogicalProject) && node.children().size() 
== 1) {
+            node = node.child(0);
+        }
+        if (node instanceof LogicalLimit) {
+            return new long[] {((LogicalLimit<?>) node).getLimit(),
+                    ((LogicalLimit<?>) node).getOffset()};
+        }
+        if (node instanceof LogicalTopN) {
+            return new long[] {((LogicalTopN<?>) node).getLimit(),
+                    ((LogicalTopN<?>) node).getOffset()};
+        }
+        return null;
+    }
+
+    static boolean rowLimitsWithin(ReplayContracts replayed, ReplayContracts 
userPlan) {
+        Map<String, Integer> allowed = userPlan.caps();
+        Map<String, Integer> used = replayed.caps();
+        return containsEveryCap(allowed, used);
+    }
+
+    static boolean rowLimitsEquivalentModuloOccurrence(ReplayContracts left, 
ReplayContracts right) {
+        if (!Arrays.equals(left.topLimit(), right.topLimit())) {
+            return false;
+        }
+        Map<String, Integer> leftCaps = left.caps();
+        Map<String, Integer> rightCaps = right.caps();
+        return ordinalFreeCaps(leftCaps).equals(ordinalFreeCaps(rightCaps));
+    }
+
+    /** The same cap multiset keyed without the per-name occurrence ordinals. 
*/
+    private static Map<String, Integer> ordinalFreeCaps(Map<String, Integer> 
caps) {
+        Map<String, Integer> stripped = new HashMap<>();
+        for (Map.Entry<String, Integer> entry : caps.entrySet()) {
+            stripped.merge(stripOccurrenceOrdinals(entry.getKey()), 
entry.getValue(), Integer::sum);
+        }
+        return stripped;
+    }
+
+    static boolean rowLimitsSurviveReplay(ReplayContracts replayed, 
ReplayContracts userPlan) {
+        Map<String, Integer> required = userPlan.caps();
+        Map<String, Integer> exposed = replayed.caps();
+        return containsEveryCap(exposed, required);
+    }
+
+    /**
+     * Whether every cap of used is available in available with at least the 
same
+     * multiplicity (the multiset containment both cap checks are built on).
+     *
+     * Parameter available: the caps the other side carries
+     * Parameter used: the caps that must be justified
+     * Returns: whether used is contained in available
+     */
+    private static boolean containsEveryCap(Map<String, Integer> available,
+            Map<String, Integer> used) {
+        for (Map.Entry<String, Integer> entry : used.entrySet()) {
+            Integer count = available.get(entry.getKey());
+            if (count == null || count < entry.getValue()) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    static boolean topCapContractPreserved(ReplayContracts replayed, 
ReplayContracts userPlan) {
+        long[] top = userPlan.topLimit();
+        if (top == null || !Arrays.equals(top, replayed.topLimit())) {
+            return false;
+        }
+        Map<String, Integer> userCaps = new HashMap<>(userPlan.caps());
+        Map<String, Integer> replayCaps = new HashMap<>(replayed.caps());
+        String prefix = top[0] + ":" + top[1] + ":";
+        String userTopKey = singleTopCapKey(userCaps, prefix);
+        String replayTopKey = singleTopCapKey(replayCaps, prefix);
+        if (userTopKey == null || replayTopKey == null) {
+            // more than one cap shares the top (limit, offset): keep the 
strict checks
+            return false;
+        }
+        if 
(!stripOccurrenceOrdinals(userTopKey).equals(stripOccurrenceOrdinals(replayTopKey)))
 {
+            return false;
+        }
+        consumeOne(userCaps, userTopKey);
+        consumeOne(replayCaps, replayTopKey);
+        for (Map.Entry<String, Integer> entry : replayCaps.entrySet()) {
+            Integer available = userCaps.get(entry.getKey());
+            if (available == null || available < entry.getValue()) {
+                return false;
+            }
+        }
+        for (Map.Entry<String, Integer> entry : userCaps.entrySet()) {
+            Integer present = replayCaps.get(entry.getKey());
+            if (present == null || present < entry.getValue()) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    /** The single cap key of the given (limit, offset) prefix, or null when 
ambiguous. */
+    private static String singleTopCapKey(Map<String, Integer> caps, String 
prefix) {
+        String found = null;
+        for (Map.Entry<String, Integer> entry : caps.entrySet()) {
+            if (entry.getKey().startsWith(prefix)) {
+                if (found != null) {
+                    return null;
+                }
+                found = entry.getKey();
+            }
+        }
+        return found;
+    }
+
+    static boolean onlyTopCap(ReplayContracts plan) {
+        long[] top = plan.topLimit();
+        if (top == null) {
+            return false;
+        }
+        Map<String, Integer> caps = plan.caps();
+        return caps.size() == 1
+                && caps.keySet().iterator().next().startsWith(top[0] + ":" + 
top[1] + ":");
+    }
+
+    /** Consumes one instance of the key's multiplicity (multiset 
bookkeeping). */
+    private static void consumeOne(Map<String, Integer> caps, String key) {
+        Integer count = caps.get(key);
+        if (count == null) {
+            return;
+        }
+        if (count <= 1) {
+            caps.remove(key);
+        } else {
+            caps.put(key, count - 1);
+        }
+    }
+
+    /**
+     * One cap key with the per-name occurrence ordinals dropped from its 
input section:
+     * "limit:offset:slice:name#N,name#M" becomes 
"limit:offset:slice:name1,name2"
+     * (sorted names, duplicates collapsed). The head - the limit, the offset 
and the
+     * ordered-slice fingerprint (order-key count and directions) - stays 
comparable.
+     */
+    private static String stripOccurrenceOrdinals(String capKey) {
+        int first = capKey.indexOf(':');
+        int second = first < 0 ? -1 : capKey.indexOf(':', first + 1);
+        int third = second < 0 ? -1 : capKey.indexOf(':', second + 1);
+        if (third < 0) {
+            return capKey;
+        }
+        TreeSet<String> names = new TreeSet<>();
+        String inputs = capKey.substring(third + 1);
+        for (String input : inputs.split(",")) {
+            if (input.isEmpty()) {
+                continue;
+            }
+            int hash = input.lastIndexOf('#');
+            names.add(hash < 0 ? input : input.substring(0, hash));
+        }
+        return capKey.substring(0, third + 1) + String.join(",", names);
+    }
+
+    static boolean replayCapsJustifiedByCallerTopLimit(ReplayContracts 
replayed, ReplayContracts userPlan) {
+        long[] top = userPlan.topLimit();
+        if (top == null) {
+            return false;
+        }
+        boolean ordered = !userPlan.order().isEmpty();
+        // With a caller ORDER BY the folded cap must not cut a different 
slice. That is
+        // guaranteed when the replay still exposes the caller's own TOP-LEVEL 
ordering
+        // AND the folded caps sit on the BRANCHES of a set operation: the 
merge of the
+        // per-branch orders selects the caller's slice among each branch's 
own top rows
+        // (tpcds q49's union branches carry one 100 cap each), while a cap on 
the input
+        // of an ordinary sort would truncate before the ordering exists.
+        if (ordered && !orderContractPreserved(replayed, userPlan)) {
+            return false;
+        }
+        Map<String, Integer> allowed = userPlan.caps();
+        Map<String, Integer> used = replayed.caps();
+        String prefix = top[0] + ":" + top[1] + ":";
+        Set<String> topScope = null;
+        List<Set<String>> extraScopes = new ArrayList<>();
+        if (ordered) {
+            // the first set operation below the order/limit wrappers: the 
class-exact
+            // helper cannot be used here (the concrete Union / Intersect / 
Except class is
+            // what the caller-side comparison keys on), so descend on the 
base interface
+            Plan probe = replayed.plan;
+            while (probe != null && !(probe instanceof LogicalSetOperation)
+                    && probe.children().size() == 1) {
+                probe = probe.child(0);
+            }
+            if (!(probe instanceof LogicalSetOperation)) {
+                return false;
+            }
+            topScope = topCapScopeOf(allowed, prefix);
+        }
+        for (Map.Entry<String, Integer> entry : used.entrySet()) {
+            if (allowed.containsKey(entry.getKey())) {
+                continue;
+            }
+            if (!entry.getKey().startsWith(prefix)) {
+                return false;
+            }
+            if (ordered) {
+                Set<String> scope = capKeyRelations(entry.getKey());
+                if (topScope == null || !topScope.containsAll(scope)) {
+                    return false;
+                }
+                extraScopes.add(scope);
+            }
+        }
+        if (ordered) {
+            // one cap per branch: overlapping branch scopes would let two 
folded caps
+            // truncate the same input
+            for (int i = 0; i < extraScopes.size(); i++) {
+                for (int j = i + 1; j < extraScopes.size(); j++) {
+                    for (String relation : extraScopes.get(i)) {
+                        if (extraScopes.get(j).contains(relation)) {
+                            return false;
+                        }
+                    }
+                }
+            }
+        }
+        return true;
+    }
+
+    /** The relation set of the WIDEST caller cap carrying the given (limit, 
offset) prefix. */
+    private static Set<String> topCapScopeOf(Map<String, Integer> allowed, 
String prefix) {
+        Set<String> widest = null;
+        for (String key : allowed.keySet()) {
+            if (key.startsWith(prefix)) {
+                Set<String> relations = capKeyRelations(key);
+                if (widest == null || relations.size() > widest.size()) {
+                    widest = relations;
+                }
+            }
+        }
+        return widest;
+    }
+
+    /** The relation names of one cap key ("limit:offset:slice:r1,r2,..."). */
+    private static Set<String> capKeyRelations(String key) {
+        int first = key.indexOf(':');
+        int second = first < 0 ? -1 : key.indexOf(':', first + 1);
+        int third = second < 0 ? -1 : key.indexOf(':', second + 1);
+        if (third < 0 || third + 1 >= key.length()) {
+            return Set.of();
+        }
+        return new HashSet<>(Arrays.asList(key.substring(third + 
1).split(",")));
+    }
+
+    /**
+     * Collects every row-limiting node of the tree as (limit, offset, INPUT 
IDENTITIES):
+     * the (limit, offset) pair ALONE is not enough - a cap of the same value 
can sit on a
+     * different input than the caller's own cap of that value, and the 
positional merge
+     * leaves it there (a manual plan capped t2 while the caller's own cap
+     * sat on t1; with one matching t1 row and two matching t2 rows the 
variant returned
+     * ONE row where the caller's own plan returns two). The key therefore 
includes every
+     * relation beneath the cap, so a replayed cap only counts as one the 
caller also has
+     * when it truncates the same input.
+     *
+     * The input identities alone are not enough either when the SAME table 
occurs more
+     * than once: a manual plan can move ORDER BY k LIMIT 1 from the first 
table
+     * instance to a second instance of the SAME table, and a caller raising 
only the
+     * outer LIMIT from 1 to 2 then compared 1:0:t against 1:0:t and
+     * accepted the replay - although t={1,2} yields (1,1),(2,1) instead of 
(1,1),(1,2)
+     * . Each input therefore carries its OCCURRENCE ORDINAL among the
+     * relations of the same name, assigned in walk order: a cap moved to 
another
+     * occurrence of the same input gets a different key and the variant is 
skipped (its
+     * placement cannot be proven equivalent), which is always safe - the 
caller's own
+     * query then simply plans normally. The ordinal (rather than the alias 
name) is what
+     * keeps an IDENTICAL-text baseline matchable: its frozen text is the 
DECOMPILED plan,
+     * whose derived aliases are regenerated, while the relative order of the 
relation
+     * occurrences is preserved.
+     *
+     * The walk covers the plans OUTSIDE children as well - CTE bodies
+     * (LogicalCTE.extraPlans) and expression-owned subquery plans (IN / 
EXISTS / scalar,
+     * plus * REPLACE payloads) - a cap inside a WITH body was invisible to a
+     * children-only walk, and the caller raising only the OUTER limit kept 
the frozen body
+     * cap for the variant. The identity set keeps a plan reachable through
+     * two paths (a filter's extraPlans and its predicate expression) from 
counting the
+     * same cap twice.
+     */
+    private static void collectRowLimits(Plan plan, Map<String, Integer> out) {
+        // pass 1: assign every relation its per-name occurrence ordinal in 
walk order;
+        // pass 2: collect the caps with those ordinals (the two walks are the 
same
+        // pre-order traversal - children, extraPlans, expressions - so an 
ordinal is
+        // identical on both sides whenever the two trees render the 
occurrences in the
+        // same relative order)
+        IdentityHashMap<Plan, Integer> relationOrdinals = new 
IdentityHashMap<>();
+        // CTE references are named DIFFERENTLY on the two sides of a 
legitimate replay:
+        // the frozen planSql is the DECOMPILED plan and the decompiler 
regenerates
+        // every WITH alias (the caller's ws_wh becomes t_4), so a CTE 
reference is
+        // identified by its CTE's DEFINITION ORDER index instead of the alias 
- the
+        // same trick the occurrence ordinal plays for table aliases (see
+        // SPMPlanTreeSupport.relationNameOf).
+        CteOrder cteOrder = cteDefinitionOrder(plan);
+        assignRelationOrdinals(plan, new HashMap<>(), relationOrdinals, 
cteOrder,
+                Collections.newSetFromMap(new IdentityHashMap<>()));
+        collectRowLimits(plan, out, relationOrdinals, cteOrder,
+                Collections.newSetFromMap(new IdentityHashMap<>()),
+                new RelationInputIndex(relationOrdinals, cteOrder));
+    }
+
+    private static void collectRowLimits(Plan plan, Map<String, Integer> out,
+            IdentityHashMap<Plan, Integer> relationOrdinals,
+            CteOrder cteOrder, Set<Plan> visited, RelationInputIndex 
inputIndex) {
+        if (plan == null || !visited.add(plan)) {
+            return;
+        }
+        if (plan instanceof LogicalLimit) {
+            out.merge(rowLimitKey(((LogicalLimit<?>) plan).getLimit(),
+                    ((LogicalLimit<?>) plan).getOffset(), plan, inputIndex),
+                    1, Integer::sum);
+        } else if (plan instanceof LogicalTopN) {
+            out.merge(rowLimitKey(((LogicalTopN<?>) plan).getLimit(),
+                    ((LogicalTopN<?>) plan).getOffset(), plan, inputIndex),
+                    1, Integer::sum);
+        }
+        for (Plan child : plan.children()) {
+            collectRowLimits(child, out, relationOrdinals, cteOrder, visited, 
inputIndex);
+        }
+        for (Plan extra : plan.extraPlans()) {
+            collectRowLimits(extra, out, relationOrdinals, cteOrder, visited, 
inputIndex);
+        }
+        for (Expression expression : plan.getExpressions()) {
+            collectRowLimits(expression, out, relationOrdinals, cteOrder, 
visited, inputIndex);
+        }
+    }
+
+    /** Recurses one expression tree looking for subquery plans (see 
walkSubqueryPlans). */
+    private static void collectRowLimits(Expression expression, Map<String, 
Integer> out,
+            IdentityHashMap<Plan, Integer> relationOrdinals,
+            CteOrder cteOrder, Set<Plan> visited, RelationInputIndex 
inputIndex) {
+        if (expression instanceof SubqueryExpr) {
+            collectRowLimits(((SubqueryExpr) expression).getQueryPlan(), out,
+                    relationOrdinals, cteOrder, visited, inputIndex);
+        }
+        if (expression instanceof UnboundStar) {
+            for (NamedExpression replaced : ((UnboundStar) 
expression).getReplacedAlias()) {
+                collectRowLimits(replaced, out, relationOrdinals, cteOrder, 
visited, inputIndex);
+            }
+        }
+        for (Expression child : expression.children()) {
+            collectRowLimits(child, out, relationOrdinals, cteOrder, visited, 
inputIndex);
+        }
+    }
+
+    /**
+     * CTE declaration indices used by row-limit keys. The reference map 
records the binding visible at each node,
+     * including shadowed aliases. The name map keeps the first declaration of 
each normalized name as a fallback
+     * for references absent from the scoped map.
+     */
+    private static final class CteOrder {
+        /** Normalized alias -> definition-order index (the FIRST definition 
of a name). */
+        private final Map<String, Integer> definitionOrder = new HashMap<>();
+        /** Reference node -> the index of the binding visible at it 
(shadowing resolved). */
+        private final IdentityHashMap<Plan, Integer> referenceIndex = new 
IdentityHashMap<>();
+
+        /**
+         * The identity of one CTE reference.
+         *
+         * Parameter reference: the referencing node
+         * Parameter written: the name the statement wrote
+         * Returns: the definition-order index, or null when the name is not a 
CTE
+         */
+        Integer indexOf(Plan reference, String written) {
+            Integer scoped = referenceIndex.get(reference);
+            return scoped != null ? scoped : 
definitionOrder.get(normalizeCteName(written));
+        }
+    }
+
+    /**
+     * Assigns every CTE of the tree (normalized, see normalizeCteName) its
+     * definition-order index AND resolves every reference to the binding 
visible at it.
+     * The two sides of one replay - the caller's raw tree and the parsed 
frozen planSql -
+     * spell the same CTE with different aliases (the decompiler regenerates 
every
+     * derived alias), but the WITH structure and its order are preserved, so 
the
+     * INDEX is the name-independent identity the row-limit keys compare. 
Distinct
+     * CTEs keep distinct indices, so a cap moved between two CTEs still 
changes its
+     * key.
+     *
+     * The walk mirrors walkPlansScoped's scoping rules, carrying the name -> 
index map
+     * instead of the visible-name set so a SHADOWED definition resolves to 
the innermost
+     * binding.
+     *
+     * Parameter root: the parsed (unbound) tree
+     * Returns: the identity maps
+     */
+    private static CteOrder cteDefinitionOrder(Plan root) {
+        CteOrder order = new CteOrder();
+        int[] next = {0};
+        assignCteOrder(root, new HashMap<>(), order, next,
+                Collections.newSetFromMap(new IdentityHashMap<>()));
+        return order;
+    }
+
+    /**
+     * One scoped step of cteDefinitionOrder.
+     *
+     * Parameter root: the node to visit (may be null)
+     * Parameter visible: the name -> index bindings visible at root
+     * Parameter order: the maps being filled
+     * Parameter next: the definition-order counter
+     * Parameter visited: the identity set of already-visited nodes
+     */
+    private static void assignCteOrder(Plan root, Map<String, Integer> 
visible, CteOrder order,
+            int[] next, Set<Plan> visited) {
+        if (root == null || !visited.add(root)) {
+            return;
+        }
+        if (root instanceof UnboundRelation) {
+            List<String> parts = ((UnboundRelation) root).getNameParts();
+            if (parts != null && parts.size() == 1) {
+                Integer index = visible.get(normalizeCteName(parts.get(0)));
+                if (index != null) {
+                    order.referenceIndex.put(root, index);
+                }
+            }
+        }
+        if (root instanceof LogicalCTE) {
+            LogicalCTE<? extends Plan> cte = (LogicalCTE<? extends Plan>) root;
+            List<LogicalSubQueryAlias<Plan>> aliases = cte.getAliasQueries();
+            Map<String, Integer> extended = new HashMap<>(visible);
+            for (LogicalSubQueryAlias<Plan> alias : aliases) {
+                String name = normalizeCteName(alias.getAlias());
+                order.definitionOrder.putIfAbsent(name, next[0]);
+                extended.put(name, next[0]++);
+            }
+            assignCteOrder(cte.child(0), extended, order, next, visited);
+            for (int i = 0; i < aliases.size(); i++) {
+                Map<String, Integer> bodyScope = new HashMap<>(visible);
+                for (int j = 0; j < i; j++) {
+                    String name = normalizeCteName(aliases.get(j).getAlias());
+                    bodyScope.put(name, extended.get(name));
+                }
+                // a self reference binds to the WITH clause only in a real 
recursive CTE;
+                // under a plain WITH it is an ordinary base-table reference
+                if (cte.isRecursive() && aliases.get(i).isRecursiveCte()) {
+                    String name = normalizeCteName(aliases.get(i).getAlias());
+                    bodyScope.put(name, extended.get(name));
+                }
+                assignCteOrder(aliases.get(i), bodyScope, order, next, 
visited);
+            }
+            return;
+        }
+        for (Plan child : root.children()) {
+            assignCteOrder(child, visible, order, next, visited);
+        }
+        for (Plan extra : root.extraPlans()) {
+            assignCteOrder(extra, visible, order, next, visited);
+        }
+        for (Expression expression : root.getExpressions()) {
+            assignCteOrderInSubqueries(expression, visible, order, next, 
visited);
+        }
+    }
+
+    /**
+     * Scoped counterpart of walkSubqueryPlans for cteDefinitionOrder.
+     *
+     * Parameter expression: the expression to scan
+     * Parameter visible: the bindings visible at the expression
+     * Parameter order: the maps being filled
+     * Parameter next: the definition-order counter
+     * Parameter visited: the identity set of already-visited nodes
+     */
+    private static void assignCteOrderInSubqueries(Expression expression,
+            Map<String, Integer> visible, CteOrder order, int[] next, 
Set<Plan> visited) {
+        if (expression instanceof SubqueryExpr) {
+            assignCteOrder(((SubqueryExpr) expression).getQueryPlan(), 
visible, order, next,
+                    visited);
+        }
+        if (expression instanceof UnboundStar) {
+            for (NamedExpression replaced : ((UnboundStar) 
expression).getReplacedAlias()) {
+                assignCteOrderInSubqueries(replaced, visible, order, next, 
visited);
+            }
+        }
+        for (Expression child : expression.children()) {
+            assignCteOrderInSubqueries(child, visible, order, next, visited);
+        }
+    }
+
+    /** Pre-order walk assigning each relation node its per-name occurrence 
ordinal. */
+    private static void assignRelationOrdinals(Plan plan, Map<String, Integer> 
counters,
+            IdentityHashMap<Plan, Integer> ordinals, CteOrder cteOrder,
+            Set<Plan> visited) {
+        if (plan == null || !visited.add(plan)) {
+            return;
+        }
+        String name = relationNameOf(plan, cteOrder);
+        if (name != null) {
+            ordinals.put(plan, counters.merge(name, 1, Integer::sum));
+        }
+        for (Plan child : plan.children()) {
+            assignRelationOrdinals(child, counters, ordinals, cteOrder, 
visited);
+        }
+        for (Plan extra : plan.extraPlans()) {
+            assignRelationOrdinals(extra, counters, ordinals, cteOrder, 
visited);
+        }
+        for (Expression expression : plan.getExpressions()) {
+            assignRelationOrdinals(expression, counters, ordinals, cteOrder, 
visited);
+        }
+    }
+
+    /** Recurses one expression tree for relation ordinals (see 
assignRelationOrdinals). */
+    private static void assignRelationOrdinals(Expression expression,
+            Map<String, Integer> counters, IdentityHashMap<Plan, Integer> 
ordinals,
+            CteOrder cteOrder, Set<Plan> visited) {
+        if (expression instanceof SubqueryExpr) {
+            assignRelationOrdinals(((SubqueryExpr) expression).getQueryPlan(), 
counters,
+                    ordinals, cteOrder, visited);
+        }
+        if (expression instanceof UnboundStar) {
+            for (NamedExpression replaced : ((UnboundStar) 
expression).getReplacedAlias()) {
+                assignRelationOrdinals(replaced, counters, ordinals, cteOrder, 
visited);
+            }
+        }
+        for (Expression child : expression.children()) {
+            assignRelationOrdinals(child, counters, ordinals, cteOrder, 
visited);
+        }
+    }
+
+    /**
+     * Encodes limit, offset, sort-key count/direction/null ordering for TopN, 
and the sorted relation-occurrence
+     * identities below the cap. A LogicalLimit uses a dash for the sort 
section. Order-key expressions and
+     * intervening filter expressions are not encoded in this key; other 
replay checks provide additional
+     * constraints.
+     */
+    private static String rowLimitKey(long limit, long offset, Plan limitNode,
+            RelationInputIndex inputIndex) {
+        Set<String> inputs = inputIndex.inputs(limitNode);
+        String slice = "-";
+        if (limitNode instanceof LogicalTopN) {
+            List<OrderKey> orderKeys = ((LogicalTopN<?>) 
limitNode).getOrderKeys();
+            StringBuilder keys = new 
StringBuilder(String.valueOf(orderKeys.size()));
+            for (OrderKey key : orderKeys) {
+                keys.append(key.isAsc() ? '+' : '-')
+                        .append(key.isNullFirst() ? 'n' : 'l').append(';');
+            }
+            slice = keys.toString();
+        }
+        return limit + ":" + offset + ":" + slice + ":" + String.join(",", 
inputs);
+    }
+
+    /** Shares input sets of overlapping cap subtrees within one collection. */
+    private static final class RelationInputIndex {
+        private final IdentityHashMap<Plan, Integer> ordinals;
+        private final CteOrder cteOrder;
+        private final IdentityHashMap<Plan, Set<String>> completed = new 
IdentityHashMap<>();
+        private final Set<Plan> active = Collections.newSetFromMap(new 
IdentityHashMap<>());
+        private boolean cyclic;
+
+        RelationInputIndex(IdentityHashMap<Plan, Integer> ordinals, CteOrder 
cteOrder) {
+            this.ordinals = ordinals;
+            this.cteOrder = cteOrder;
+        }
+
+        Set<String> inputs(Plan plan) {
+            Set<String> result = cyclic ? Set.of() : collect(plan);
+            if (cyclic) {
+                // extraPlans can expose a cycle. Preserve the original 
identity-set
+                // reachability semantics rather than publishing a partial 
cached set.
+                result = new TreeSet<>();
+                collectRelationInputs(plan, ordinals, cteOrder, result,
+                        Collections.newSetFromMap(new IdentityHashMap<>()));
+            }
+            return result;
+        }
+
+        private Set<String> collect(Plan plan) {
+            Set<String> cached = completed.get(plan);
+            if (cached != null) {
+                return cached;
+            }
+            Set<String> result = new TreeSet<>();
+            collectInto(plan, plan, result, Collections.newSetFromMap(new 
IdentityHashMap<>()));
+            Set<String> frozen = Collections.unmodifiableSet(result);
+            completed.put(plan, frozen);
+            return frozen;
+        }
+
+        private void collectInto(Plan plan, Plan root, Set<String> result, 
Set<Plan> visited) {
+            if (plan == null) {
+                return;
+            }
+            if (plan != root && (plan instanceof LogicalLimit || plan 
instanceof LogicalTopN)) {
+                result.addAll(collect(plan));
+                return;
+            }
+            if (active.contains(plan)) {
+                cyclic = true;
+                return;
+            }
+            if (!visited.add(plan)) {
+                return;
+            }
+            active.add(plan);
+            String name = relationNameOf(plan, cteOrder);
+            if (name != null) {
+                Integer ordinal = ordinals.get(plan);
+                result.add(ordinal == null ? name : name + "#" + ordinal);
+            }
+            for (Plan child : plan.children()) {
+                collectInto(child, root, result, visited);
+            }
+            for (Plan extra : plan.extraPlans()) {
+                collectInto(extra, root, result, visited);
+            }
+            for (Expression expression : plan.getExpressions()) {
+                collectExpression(expression, root, result, visited);
+            }
+            active.remove(plan);
+        }
+
+        private void collectExpression(Expression expression, Plan root, 
Set<String> result, Set<Plan> visited) {
+            if (expression instanceof SubqueryExpr) {
+                collectInto(((SubqueryExpr) expression).getQueryPlan(), root, 
result, visited);
+            }
+            if (expression instanceof UnboundStar) {
+                for (NamedExpression replaced : ((UnboundStar) 
expression).getReplacedAlias()) {
+                    collectExpression(replaced, root, result, visited);
+                }
+            }
+            for (Expression child : expression.children()) {
+                collectExpression(child, root, result, visited);
+            }
+        }
+    }
+
+    /**
+     * The OCCURRENCE-TAGGED name of every relation beneath a row-limiting 
node (children,
+     * CTE bodies and expression-owned subquery plans included): db.t#N with N 
the
+     * node's per-name ordinal in the tree's walk order. A subtree without a 
relation (a
+     * FROM-less child) contributes nothing - the key then identifies the cap 
by its
+     * values alone, exactly as the caller's equivalent cap does.
+     */
+    private static void collectRelationInputs(Plan plan,
+            IdentityHashMap<Plan, Integer> relationOrdinals,
+            CteOrder cteOrder, Set<String> out,
+            Set<Plan> visited) {
+        if (plan == null || !visited.add(plan)) {
+            return;
+        }
+        String name = relationNameOf(plan, cteOrder);
+        if (name != null) {
+            Integer ordinal = relationOrdinals.get(plan);
+            out.add(ordinal == null ? name : name + "#" + ordinal);
+        }
+        for (Plan child : plan.children()) {
+            collectRelationInputs(child, relationOrdinals, cteOrder, out, 
visited);
+        }
+        for (Plan extra : plan.extraPlans()) {
+            collectRelationInputs(extra, relationOrdinals, cteOrder, out, 
visited);
+        }
+        for (Expression expression : plan.getExpressions()) {
+            collectRelationInputs(expression, relationOrdinals, cteOrder, out, 
visited);
+        }
+    }
+
+    /** Recurses one expression tree for relation inputs (see 
collectRelationInputs). */
+    private static void collectRelationInputs(Expression expression,
+            IdentityHashMap<Plan, Integer> relationOrdinals,
+            CteOrder cteOrder, Set<String> out,
+            Set<Plan> visited) {
+        if (expression instanceof SubqueryExpr) {
+            collectRelationInputs(((SubqueryExpr) expression).getQueryPlan(),
+                    relationOrdinals, cteOrder, out, visited);
+        }
+        if (expression instanceof UnboundStar) {
+            for (NamedExpression replaced : ((UnboundStar) 
expression).getReplacedAlias()) {
+                collectRelationInputs(replaced, relationOrdinals, cteOrder, 
out, visited);
+            }
+        }
+        for (Expression child : expression.children()) {
+            collectRelationInputs(child, relationOrdinals, cteOrder, out, 
visited);
+        }
+    }
+
+    /**
+     * The identity name of one relation node used by the row-limit keys, or 
null when
+     * the node is not a relation.
+     *
+     * A one-part relation bound by a CTE alias is named by its CTE's 
DEFINITION ORDER
+     * index ("cte#N"), not by the alias: the frozen planSql replayed for an
+     * identical-text baseline is the DECOMPILED plan, and the decompiler 
regenerates
+     * every WITH alias (the caller's ws_wh becomes t_4) while preserving the 
WITH
+     * structure and its order (see SPMPlanTreeSupport.cteDefinitionOrder). 
Comparing
+     * the alias verbatim made the identical query fail its own cap contract. 
The
+     * index keeps distinct CTEs distinct, so a cap moved between two CTEs 
still
+     * changes its key.
+     */
+    private static String relationNameOf(Plan plan, CteOrder cteOrder) {
+        if (plan instanceof UnboundRelation) {
+            List<String> parts = ((UnboundRelation) plan).getNameParts();
+            if (parts == null || parts.isEmpty()) {
+                return null;
+            }
+            if (parts.size() == 1 && cteOrder != null) {
+                Integer cteIndex = cteOrder.indexOf(plan, parts.get(0));
+                if (cteIndex != null) {
+                    return "cte#" + cteIndex;
+                }
+            }
+            return String.join(".", parts);
+        }
+        if (plan instanceof LogicalCatalogRelation) {
+            return ((LogicalCatalogRelation) 
plan).getTable().getNameWithFullQualifiers();
+        }
+        if (plan instanceof UnboundTVFRelation) {
+            return ((UnboundTVFRelation) plan).getFunctionName();
+        }
+        return null;
+    }
+
+    // whole-tree transform (parameterize / substitute).
+
+    /**
+     * Transforms supported expression positions and rebuilds affected logical 
nodes. Explicit handlers cover
+     * filters, projections, aggregates, joins, sorting, generators, repeats 
and CTE payloads. Other nodes rebuild
+     * ordinary children when supported; their expression payloads are not 
transformed generically.
+     * Expression-owned subquery traversal is the responsibility of the 
supplied expression transform.
+     */
+    public static LogicalPlan transform(LogicalPlan plan, ExprTransform 
transform) {
+        Plan result = plan.accept(new TreeTransformer(), transform);
+        return result instanceof LogicalPlan ? (LogicalPlan) result : plan;
+    }
+
+    /**
+     * The GROUP BY mirror KEY of one expression (see mirrorProjectItem / 
mirrorGroupByText).
+     *
+     * The rendered text alone is NOT an identity: UnboundFunction.toString 
drops the DATABASE
+     * qualifier, so GROUP BY db1.f(k, 1), db2.f(k, 1) recorded the SAME key 
twice and the
+     * reverse lookup replaced the db1.f select item with the LAST (db2.f) 
group key. Both
+     * group keys exist and the copy parameterizes its literals identically, 
so CREATE still
+     * planned and stored the baseline - but the caller's namespace-qualified 
tree carries
+     * db1.f, which SPMAstCheckVisitor rejects against the stored db2.f, so 
the baseline could
+     * not match even its own identical query.
+     *
+     * The trace therefore appends the RESOLVED SCOPE of every function call 
(its written
+     * database) and of every column reference (its full name parts / slot 
identity) in
+     * pre-order. It is a pure REFINEMENT of the former text key - two 
expressions whose text
+     * differed still differ - so no mirror that used to match stops matching.
+     *
+     * Parameter expr: the expression to key
+     * Returns: the stable mirror key
+     */
+    public static String expressionIdentity(Expression expr) {
+        if (expr == null) {
+            return "null";
+        }
+        StringBuilder identity = new StringBuilder(expr.toString());
+        appendExpressionScope(expr, identity);
+        return identity.toString();
+    }
+
+    /**
+     * The scope trace of expressionIdentity: one entry per function / column
+     * reference, in pre-order.
+     *
+     * Parameter expr: the expression to render
+     * Parameter identity: the identity being built
+     */
+    private static void appendExpressionScope(Expression expr, StringBuilder 
identity) {
+        if (expr instanceof org.apache.doris.nereids.analyzer.UnboundFunction) 
{
+            // the WRITTEN qualifier: db1.f(...) and db2.f(...) render 
identically without it
+            org.apache.doris.nereids.analyzer.UnboundFunction function =
+                    (org.apache.doris.nereids.analyzer.UnboundFunction) expr;
+            identity.append('\u0001').append("fn=")
+                    .append(function.getDbName() == null ? ""
+                            : 
function.getDbName().toLowerCase(java.util.Locale.ROOT))
+                    .append('|').append(function.isDistinct());
+        } else if (expr instanceof 
org.apache.doris.nereids.analyzer.UnboundSlot) {
+            identity.append('\u0001').append("col=").append(String.join(".",
+                    ((org.apache.doris.nereids.analyzer.UnboundSlot) 
expr).getNameParts()));
+        } else if (expr instanceof 
org.apache.doris.nereids.trees.expressions.SlotReference) {
+            // an analyzed reference has no name parts left: its expression id 
IS its identity
+            org.apache.doris.nereids.trees.expressions.SlotReference slot =
+                    (org.apache.doris.nereids.trees.expressions.SlotReference) 
expr;
+            identity.append('\u0001').append("col=").append(slot.getName())
+                    .append('#').append(slot.getExprId().asInt());
+        }
+        for (Expression child : expr.children()) {
+            appendExpressionScope(child, identity);
+        }
+    }
+
+    /** Plan visitor that rebuilds every node, transforming its expressions. */
+    private static class TreeTransformer extends PlanVisitor<Plan, 
ExprTransform> {
+
+        /**
+         * GROUP BY mirror records (see mirrorProjectItem): a group-by 
expression's
+         * pre-parameterization text mapped to its transformed self. A select 
item spelling
+         * the SAME expression must reuse those placeholder ids, or the 
parameterized tree
+         * fails NormalizeAggregate ("PROJECT expression... must appear in the 
GROUP BY
+         * clause"; tpcds q23_1 groups by substr(i_item_desc, 1, 30) and 
selects the same
+         * expression, whose literals otherwise receive their own ids and make 
the two
+         * copies structurally different). Records stay consumable for the 
projection
+         * directly above the aggregate and are dropped once its items were 
processed.
+         */
+        private final java.util.List<GroupByMirror> groupByMirrors = new 
java.util.ArrayList<>();
+
+        /** One recorded group-by mirror: the scope-aware key and the 
transformed expression. */
+        private static final class GroupByMirror {
+            private final String key;
+            private final Expression expression;
+
+            private GroupByMirror(String key, Expression expression) {
+                this.key = key;
+                this.expression = expression;
+            }
+        }
+
+        @Override
+        public Plan visit(Plan plan, ExprTransform transform) {
+            // LogicalUsingJoin.accept dispatches to this generic visit 
(PlanVisitor has no
+            // using-join overload), so the ASOF MATCH_CONDITION is handled 
here: it is
+            // stored OUTSIDE children and getExpressions and would otherwise 
keep its
+            // literal concrete.
+            if (plan instanceof LogicalUsingJoin) {
+                return visitUsingJoin((LogicalUsingJoin<?, ?>) plan, 
transform);
+            }
+            List<Plan> children = plan.children();
+            boolean changed = false;
+            List<Plan> newChildren = new ArrayList<>(children.size());
+            for (Plan child : children) {
+                Plan newChild = child.accept(this, transform);
+                newChildren.add(newChild);
+                if (newChild != child) {
+                    changed = true;
+                }
+            }
+            if (!changed) {
+                return plan;
+            }
+            try {
+                return plan.withChildren(newChildren);
+            } catch (RuntimeException e) {
+                // plan type without withChildren -> keep the original children
+                return plan;
+            }
+        }
+
+        @Override
+        public Plan visitLogicalCTE(LogicalCTE<? extends Plan> cte, 
ExprTransform transform) {
+            // the main query subtree, then the CTE bodies (kept in 
aliasQueries, not in
+            // children) - a WHERE inside a CTE definition is transformed too.
+            // A ScopedTransform needs per-scope contexts here: the main query 
sees every
+            // alias of this WITH, alias body i only the aliases defined 
before it.
+            // A WITH is a QUERY-BLOCK boundary for the GROUP BY mirrors as 
well: its
+            // aggregates record mirrors for their own block's SELECT / HAVING 
/ ORDER BY
+            // only, and nothing recorded inside may be consumed by an item 
list above the
+            // WITH (see visitLogicalSubQueryAlias / mirrorProjectItem).
+            int mirrorMark = groupByMirrors.size();
+            try {
+                ExprTransform mainContext = transform instanceof 
ScopedTransform
+                        ? ((ScopedTransform) transform).enterCteMain(cte) : 
transform;
+                Plan newChild = cte.child(0) == null ? null : 
cte.child(0).accept(this, mainContext);
+                boolean childChanged = newChild != cte.child(0);
+                List<LogicalSubQueryAlias<Plan>> newAliasQueries =
+                        new ArrayList<>(cte.getAliasQueries().size());
+                boolean aliasChanged = false;
+                for (int i = 0; i < cte.getAliasQueries().size(); i++) {
+                    LogicalSubQueryAlias<Plan> aliasQuery = 
cte.getAliasQueries().get(i);
+                    ExprTransform aliasContext = transform instanceof 
ScopedTransform
+                            ? ((ScopedTransform) transform).enterCteAlias(cte, 
i) : transform;
+                    Plan newAliasQuery = aliasQuery.accept(this, aliasContext);
+                    newAliasQueries.add((LogicalSubQueryAlias<Plan>) 
newAliasQuery);
+                    if (newAliasQuery != aliasQuery) {
+                        aliasChanged = true;
+                    }
+                }
+                if (!childChanged && !aliasChanged) {
+                    return cte;
+                }
+                try {
+                    return new LogicalCTE<Plan>(cte.isRecursive(), 
newAliasQueries, newChild);
+                } catch (RuntimeException e) {
+                    return cte;
+                }
+            } finally {
+                dropGroupByMirrorsFrom(mirrorMark);
+            }
+        }
+
+        @Override
+        public Plan visitLogicalSubQueryAlias(LogicalSubQueryAlias<? extends 
Plan> alias,
+                ExprTransform transform) {
+            // A derived table / CTE body opens a nested QUERY BLOCK (see
+            // ExprTransform.enterQueryBlock): its literals must be able to 
distinguish
+            // themselves from equally shaped literals of the outer block or 
of a sibling.
+            // The numbering is per rebuild and both trees of a baseline 
traverse the same
+            // structure, so corresponding blocks keep corresponding ids.
+            transform.enterQueryBlock();
+            int mirrorMark = groupByMirrors.size();
+            try {
+                Plan child = alias.child() == null ? null : 
alias.child().accept(this, transform);
+                if (child == alias.child()) {
+                    return alias;
+                }
+                return alias.withChildren(java.util.List.of(child));
+            } finally {
+                transform.exitQueryBlock();
+                // A derived table / CTE body is its OWN query block: the 
GROUP BY mirrors its
+                // aggregate recorded must be consumable ONLY by that block's 
own SELECT /
+                // HAVING / ORDER BY (all inside this subtree). Leaving them 
behind let the
+                // ENCLOSING block's projection - the item list ABOVE this 
alias - consume the
+                // inner expression's placeholder ids for an equally spelled 
item, so two
+                // DIFFERENT values shared one id and a valid literal variant 
could never use
+                // its baseline (see mirrorProjectItem).
+                dropGroupByMirrorsFrom(mirrorMark);
+            }
+        }
+
+        @Override
+        public Plan visitUnboundRelation(UnboundRelation relation, 
ExprTransform transform) {
+            // of the whole-tree transforms, only namespace qualification 
rewrites relation
+            // references; parameterization / substitution leave them untouched
+            return transform instanceof QualifyTransform
+                    ? ((QualifyTransform) transform).qualify(relation) : 
relation;
+        }
+
+        @Override
+        public Plan visitLogicalProject(LogicalProject<? extends Plan> project,
+                ExprTransform transform) {
+            int mirrorMark = groupByMirrors.size();
+            Plan child = project.child().accept(this, transform);
+            boolean changed = child != project.child();
+            List<NamedExpression> newProjects = 
transformProjectItems(project.getProjects(),
+                    transform, mirrorMark);
+            dropGroupByMirrorsFrom(mirrorMark);
+            if (newProjects != project.getProjects()) {
+                changed = true;
+            }
+            if (!changed) {
+                return project;
+            }
+            return project.withProjectsAndChild(newProjects, child);
+        }
+
+        /**
+         * transformNamed with the GROUP BY mirror: an item whose 
pre-parameterization value
+         * text equals a group-by expression recorded by the aggregate below 
inherits that
+         * expression WITH its placeholder ids, keeping the two structurally 
equal (the
+         * analyzer requires a select expression to literally reappear in the 
GROUP BY: the
+         * ids allocated for one copy cannot be re-derived for the other, see
+         * mirrorProjectItem).
+         */
+        private List<NamedExpression> 
transformProjectItems(List<NamedExpression> expressions,
+                ExprTransform transform, int mirrorMark) {
+            boolean changed = false;
+            List<NamedExpression> newExpressions = new 
ArrayList<>(expressions.size());
+            for (int i = 0; i < expressions.size(); i++) {
+                NamedExpression expression = expressions.get(i);
+                NamedExpression mirrored = mirrorProjectItem(expression, 
mirrorMark);
+                if (mirrored != null) {
+                    newExpressions.add(mirrored);
+                    changed = true;
+                    continue;
+                }
+                // the item's POSITION in the list is part of the placeholder 
identity (see
+                // ExprTransform.enterProjectionItem)
+                transform.enterProjectionItem(i);
+                Expression transformed;
+                try {
+                    transformed = transform.apply(expression);
+                } finally {
+                    transform.exitProjectionItem();
+                }
+                if (transformed instanceof NamedExpression && transformed != 
expression) {
+                    newExpressions.add((NamedExpression) transformed);
+                    changed = true;
+                } else {
+                    newExpressions.add(expression);
+                }
+            }
+            return changed ? newExpressions : expressions;
+        }
+
+        /** One item rewritten to the recorded group-by expression, or null 
when none matches. */
+        private NamedExpression mirrorProjectItem(NamedExpression item, int 
mirrorMark) {
+            // the raw parse tree wraps select items in UnboundAlias, the 
analyzed tree in
+            // Alias: both expose the aliased expression as their only child
+            Expression value = item instanceof Alias || item instanceof 
UnboundAlias
+                    ? item.child(0) : item;
+            String key = expressionIdentity(value);
+            Expression mirror = null;
+            for (int i = groupByMirrors.size() - 1; i >= mirrorMark; i--) {
+                if (groupByMirrors.get(i).key.equals(key)) {
+                    mirror = groupByMirrors.get(i).expression;
+                    break;
+                }
+            }
+            if (mirror == null) {
+                return null;
+            }
+            if (item instanceof Alias || item instanceof UnboundAlias) {
+                return (NamedExpression) 
item.withChildren(java.util.List.of(mirror));
+            }
+            return mirror instanceof NamedExpression ? (NamedExpression) 
mirror : null;
+        }
+
+        private void dropGroupByMirrorsFrom(int mirrorMark) {
+            while (groupByMirrors.size() > mirrorMark) {
+                groupByMirrors.remove(groupByMirrors.size() - 1);
+            }
+        }
+
+        /**
+         * One recorded group-by expression resolved by PRE-text within a 
clause window,
+         * but ONLY when its transformed form carries placeholder ids (see
+         * installGroupByMirrorLookup). A LITERAL-FREE group-by expression 
transforms to
+         * itself, so reusing it would merely SHARE the object with the ORDER 
BY / HAVING
+         * copy: the optimizer's common-subexpression handling then rewires 
the plan and
+         * the decompiled text (tpcds q22 / q26 / q29 / q46 CTE-renumbering 
diffs) without
+         * any matching or analyzability benefit. Only a PARAMETERIZED copy 
(tpcds q62:
+         * substr(w_warehouse_name, _spm_const_var(..), _spm_const_var(..))) 
must be reused,
+         * because fresh ids would break the analyzer's literal-reappearance 
requirement.
+         */
+        private Expression mirrorGroupByText(String text, int mirrorMark) {
+            for (int i = groupByMirrors.size() - 1; i >= mirrorMark; i--) {
+                if (groupByMirrors.get(i).key.equals(text)
+                        && 
containsPlaceholder(groupByMirrors.get(i).expression)) {
+                    return groupByMirrors.get(i).expression;
+                }
+            }
+            return null;
+        }
+
+        /**
+         * Supplies the clause-local GROUP BY mirror lookup through the 
transform callback. A parameterizing
+         * transform, including its subquery adapter, reuses these transformed 
expressions when nested HAVING or
+         * ORDER BY expressions refer to the same group key. Other transforms 
can leave the callback unused.
+         */
+        private void installGroupByMirrorLookup(ExprTransform transform, int 
mirrorMark) {
+            transform.setGroupByMirrorLookup(text -> mirrorGroupByText(text, 
mirrorMark));
+        }
+
+        private void clearGroupByMirrorLookup(ExprTransform transform) {
+            transform.setGroupByMirrorLookup(null);
+        }
+
+        @Override
+        public Plan visitLogicalFilter(LogicalFilter<? extends Plan> filter,
+                ExprTransform transform) {
+            Plan child = filter.child().accept(this, transform);
+            boolean changed = child != filter.child();
+            Set<Expression> newConjuncts = 
transformConjuncts(filter.getConjuncts(), transform);
+            if (newConjuncts != filter.getConjuncts()) {
+                changed = true;
+            }
+            if (!changed) {
+                return filter;
+            }
+            return filter.withConjunctsAndChild(newConjuncts, child);
+        }
+
+        @Override
+        public Plan visitLogicalJoin(LogicalJoin<? extends Plan, ? extends 
Plan> join,
+                ExprTransform transform) {
+            // A literal can live directly in a JOIN's ON clause (e.g.
+            // "a JOIN b ON a.k = b.k AND a.cat = 'x'"); it is NOT pushed into 
a Filter
+            // on the unbound (raw) tree that parameterization runs over. 
Without handling
+            // the join's own conjuncts here those literals would stay 
concrete in the
+            // parameterized bind tree, so a structurally identical query with 
a different
+            // literal would fail the Level 3 structural match and never hit 
the baseline.
+            Plan left = join.left().accept(this, transform);
+            Plan right = join.right().accept(this, transform);
+            List<Expression> hash = 
transformExprs(join.getHashJoinConjuncts(), transform);
+            List<Expression> other = 
transformExprs(join.getOtherJoinConjuncts(), transform);
+            List<Expression> mark = 
transformExprs(join.getMarkJoinConjuncts(), transform);
+            boolean changed = left != join.left() || right != join.right()
+                    || hash != join.getHashJoinConjuncts()
+                    || other != join.getOtherJoinConjuncts()
+                    || mark != join.getMarkJoinConjuncts();
+            if (!changed) {
+                return join;
+            }
+            return join.withConjunctsChildren(hash, other, mark, left, right,
+                    new JoinReorderContext());
+        }
+
+        /**
+         * Rebuilds an ASOF / USING join, transforming the MATCH_CONDITION. 
The condition is
+         * stored in matchCondition, OUTSIDE both children and
+         * getExpressions (which returns the USING slots), so the generic pass 
would
+         * leave its literal concrete on the bind side - the Level 3 match 
would then
+         * compare only the USING slots and accept a user variant with a 
different
+         * temporal boundary, replaying the captured one.
+         */
+        private Plan visitUsingJoin(LogicalUsingJoin<? extends Plan, ? extends 
Plan> join,
+                ExprTransform transform) {
+            Plan left = join.left().accept(this, transform);
+            Plan right = join.right().accept(this, transform);
+            Optional<Expression> match = join.getMatchCondition();
+            Optional<Expression> newMatch = match.isPresent()
+                    ? Optional.of(transform.apply(match.get())) : match;
+            if (left == join.left() && right == join.right() && 
newMatch.equals(match)) {
+                return join;
+            }
+            return new LogicalUsingJoin<>(join.getJoinType(), left, right,
+                    join.getUsingSlots(), newMatch, join.getDistributeHint());
+        }
+
+        @Override
+        public Plan visitLogicalHaving(LogicalHaving<? extends Plan> having, 
ExprTransform transform) {
+            // HAVING is resolved against the aggregate UNDER it: a conjunct 
that spells a
+            // GROUP BY expression must reuse that group-by mirror (its 
placeholder ids),
+            // or the parameterized tree fails FillUpMissingSlots ("HAVING 
expression...
+            // must appear in the GROUP BY clause" under ONLY_FULL_GROUP_BY) - 
the same
+            // one-copy-two-ids trap the SELECT list hit (see 
mirrorProjectItem). The
+            // records are NOT dropped here: a Sort directly above this HAVING 
still
+            // consumes them.
+            int mirrorMark = groupByMirrors.size();
+            Plan child = having.child().accept(this, transform);
+            boolean changed = child != having.child();
+            installGroupByMirrorLookup(transform, mirrorMark);
+            Set<Expression> newConjuncts;
+            try {
+                newConjuncts = transformConjuncts(having.getConjuncts(), 
transform);
+            } finally {
+                clearGroupByMirrorLookup(transform);
+            }
+            if (newConjuncts != having.getConjuncts()) {
+                changed = true;
+            }
+            if (!changed) {
+                return having;
+            }
+            return having.withConjunctsAndChild(newConjuncts, child);
+        }
+
+        @Override
+        public Plan visitLogicalAggregate(LogicalAggregate<? extends Plan> 
aggregate,
+                ExprTransform transform) {
+            Plan child = aggregate.child().accept(this, transform);
+            boolean changed = child != aggregate.child();
+            int mirrorMark = groupByMirrors.size();
+            List<Expression> newGroupBy = new 
ArrayList<>(aggregate.getGroupByExpressions().size());
+            for (Expression groupByExpr : aggregate.getGroupByExpressions()) {
+                // A BARE integer GROUP BY key is an ORDINAL - a positional 
reference to the
+                // SELECT item, resolved by bindWithOrdinal during analyze 
(exactly like the
+                // ORDER BY ordinal handling in visitLogicalSort), NOT the 
literal value of
+                // that item. Parameterizing it turned the ordinal into a 
placeholder
+                // function (the analyzer no longer resolves a position and 
groups by a
+                // constant), AND the group-by mirror recorded "1 -> ph1", 
which
+                // mirrorProjectItem then REUSED for the independent SELECT 
literal:
+                // SELECT 1 AS c, count(*) AS n FROM t GROUP BY 1 recorded 
ph1=1 from the
+                // group expression during matching and the output expression 
then rejected
+                // the caller's ph1=2 - the valid SELECT 2 AS c... GROUP BY 1 
variant
+                // could never hit its own baseline.
+                if (groupByExpr instanceof IntegerLikeLiteral) {
+                    newGroupBy.add(groupByExpr);
+                    continue;
+                }
+                Expression newExpr = transform.apply(groupByExpr);
+                newGroupBy.add(newExpr);
+                if (newExpr != groupByExpr) {
+                    changed = true;
+                    // a select item spelling the same expression must reuse 
these ids (see
+                    // mirrorProjectItem): the analyzer requires the select 
expression to
+                    // literally reappear in the GROUP BY of the parameterized 
tree
+                    groupByMirrors.add(new 
GroupByMirror(expressionIdentity(groupByExpr), newExpr));
+                }
+            }
+            // The SELECT list of an aggregate query lives in the aggregate's 
OWN output
+            // expressions for aggregate-rooted shapes, and in the PROJECT 
above it for
+            // project-rooted shapes: the records stay alive for BOTH 
consumers and are
+            // dropped by the enclosing projection's own cleanup after its 
items ran.
+            List<NamedExpression> newOutput = transformProjectItems(
+                    aggregate.getOutputExpressions(), transform, mirrorMark);
+            if (newOutput != aggregate.getOutputExpressions()) {
+                changed = true;
+            }
+            // The source target carries the placeholder ids that must survive 
in a
+            // grouping-column producer in the frozen SQL, not in the ordinal 
itself.
+            
noteParameterizedGroupByOrdinalTargets(aggregate.getGroupByExpressions(), 
newOutput, transform);
+            if (!changed) {
+                return aggregate;
+            }
+            return aggregate.withChildGroupByAndOutput(newGroupBy, newOutput, 
child);
+        }
+
+        @Override
+        public Plan visitUnboundOneRowRelation(UnboundOneRowRelation oneRow,
+                ExprTransform transform) {
+            List<NamedExpression> newProjects = 
transformNamed(oneRow.getProjects(), transform);
+            if (newProjects == oneRow.getProjects()) {
+                return oneRow;
+            }
+            return new UnboundOneRowRelation(oneRow.getRelationId(), 
newProjects);
+        }
+
+        @Override
+        public Plan visitLogicalOneRowRelation(LogicalOneRowRelation oneRow,
+                ExprTransform transform) {
+            List<NamedExpression> newProjects = 
transformNamed(oneRow.getProjects(), transform);
+            if (newProjects == oneRow.getProjects()) {
+                return oneRow;
+            }
+            return new LogicalOneRowRelation(oneRow.getRelationId(), 
newProjects);
+        }
+
+        @Override
+        public Plan visitLogicalSort(LogicalSort<? extends Plan> sort,
+                ExprTransform transform) {
+            // ORDER BY keys can carry literals (e.g. substr(w_warehouse_name, 
1, 20) in a
+            // TPCDS query): they must be parameterized / substituted like any 
other
+            // expression, otherwise the rewritten tree would keep the 
bind-side order key
+            // while group-by / project got the user's value -> analyze error 
/ wrong order.
+            //
+            // EXCEPTION: an ORDER BY whose key is a BARE integer literal is 
an ORDINAL
+            // (position reference, e.g. ORDER BY 1, 2), resolved by 
BindExpression during
+            // analyze. It must NOT be parameterized: parameterizing would 
turn the ordinal
+            // into a placeholder function and the optimizer would then sort 
by the
+            // constant value (projecting it as an extra column) instead of by 
the
+            // referenced output column - silently changing the query's row 
order.
+            //
+            // A key that SPELLS a GROUP BY expression of the aggregate 
directly below
+            // (".when"-shapes like "GROUP BY substr(x, 1, 20) ORDER BY 
substr(x, 1, 20)")
+            // must reuse the group-by mirror instead of allocating its own 
placeholder
+            // ids: the analyzer requires the order key to literally reappear 
in the GROUP
+            // BY of the parameterized tree (ONLY_FULL_GROUP_BY), and two 
independently
+            // parameterized copies are structurally different (tpcds q62). 
The mirror
+            // lookup also keeps the one-id-one-value rule working: a user 
query whose
+            // order key literal differs from its group-by literal fails the 
value
+            // comparison instead of replaying the group-by value.
+            int mirrorMark = groupByMirrors.size();
+            Plan child = sort.child().accept(this, transform);
+            boolean changed = child != sort.child();
+            List<OrderKey> orderKeys = sort.getOrderKeys();
+            List<OrderKey> newOrderKeys = new ArrayList<>(orderKeys.size());
+            installGroupByMirrorLookup(transform, mirrorMark);
+            try {
+                for (OrderKey orderKey : orderKeys) {
+                    Expression keyExpr = orderKey.getExpr();
+                    Expression mirrored = keyExpr instanceof IntegerLikeLiteral
+                            ? null : mirrorGroupByText(keyExpr.toString(), 
mirrorMark);
+                    Expression newExpr = keyExpr instanceof IntegerLikeLiteral
+                            ? keyExpr
+                            : mirrored != null ? mirrored : 
transform.apply(keyExpr);
+                    if (newExpr != keyExpr) {
+                        changed = true;
+                    }
+                    newOrderKeys.add(orderKey.withExpression(newExpr));
+                }
+            } finally {
+                clearGroupByMirrorLookup(transform);
+            }
+            // Analysis binds ORDER BY ordinals to output slots before 
optimization.
+            // The decompiler renders those physical sort slots against its 
own projection.
+            dropGroupByMirrorsFrom(mirrorMark);
+            if (!changed) {
+                return sort;
+            }
+            return sort.withOrderKeysAndChild(newOrderKeys, child);
+        }
+
+        /** Detects a GROUP BY ordinal that resolves to a parameterized SELECT 
item. */
+        private void noteParameterizedGroupByOrdinalTargets(List<Expression> 
keys,
+                List<? extends NamedExpression> outputs, ExprTransform 
transform) {
+            for (Expression key : keys) {
+                Expression target = groupingOrdinalTarget(key, outputs);
+                if (target != null && containsPlaceholder(target)) {
+                    transform.noteParameterizedGroupingTarget(target);
+                }
+            }
+        }
+
+        @Override
+        public Plan visitLogicalQualify(LogicalQualify<? extends Plan> qualify,
+                ExprTransform transform) {
+            // QUALIFY <window-predicate>: the predicates live on the 
LogicalQualify node
+            // itself (e.g. "row_number() over (...) = 1") and would otherwise 
keep their
+            // literals concrete in the parameterized tree, so a user query 
with a
+            // different QUALIFY threshold never matches the baseline.
+            Plan child = qualify.child().accept(this, transform);
+            boolean changed = child != qualify.child();
+            Set<Expression> newConjuncts = 
transformConjuncts(qualify.getConjuncts(), transform);
+            if (newConjuncts != qualify.getConjuncts()) {
+                changed = true;
+            }
+            if (!changed) {
+                return qualify;
+            }
+            return new LogicalQualify<Plan>(newConjuncts, child);
+        }
+
+        @Override
+        public Plan visitLogicalGenerate(LogicalGenerate<? extends Plan> 
generate,
+                ExprTransform transform) {
+            // LATERAL VIEW / UNNEST: the generator arguments (e.g.
+            // explode(split('a,b,c', ','))) decide which rows/values the 
generator emits -
+            // they are NOT predicates (no WHERE-like semantics), so a 
different argument
+            // means a different query. They are therefore intentionally left 
concrete and
+            // never parameterized: SPM only matches a user query carrying the 
exact same
+            // generator argument. The conjuncts field is the only WHERE-like 
part of this
+            // node (empty at parse time), so it is still transformed for 
future-proofing.
+            Plan child = generate.child().accept(this, transform);
+            boolean changed = child != generate.child();
+            List<Expression> newConjuncts = 
transformExprs(generate.getConjuncts(), transform);
+            if (newConjuncts != generate.getConjuncts()) {
+                changed = true;
+            }
+            if (!changed) {
+                return generate;
+            }
+            return new LogicalGenerate<Plan>(generate.getGenerators(),
+                    generate.getGeneratorOutput(), 
generate.getExpandColumnAlias(),
+                    newConjuncts, child);
+        }
+
+        @Override
+        public Plan visitLogicalRepeat(LogicalRepeat<? extends Plan> repeat,
+                ExprTransform transform) {
+            Plan child = repeat.child().accept(this, transform);
+            boolean changed = child != repeat.child();
+            int mirrorMark = groupByMirrors.size();
+            List<NamedExpression> outputs = repeat.getOutputExpressions();
+            // ROLLUP/CUBE expand the same key into several sets. Parameterize 
each
+            // distinct expression once, before its SELECT/GROUPING/HAVING 
consumers.
+            // An ordinal itself stays concrete; its SELECT target is the 
expression
+            // that must share the marker ids with GROUPING(target).
+            Map<String, Expression> transformedKeys = new HashMap<>();
+            List<List<Expression>> newSets = new 
ArrayList<>(repeat.getGroupingSets().size());
+            for (List<Expression> set : repeat.getGroupingSets()) {
+                List<Expression> newKeys = new ArrayList<>(set.size());
+                for (Expression key : set) {
+                    Expression target = groupingOrdinalTarget(key, outputs);
+                    if (target == null && key instanceof IntegerLikeLiteral) {
+                        // An out-of-range integer is a concrete grouping 
value, just
+                        // as in visitLogicalAggregate; never turn it into an 
ordinal.
+                        newKeys.add(key);
+                        continue;
+                    }
+                    Expression value = target == null ? key : target;
+                    String identity = expressionIdentity(value);
+                    Expression transformed = transformedKeys.get(identity);
+                    if (transformed == null) {
+                        transformed = transform.apply(value);
+                        transformedKeys.put(identity, transformed);
+                        if (transformed != value) {
+                            groupByMirrors.add(new GroupByMirror(identity, 
transformed));
+                        }
+                        if (containsPlaceholder(transformed)) {
+                            
transform.noteParameterizedGroupingTarget(transformed);
+                        }
+                    }
+                    Expression newKey = target == null ? transformed : key;
+                    newKeys.add(newKey);
+                    changed |= newKey != key;
+                }
+                newSets.add(newKeys);
+            }
+            List<NamedExpression> newOutput;
+            if (groupByMirrors.size() == mirrorMark) {
+                newOutput = transformNamed(outputs, transform);
+            } else {
+                // GROUPING()/GROUPING_ID() arguments and nested grouping 
expressions
+                // must reuse the same symbolic key, even when the referencing 
item
+                // precedes the SELECT item that an ordinal names.
+                installGroupByMirrorLookup(transform, mirrorMark);
+                try {
+                    newOutput = transformProjectItems(outputs, transform, 
mirrorMark);
+                } finally {
+                    clearGroupByMirrorLookup(transform);
+                }
+            }
+            changed |= newOutput != outputs;
+            if (!changed) {
+                return repeat;
+            }
+            // Preserve the parse-time withInProjection flag and any 
grouping-id values.
+            return repeat.withGroupingIdValues(newSets, newOutput,
+                    repeat.getGroupingId().orElse(null), child);
+        }
+    }
+
+    /** Name of a parsed, unqualified GROUPING/GROUPING_ID call, or null for 
other expressions. */
+    public static String groupingFunctionName(Expression expression) {
+        if (expression instanceof UnboundFunction) {
+            UnboundFunction function = (UnboundFunction) expression;
+            String name = function.getName().toLowerCase(Locale.ROOT);
+            if ((function.getDbName() == null || 
function.getDbName().isEmpty())
+                    && ("grouping".equals(name) || 
"grouping_id".equals(name))) {
+                return name;
+            }
+        }
+        return null;
+    }
+
+    /** Resolves an in-range integer grouping ordinal against its SELECT list, 
without changing the ordinal. */
+    static Expression groupingOrdinalTarget(Expression key, List<? extends 
NamedExpression> outputs) {
+        if (!(key instanceof IntegerLikeLiteral)) {
+            return null;
+        }
+        BigDecimal ordinal = ((IntegerLikeLiteral) key).getBigDecimalValue();
+        if (ordinal.compareTo(BigDecimal.ONE) < 0 || 
ordinal.compareTo(BigDecimal.valueOf(outputs.size())) > 0) {
+            return null;
+        }
+        NamedExpression item = outputs.get(ordinal.intValueExact() - 1);
+        return item instanceof Alias || item instanceof UnboundAlias ? 
item.child(0) : item;
+    }
+
+    /**
+     * Transforms an ordinary (non-Named) expression list in place-free way; 
returns the
+     * original list when no element changed.
+     *
+     * Used for expression LISTS that are not SELECT items and carry no output 
name/alias
+     * of their own, e.g. a join's conjuncts or a LogicalGenerate's conjuncts. 
Example -
+     * the ON / residual predicates of
+     *
+     *     SELECT... FROM t1 JOIN t2 ON t1.k = t2.k WHERE t2.a > 100 AND t2.b 
= 'x'
+     *
+     * are parameterized one conjunct at a time, so a user query whose literal 
differs
+     * (e.g. t2.a > 200) still structurally matches the baseline. The list 
keeps its
+     * order (no Set normalization - join conjunct order is meaningful).
+     *
+     * Parameter expressions: the expression list to transform
+     * Parameter transform: the per-expression transform (parameterize or 
substitute)
+     * Returns: the transformed list, or the original list instance when 
nothing changed
+     */
+    private static List<Expression> transformExprs(List<Expression> 
expressions,
+            ExprTransform transform) {
+        boolean changed = false;
+        List<Expression> newExpressions = new ArrayList<>(expressions.size());
+        for (Expression expression : expressions) {
+            Expression transformed = transform.apply(expression);
+            newExpressions.add(transformed);
+            if (transformed != expression) {
+                changed = true;
+            }
+        }
+        return changed ? newExpressions : expressions;
+    }
+
+    /**
+     * Transforms a NamedExpression list (SELECT items / aggregate outputs) in 
place-free
+     * way; returns the original list when no element changed.
+     *
+     * A NamedExpression is an expression paired with an output name/alias 
(e.g.
+     * Alias(expr, name)). The transform runs over the WHOLE NamedExpression - 
including
+     * the alias name itself when it is derived from the expression text - so 
its inner
+     * literals are parameterized while the output column name is kept 
consistent with
+     * the (also parameterized) bind side. Example - the SELECT list of
+     *
+     *     SELECT l_returnflag, sum(l_quantity * 2) AS total FROM lineitem
+     *     GROUP BY l_returnflag
+     *
+     * is transformed per item: the plain column l_returnflag is unchanged, 
while the
+     * aggregate item's constant 2 becomes a placeholder
+     * (sum(l_quantity * SpmConstVar(1, 2)) AS total), so a similar user query 
with a
+     * different multiplier still matches. Only a transform result that stays a
+     * NamedExpression is adopted (an Alias must not collapse into a bare 
expression,
+     * which would drop the output name).
+     *
+     * Parameter expressions: the NamedExpression list (projects / aggregate 
outputs) to
+     *                    transform
+     * Parameter transform: the per-expression transform (parameterize or 
substitute)
+     * Returns: the transformed list, or the original list instance when 
nothing changed
+     */
+    private static List<NamedExpression> transformNamed(List<NamedExpression> 
expressions,
+            ExprTransform transform) {
+        boolean changed = false;
+        List<NamedExpression> newExpressions = new 
ArrayList<>(expressions.size());
+        for (int i = 0; i < expressions.size(); i++) {
+            NamedExpression expression = expressions.get(i);
+            // the item's POSITION in the list is part of the placeholder 
identity (see
+            // ExprTransform.enterProjectionItem)
+            transform.enterProjectionItem(i);
+            Expression transformed;
+            try {
+                transformed = transform.apply(expression);
+            } finally {
+                transform.exitProjectionItem();
+            }
+            if (transformed instanceof NamedExpression && transformed != 
expression) {
+                newExpressions.add((NamedExpression) transformed);
+                changed = true;
+            } else {
+                newExpressions.add(expression);
+            }
+        }
+        return changed ? newExpressions : expressions;
+    }
+
+    /**
+     * Transforms a conjunct set in a deterministic order; returns the 
original set when
+     * no element changed. The conjuncts of a filter / having are a Set whose 
iteration
+     * order is not stable across separately parsed trees, so they are ordered 
by SQL
+     * text before transforming: the bind tree and the (separately parsed) 
plan tree of
+     * one baseline then parameterize their conjuncts in the same order and the
+     * placeholder ids stay aligned (no cross-tree id skew for identical 
conjuncts).
+     */
+    private static Set<Expression> transformConjuncts(Set<Expression> 
conjuncts,
+            ExprTransform transform) {
+        List<Expression> ordered = new ArrayList<>(conjuncts);
+        ordered.sort(Comparator.comparing(Expression::toSql));
+        boolean changed = false;
+        Set<Expression> newConjuncts = new LinkedHashSet<>(conjuncts.size());
+        for (Expression conjunct : ordered) {
+            Expression transformed = transform.apply(conjunct);
+            newConjuncts.add(transformed);
+            if (transformed != conjunct) {
+                changed = true;
+            }
+        }
+        return changed ? newConjuncts : conjuncts;
+    }
+
+    // namespace qualification (creation catalog / database).
+
+    /**
+     * Returns a copy of the tree where every UNQUALIFIED relation reference 
(nameParts.size
+     * == 1) that binds to a BASE TABLE is prefixed with the given catalog / 
database, so the
+     * SPM digest / hash key of "FROM t" depends on the query's effective 
namespace. The copy
+     * is only used to compute the matching key / compare against a baseline - 
it is never
+     * analyzed, optimized or executed.
+     *
+     * Without this, "SELECT... FROM t" has the same key under db1 and db2: a 
baseline
+     * captured under db1 would silently match the same text executed under 
db2 and - because
+     * the frozen planSql is fully qualified - keep executing against db1.t.
+     *
+     * A reference to a CTE alias is NOT prefixed: its binding comes from the 
WITH clause of
+     * the query itself and therefore means the same thing in every database 
(prefixing it
+     * made "WITH c AS (...) SELECT * FROM c" match only in the database it 
was created in).
+     * Whether a single-part name is a CTE reference is decided with the 
analyzer's scoping
+     * rules (AnalyzeCTE): an alias body sees the aliases defined before it, 
plus itself when
+     * it is a real recursive CTE (WITH RECURSIVE plus a self-reference in its 
body); a CTE's
+     * main query sees every alias of that WITH; nested WITH nodes extend the 
enclosing
+     * scope; expression subqueries inherit the scope of the point they appear 
in
+     * (SubExprAnalyzer). A name that is NOT a visible alias - including a 
forward reference
+     * to a later alias and a self reference under a plain (non-RECURSIVE) 
WITH, both of which
+     * bind as base tables - is always prefixed, so this can only narrow the 
match key, never
+     * make a base-table reference namespace-independent.
+     *
+     * Parameter plan: the parsed (unbound) tree
+     * Parameter catalog: the effective catalog, may be null / empty (then 
only the db is prefixed)
+     * Parameter db: the effective database; when null / empty the tree is 
returned as-is
+     * Returns: the qualified tree (a rebuilt copy; the argument is not 
modified)
+     */
+    public static LogicalPlan namespaceQualified(LogicalPlan plan, String 
catalog, String db) {
+        boolean hasCatalog = catalog != null && !catalog.isEmpty();
+        boolean hasDb = db != null && !db.isEmpty();
+        // A TWO-part name (db.t) is relative to the current CATALOG, not to 
the current
+        // database, so it must be prefixed whenever the catalog is known - a 
session can
+        // switch to cat1 WITHOUT a USE db, and an unprefixed db.t would key 
the same text
+        // under cat2 to the same digest while the frozen SQL still reads 
cat1.db.t. Only
+        // when NEITHER the catalog nor the db is known can nothing be made
+        // namespace-independent.
+        if (plan == null || (!hasCatalog && !hasDb)) {
+            return plan;
+        }
+        Plan result = plan.accept(new TreeTransformer(), new 
QualifyTransform(catalog, db));
+        return result instanceof LogicalPlan ? (LogicalPlan) result : plan;
+    }
+
+    /**
+     * Namespace-qualification scope: prefixes single-part base-table 
references with the
+     * effective [catalog, db] and keeps references to the CTE aliases visible 
at the current
+     * point verbatim. Immutable: entering a CTE scope returns a new instance 
whose visible
+     * set is the enclosing one plus the aliases visible in that scope.
+     */
+    private static final class QualifyTransform implements ScopedTransform {
+        private final String catalog;
+        private final String db;
+        /** normalized names of the CTE aliases visible at the current point */
+        private final Set<String> visibleCtes;
+
+        QualifyTransform(String catalog, String db) {
+            this(catalog, db, Collections.emptySet());
+        }
+
+        private QualifyTransform(String catalog, String db, Set<String> 
visibleCtes) {
+            this.catalog = catalog;
+            this.db = db;
+            this.visibleCtes = visibleCtes;
+        }
+
+        @Override
+        public Expression apply(Expression expr) {
+            return qualifyExpression(expr, this);
+        }
+
+        @Override
+        public ExprTransform enterCteMain(LogicalCTE<? extends Plan> cte) {
+            Set<String> extended = new LinkedHashSet<>(visibleCtes);
+            for (LogicalSubQueryAlias<Plan> alias : cte.getAliasQueries()) {
+                extended.add(normalizeCteName(alias.getAlias()));
+            }
+            return new QualifyTransform(catalog, db, 
Collections.unmodifiableSet(extended));
+        }
+
+        @Override
+        public ExprTransform enterCteAlias(LogicalCTE<? extends Plan> cte, int 
aliasIndex) {
+            List<LogicalSubQueryAlias<Plan>> aliases = cte.getAliasQueries();
+            Set<String> extended = new LinkedHashSet<>(visibleCtes);
+            for (int i = 0; i < aliasIndex; i++) {
+                extended.add(normalizeCteName(aliases.get(i).getAlias()));
+            }
+            // a self reference binds to the WITH clause only in a real 
recursive CTE;
+            // under a plain WITH it is an ordinary base-table reference
+            LogicalSubQueryAlias<Plan> alias = aliases.get(aliasIndex);
+            if (cte.isRecursive() && alias.isRecursiveCte()) {
+                extended.add(normalizeCteName(alias.getAlias()));
+            }
+            return new QualifyTransform(catalog, db, 
Collections.unmodifiableSet(extended));
+        }
+
+        /** Prefixes a one- or two-part relation with the effective namespace. 
*/
+        Plan qualify(UnboundRelation relation) {
+            List<String> parts = relation.getNameParts();
+            if (parts.size() > 2) {
+                return relation; // fully qualified (catalog.db.table): 
nothing to add
+            }
+            if (parts.size() == 1 && isVisibleCte(parts.get(0))) {
+                return relation; // bound by a WITH clause, not a base-table 
reference
+            }
+            // A one-part name is relative to the current db, but a TWO-part 
name is only
+            // relative to the current CATALOG ("db.t" means 
current_catalog.db.t):
+            // leaving "db.t" verbatim would let a baseline created in cat1 
match the
+            // same text executed in cat2, after which the frozen 
fully-qualified replay
+            // keeps reading cat1.db.t. Only three-part names are complete.
+            List<String> qualified = new ArrayList<>(3);
+            if (parts.size() == 1) {
+                if (db == null || db.isEmpty()) {
+                    // A one-part name needs the DATABASE to become absolute; 
prefixing only
+                    // the catalog would turn the table name into a database 
name.
+                    return relation;
+                }
+                if (catalog != null && !catalog.isEmpty()) {
+                    qualified.add(catalog);
+                }
+                qualified.add(db);
+            } else {
+                // two-part name: the catalog completes it
+                if (catalog == null || catalog.isEmpty()) {
+                    return relation;
+                }
+                qualified.add(catalog);
+            }
+            qualified.addAll(parts);
+            try {
+                return copyWithNameParts(relation, qualified);
+            } catch (RuntimeException e) {
+                return relation;
+            }
+        }
+
+        /**
+         * Rebuilds the relation with new name parts while preserving EVERY 
scan modifier
+         * (partition list, tablet ids, hints, sample, index, scan params, 
snapshot):
+         * dropping them here would hide a PARTITION(...) / TABLESAMPLE / FOR 
VERSION
+         * selection from the Level 3 comparison and allow a baseline captured 
under a
+         * different selection to match.
+         */
+        private static UnboundRelation copyWithNameParts(UnboundRelation 
relation,
+                List<String> nameParts) {
+            return new UnboundRelation(relation.getRelationId(), nameParts,
+                    relation.getPartNames(), relation.isTempPart(), 
relation.getTabletIds(),
+                    relation.getHints(), relation.getTableSample(), 
relation.getIndexName(),
+                    relation.getScanParams(), relation.getIndexInSqlString(),
+                    relation.getTableSnapshot());
+        }
+
+        private boolean isVisibleCte(String name) {
+            return !visibleCtes.isEmpty() && 
visibleCtes.contains(normalizeCteName(name));
+        }
+    }
+
+    /** Mirrors the analyzer's CTE name comparison 
(CTEContext.findCTEContext). */
+    private static String normalizeCteName(String name) {
+        return lowerCaseTableNamesPolicy() != 0 ? 
name.toLowerCase(Locale.ROOT) : name;
+    }
+
+    /**
+     * The catalog's identifier case policy (see 
GlobalVariable.lowerCaseTableNames): the
+     * analyzer resolves relation names and subquery aliases through
+     * ExpressionAnalyzer.sameTableName, which compares case-INSENSITIVELY 
when the
+     * policy is 1.
+     */
+    private static int lowerCaseTableNamesPolicy() {
+        int lowerCaseTableNames = GlobalVariable.lowerCaseTableNames;
+        ConnectContext ctx = ConnectContext.get();
+        if (ctx != null && ctx.getCurrentCatalog() != null) {
+            lowerCaseTableNames = 
ctx.getCurrentCatalog().getLowerCaseTableNames();
+        }
+        return lowerCaseTableNames;
+    }
+
+    /**
+     * Whether a qualifier the CALLER wrote names a relation / subquery alias, 
under the SAME
+     * case policy the analyzer applies (see ExpressionAnalyzer.sameTableName).
+     *
+     * The comparison used to be case-SENSITIVE: with lower_case_table_names = 
1 the analyzer
+     * binds SELECT d.* FROM (SELECT k + 1 AS x FROM t) D (the parser keeps 
the alias D as
+     * written, and normal binding matches it case-insensitively), while the 
star expansion
+     * rejected that relation - starExpansionForStar threw and BOTH replay 
paths skipped the
+     * candidate, so the query could not use even its identical baseline.
+     *
+     * Parameter written: the name component the caller wrote
+     * Parameter resolved: the relation's / alias's own name
+     * Returns: whether the two name the same relation
+     */
+    private static boolean sameRelationName(String written, String resolved) {
+        return lowerCaseTableNamesPolicy() != 0
+                ? written.equalsIgnoreCase(resolved)
+                : written.equals(resolved);
+    }
+
+    /**
+     * Qualifies the relations of every subquery plan owned by an expression, 
recursively
+     * (IN / scalar / EXISTS subqueries anywhere in the tree). The subquery 
inherits the
+     * qualification scope of the point it appears in, i.e. the CTE aliases 
visible there.
+     */
+    private static Expression qualifyExpression(Expression expr, 
QualifyTransform transform) {
+        if (expr instanceof SubqueryExpr) {
+            LogicalPlan subPlan = ((SubqueryExpr) expr).getQueryPlan();
+            Plan qualified = subPlan.accept(new TreeTransformer(), transform);
+            if (qualified instanceof LogicalPlan && qualified != subPlan) {
+                return ((SubqueryExpr) expr).withSubquery((LogicalPlan) 
qualified);
+            }
+            return expr;
+        }
+        if (expr instanceof UnboundStar) {
+            // SELECT * REPLACE((SELECT max(v) FROM u) AS k): the replacement 
payloads sit
+            // OUTSIDE children, so the generic recursion below never reached 
the
+            // subquery plan they own. Creating a baseline in db1 and running 
the same
+            // text under db2 kept the raw "u": digest and the Level-3 check 
matched (the
+            // outer table was fixed) while the frozen SQL still read db1.u, 
so replay
+            // returned db1's value. Rebuild the payloads under the CURRENT 
namespace and
+            // CTE scope.
+            UnboundStar star = (UnboundStar) expr;
+            List<NamedExpression> replaced = star.getReplacedAlias();
+            if (replaced.isEmpty()) {
+                return expr;
+            }
+            boolean changed = false;
+            List<NamedExpression> newReplaced = new 
ArrayList<>(replaced.size());
+            for (NamedExpression replacement : replaced) {
+                Expression newReplacement = qualifyExpression(replacement, 
transform);
+                newReplaced.add(newReplacement instanceof NamedExpression
+                        ? (NamedExpression) newReplacement : replacement);
+                changed |= newReplacement != replacement;
+            }
+            return changed ? new UnboundStar(star.getQualifier(), 
star.getExceptedSlots(),
+                    newReplaced, star.getIndexInSqlString()) : expr;
+        }
+        if (expr.children().isEmpty()) {
+            return expr;
+        }
+        boolean changed = false;
+        List<Expression> newChildren = new ArrayList<>(expr.children().size());
+        for (Expression child : expr.children()) {
+            Expression newChild = qualifyExpression(child, transform);
+            newChildren.add(newChild);
+            if (newChild != child) {
+                changed = true;
+            }
+        }
+        return changed ? expr.withChildren(newChildren) : expr;
+    }
+
+    /**
+     * Removes only SET_VAR hints from a replay plan, including CTE bodies and 
expression subqueries.
+     * Both frozen-text replay and parameterized-tree fallback use this 
cleanup before attaching the caller's
+     * own settings. Matching compares the caller with bindSql; planSql may 
carry different SET_VAR payloads.
+     * Reading or replaying that captured text must not apply its settings to 
the caller.
+     *
+     * Other hints, including ORDERED and LEADING, remain available to enforce 
plan choices. A wrapper with
+     * no remaining hints is removed. Scan selectors and join-distribution 
hints are preserved as well.
+     */
+    public static LogicalPlan stripSetVarHints(LogicalPlan plan) {
+        if (plan == null) {
+            return null;
+        }
+        Plan result = plan.accept(new SetVarHintStripper(), 
SET_VAR_HINT_STRIP_EXPR);
+        LogicalPlan stripped = result instanceof LogicalPlan ? (LogicalPlan) 
result : plan;
+        // The plan-level stripper above rebuilds only PLAN children, and an 
expression-owned
+        // scalar subquery (a projection item, a HAVING / filter predicate, a 
* REPLACE
+        // payload) keeps its own query plan OUTSIDE children: the SET_VAR 
hint inside it
+        // survived the peel, and the ordinary replay analysis then applied 
the BASELINE's
+        // time_zone on top of a caller that came with no hint at all - 
from_unixtime
+        // returned the captured zone's values. SET_VAR_HINT_STRIP_EXPR 
re-enters
+        // those subquery plans (see its declaration), so one more rebuild 
pass reaches every
+        // expression-owned plan. Both passes keep every NON-SET_VAR hint 
(INDEX / BROADCAST
+        // / SHUFFLE), which is what the frozen replay exists for.
+        return transform(stripped, SET_VAR_HINT_STRIP_EXPR);
+    }
+
+    /**
+     * TreeTransformer that removes the SET_VAR payloads from every 
LogicalSelectHint
+     * wrapper (whilst descending into nested blocks and keeping the other 
hints). A
+     * wrapper left without hints is dropped entirely, so a hint-free subtree 
keeps its
+     * original shape.
+     */
+    private static class SetVarHintStripper extends TreeTransformer {
+        @Override
+        public Plan visit(Plan plan, ExprTransform transform) {
+            if (!(plan instanceof LogicalSelectHint)) {
+                return super.visit(plan, transform);
+            }
+            LogicalSelectHint<?> selectHint = (LogicalSelectHint<?>) plan;
+            Plan child = selectHint.child(0);
+            if (child == null) {
+                return plan;
+            }
+            Plan strippedChild = child.accept(this, transform);
+            List<SelectHint> kept = new 
ArrayList<>(selectHint.getHints().size());
+            for (SelectHint hint : selectHint.getHints()) {
+                if (!(hint instanceof SelectHintSetVar)) {
+                    kept.add(hint);
+                }
+            }
+            if (kept.isEmpty()) {
+                return strippedChild;
+            }
+            return new LogicalSelectHint<>(ImmutableList.copyOf(kept), 
strippedChild);
+        }
+    }
+
+    // creator-context expression detection.
+
+    /** Direct supported context functions can be deferred; variables and 
alias bodies cannot. */
+    static boolean containsUnsupportedCreatorContextExpression(LogicalPlan 
plan) {
+        return containsCreatorContextExpression(plan, true);
+    }
+
+    /**
+     * Whether the tree references a statement/session context expression, 
including
+     * session variables, identity functions and statement clocks. The full 
detector
+     * remains strict for transitive alias UDF bodies, whose dynamic calls are 
not
+     * visible in the submitted SQL. Direct supported builtin calls instead 
use the
+     * unsupported-context detector above and the capture-time preservation 
policy.
+     * Replay evaluates a preserved call with the caller's own statement 
context.
+     * The strict detector also remains useful to inspect the original parsed 
tree.
+     *
+     * Parameter plan: the parsed (unbound) tree
+     * Returns: true when such an expression is found anywhere - every 
subquery plan
+     *         (IN / EXISTS / scalar, coercions included), CTE bodies and an 
ASOF join's
+     *         out-of-band MATCH_CONDITION are scanned
+     */
+    public static boolean containsCreatorContextExpression(LogicalPlan plan) {
+        return containsCreatorContextExpression(plan, false);
+    }
+
+    private static boolean containsCreatorContextExpression(LogicalPlan plan, 
boolean allowDeferred) {
+        if (plan == null) {
+            return false;
+        }
+        return anyPlan(plan, node -> {
+            if (node instanceof LogicalUsingJoin) {
+                // matchCondition lives outside children and getExpressions
+                Optional<Expression> matchCondition =
+                        ((LogicalUsingJoin<?, ?>) node).getMatchCondition();
+                if (matchCondition.isPresent()
+                        && 
containsCreatorContextExpression(matchCondition.get(), true, allowDeferred)) {
+                    return true;
+                }
+            }
+            for (Expression expr : node.getExpressions()) {
+                if (containsCreatorContextExpression(expr, false, 
allowDeferred)) {
+                    return true;
+                }
+            }
+            return false;
+        });
+    }
+
+    /** Whether an expression tree contains a creator-context expression. */
+    public static boolean containsCreatorContextExpression(Expression expr) {
+        return containsCreatorContextExpression(expr, true, false);
+    }
+
+    private static boolean containsCreatorContextExpression(Expression expr, 
boolean descendSubqueries,
+            boolean allowDeferred) {
+        if (expr instanceof Variable || expr instanceof UnboundVariable) {
+            return true;
+        }
+        if (SPMContextFunctions.isCandidate(expr) && !allowDeferred) {
+            return true;
+        }
+        if (expr instanceof UnboundStar) {
+            // SELECT * REPLACE(f(@v) AS v): the replaced-alias payloads are 
NOT expression
+            // children of the star, so the recursive walk below never reached 
them and the
+            // statement passed the guard. Scan the payloads explicitly.
+            for (NamedExpression replaced : ((UnboundStar) 
expr).getReplacedAlias()) {
+                if (containsCreatorContextExpression(replaced, 
descendSubqueries, allowDeferred)) {
+                    return true;
+                }
+            }
+        }
+        if (descendSubqueries && expr instanceof SubqueryExpr) {
+            if (containsCreatorContextExpression(((SubqueryExpr) 
expr).getQueryPlan(), allowDeferred)) {
+                return true;
+            }
+        }
+        for (Expression child : expr.children()) {
+            if (containsCreatorContextExpression(child, descendSubqueries, 
allowDeferred)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Whether the tree REFERENCES an alias UDF whose RESOLVED BODY 
(transitively) carries a
+     * replay-time context expression (see
+     * 
org.apache.doris.nereids.spm.SPMPlanner.rejectCreatorContextExpressions).
+     *
+     * The parsed-tree check above only sees the CALL: CREATE ALIAS FUNCTION 
f() WITH
+     * PARAMETER() AS current_user() is an ordinary UnboundFunction in the 
bind text, and its
+     * registry-owned body enters the plan LATER, when analysis INLINES the 
alias body. The
+     * creator-context optimization of the capture then folds that CurrentUser 
into the CREATOR's
+     * identity (FoldConstantRuleOnFE, no NeedSessionVarGuard on CurrentUser) 
and the frozen
+     * planSql persists it - while matching still compares the user's own f() 
text, so a GLOBAL
+     * baseline served every other user the creating identity. The body is 
therefore resolved
+     * here, through the registry and TRANSITIVELY (an alias body may call 
another alias), and
+     * inspected with the same classifier.
+     *
+     * Only ALIAS UDFs are expanded: a Java / Python UDF's body is compiled 
code, not SQL.
+     *
+     * Parameter ctx: the creating session (supplies the CURRENT database for 
an unqualified call)
+     * Parameter plan: the parsed (unbound) tree
+     * Returns: whether a resolved alias body contains a replay-time context 
expression
+     */
+    public static boolean containsCreatorContextInAliasBodies(ConnectContext 
ctx,
+            LogicalPlan plan) {
+        return containsCreatorContextInAliasBodies(ctx, plan, new HashSet<>());
+    }
+
+    /**
+     * As containsCreatorContextInAliasBodies(ConnectContext, LogicalPlan), 
carrying the
+     * resolved scopes already expanded on this path (an alias body may 
reference a subquery).
+     */
+    private static boolean containsCreatorContextInAliasBodies(ConnectContext 
ctx, LogicalPlan plan,
+            Set<String> expanding) {
+        if (plan == null) {
+            return false;
+        }
+        return anyPlan(plan, node -> {
+            if (node instanceof LogicalUsingJoin) {
+                Optional<Expression> matchCondition =
+                        ((LogicalUsingJoin<?, ?>) node).getMatchCondition();
+                if (matchCondition.isPresent() && 
containsCreatorContextInAliasBodies(ctx,
+                        matchCondition.get(), expanding)) {
+                    return true;
+                }
+            }
+            for (Expression expr : node.getExpressions()) {
+                if (containsCreatorContextInAliasBodies(ctx, expr, expanding, 
false)) {
+                    return true;
+                }
+            }
+            return false;
+        });
+    }
+
+    /** Whether one expression tree references an alias body with a context 
expression. */
+    private static boolean containsCreatorContextInAliasBodies(ConnectContext 
ctx,
+            Expression expr, Set<String> expanding) {
+        return containsCreatorContextInAliasBodies(ctx, expr, expanding, true);
+    }
+
+    private static boolean containsCreatorContextInAliasBodies(ConnectContext 
ctx,
+            Expression expr, Set<String> expanding, boolean descendSubqueries) 
{
+        if (expr == null) {
+            return false;
+        }
+        if (expr instanceof UnboundFunction) {
+            UnboundFunction function = (UnboundFunction) expr;
+            String scope = function.getDbName() == null || 
function.getDbName().isEmpty()
+                    ? (ctx == null || ctx.getDatabase() == null ? null : 
ctx.getDatabase())
+                    : function.getDbName();
+            String name = function.getName() == null ? ""
+                    : function.getName().toLowerCase(Locale.ROOT);
+            String key = (scope == null ? "" : scope.toLowerCase(Locale.ROOT)) 
+ '.' + name;
+            if (expanding.add(key)) {
+                try {
+                    for 
(org.apache.doris.nereids.trees.expressions.functions.udf.AliasUdf body
+                            : aliasUdfBodies(scope, function.getName())) {
+                        if 
(containsCreatorContextExpression(body.getUnboundFunction())
+                                || containsCreatorContextInAliasBodies(ctx,
+                                        body.getUnboundFunction(), expanding)) 
{
+                            return true;
+                        }
+                    }
+                } finally {
+                    expanding.remove(key);
+                }
+            }
+        }
+        if (expr instanceof UnboundStar) {
+            for (NamedExpression replaced : ((UnboundStar) 
expr).getReplacedAlias()) {
+                if (containsCreatorContextInAliasBodies(ctx, replaced, 
expanding, descendSubqueries)) {
+                    return true;
+                }
+            }
+        }
+        if (descendSubqueries && expr instanceof SubqueryExpr) {
+            if (containsCreatorContextInAliasBodies(ctx,
+                    ((SubqueryExpr) expr).getQueryPlan(), expanding)) {
+                return true;
+            }
+        }
+        for (Expression child : expr.children()) {
+            if (containsCreatorContextInAliasBodies(ctx, child, expanding, 
descendSubqueries)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * The ALIAS UDF definitions one unqualified / qualified call resolves to 
(see
+     * containsCreatorContextInAliasBodies).
+     *
+     * Parameter scope: the resolved lookup scope (the written qualifier, else 
the current database)
+     * Parameter name: the written function name
+     * Returns: the alias bodies (never null)
+     */
+    private static 
List<org.apache.doris.nereids.trees.expressions.functions.udf.AliasUdf>
+            aliasUdfBodies(String scope, String name) {
+        
List<org.apache.doris.nereids.trees.expressions.functions.udf.AliasUdf> bodies =
+                new ArrayList<>();
+        if (name == null || name.isEmpty()) {
+            return bodies;
+        }
+        try {
+            for 
(org.apache.doris.nereids.trees.expressions.functions.FunctionBuilder builder
+                    : 
org.apache.doris.catalog.Env.getCurrentEnv().getFunctionRegistry()
+                            .findUdfBuilder(scope, name)) {
+                if (builder instanceof 
org.apache.doris.nereids.trees.expressions.functions.udf
+                        .AliasUdfBuilder) {
+                    
org.apache.doris.nereids.trees.expressions.functions.udf.AliasUdf body =
+                            
((org.apache.doris.nereids.trees.expressions.functions.udf
+                                    .AliasUdfBuilder) builder).getAliasUdf();
+                    if (body != null) {
+                        bodies.add(body);
+                    }
+                }
+            }
+        } catch (RuntimeException e) {
+            // a registry hiccup cannot certify the body: the direct 
parsed-tree check above
+            // still covers the caller's own text
+            return bodies;
+        }
+        return bodies;
+    }
+
+    // whole-tree placeholder detection.
+
+    /**
+     * Whether the plan tree (including filters/having/projections and every 
subquery
+     * plan reachable from an expression) still contains an unbound 
placeholder.
+     *
+     * Parameter plan: the plan tree to scan
+     * Returns: true when a SpmConstVar / SpmConstList is found anywhere
+     */
+    public static boolean containsPlaceholder(LogicalPlan plan) {
+        return plan.accept(new PlaceholderScanVisitor(), null);
+    }
+
+    /** Plan visitor that scans every node's expressions (and subquery plans) 
for placeholders. */
+    private static class PlaceholderScanVisitor extends PlanVisitor<Boolean, 
Void> {
+        @Override
+        public Boolean visit(Plan plan, Void context) {
+            if (plan instanceof LogicalUsingJoin) {
+                // The USING join's matchCondition is OUT OF BAND: it is 
neither a child
+                // nor in getExpressions. A bind/plan pair whose ASOF boundary 
differs
+                // only in an interval literal leaves a plan-only id in this 
field; the
+                // in-memory fallback substitutes the original 
LogicalUsingJoin, so a
+                // visitor that only walks USING slots + children would return 
an invalid
+                // tree (an unresolved placeholder id) to analysis.
+                Optional<Expression> matchCondition =
+                        ((LogicalUsingJoin<?, ?>) plan).getMatchCondition();
+                if (matchCondition.isPresent() && 
containsPlaceholder(matchCondition.get())) {
+                    return true;
+                }
+            }
+            for (Expression expr : plan.getExpressions()) {
+                if (containsPlaceholder(expr)) {
+                    return true;
+                }
+            }
+            for (Plan child : plan.children()) {
+                if (child.accept(this, context)) {
+                    return true;
+                }
+            }
+            return false;
+        }
+
+        @Override
+        public Boolean visitLogicalCTE(LogicalCTE<? extends Plan> cte, Void 
context) {
+            if (cte.child(0) != null && cte.child(0).accept(this, context)) {
+                return true;
+            }
+            for (LogicalSubQueryAlias<Plan> aliasQuery : 
cte.getAliasQueries()) {
+                if (aliasQuery.accept(this, context)) {
+                    return true;
+                }
+            }
+            return false;
+        }
+    }
+
+    /**
+     * Whether an expression tree (recursing into subquery plans) contains a 
placeholder.
+     */
+    public static boolean containsPlaceholder(Expression expr) {
+        if (expr instanceof SpmConstVar || expr instanceof SpmConstList) {
+            return true;
+        }
+        if (expr instanceof SubqueryExpr) {
+            if (containsPlaceholder(((SubqueryExpr) expr).getQueryPlan())) {
+                return true;
+            }
+        }
+        for (Expression child : expr.children()) {
+            if (containsPlaceholder(child)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    // Frozen-tree placeholder detection.
+
+    /**
+     * Whether a plan tree (re-parsed from the frozen planSql) still carries an
+     * unsubstituted placeholder call (_spm_const_var(id) / 
_spm_const_list(id) as a raw
+     * UnboundFunction). Such a call would reach the analyzer as an 
unregistered function
+     * and fail, so the rewrite must reject the tree instead of returning it.
+     *
+     * Parameter plan: the frozen (re-parsed) plan tree to scan
+     * Returns: true when an unsubstituted placeholder call is found anywhere
+     */
+    public static boolean containsFrozenPlaceholder(Plan plan) {
+        return plan.accept(new FrozenPlaceholderScanVisitor(), null);
+    }
+
+    /**
+     * Plan visitor that scans every node's expressions (and subquery plans) 
for
+     * unsubstituted frozen-tree placeholder calls.
+     */
+    private static class FrozenPlaceholderScanVisitor extends 
PlanVisitor<Boolean, Void> {
+        @Override
+        public Boolean visit(Plan plan, Void context) {
+            if (plan instanceof LogicalUsingJoin) {
+                // Same out-of-band field as PlaceholderScanVisitor: an 
unresolved
+                // placeholder id inside the ASOF boundary must reject the 
fallback tree.
+                Optional<Expression> matchCondition =
+                        ((LogicalUsingJoin<?, ?>) plan).getMatchCondition();
+                if (matchCondition.isPresent() && 
containsFrozenPlaceholder(matchCondition.get())) {
+                    return true;
+                }
+            }
+            for (Expression expr : plan.getExpressions()) {
+                if (containsFrozenPlaceholder(expr)) {
+                    return true;
+                }
+            }
+            for (Plan child : plan.children()) {
+                if (child.accept(this, context)) {
+                    return true;
+                }
+            }
+            return false;
+        }
+
+        @Override
+        public Boolean visitLogicalCTE(LogicalCTE<? extends Plan> cte, Void 
context) {
+            if (cte.child(0) != null && cte.child(0).accept(this, context)) {
+                return true;
+            }
+            for (LogicalSubQueryAlias<Plan> aliasQuery : 
cte.getAliasQueries()) {
+                if (aliasQuery.accept(this, context)) {
+                    return true;
+                }
+            }
+            return false;
+        }
+    }
+
+    /** Whether an expression tree contains an unsubstituted frozen-tree 
placeholder call. */
+    public static boolean containsFrozenPlaceholder(Expression expr) {
+        if (SPMFrozenTreeReplacer.isUnsubstitutedPlaceholder(expr)) {
+            return true;
+        }
+        if (expr instanceof SubqueryExpr) {
+            if (containsFrozenPlaceholder(((SubqueryExpr) 
expr).getQueryPlan())) {
+                return true;
+            }
+        }
+        for (Expression child : expr.children()) {
+            if (containsFrozenPlaceholder(child)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    // whole-tree structural check (Level 3).
+
+    /**
+     * Compares a parameterized bind tree with the user's original tree node 
by node and
+     * expression by expression. Placeholder values are extracted from the 
user side into
+     * placeholderValues (a repeated id must resolve to the same user value).
+     *
+     * Parameter bindPlan: the parameterized bind tree (contains placeholders)
+     * Parameter userPlan: the user's original tree (contains real literals)
+     * Parameter placeholderValues: placeholder id -> user value (filled in 
here)
+     * Returns: whether the two trees match
+     */
+    public static boolean check(LogicalPlan bindPlan, LogicalPlan userPlan,
+            Map<Long, Expression> placeholderValues) {
+        PlaceholderBindings bindings = 
PlaceholderBindings.track(placeholderValues);
+        MatchAttempt attempt = MatchAttempt.begin();
+        if (attempt == null) {
+            // a NESTED match (a subquery plan reached from the visitor) rides 
the
+            // enclosing attempt: its choices and the outer tree's share one 
placeholder
+            // map, so only the OUTERMOST driver may retry
+            return checkPlan(bindPlan, userPlan, bindings, false);
+        }
+        try {
+            int entryState = bindings.checkpoint();
+            for (int i = 0; i < MatchAttempt.MAX_ATTEMPTS; i++) {
+                attempt.resetPass();
+                if (checkPlan(bindPlan, userPlan, bindings, false)) {
+                    return true;
+                }
+                bindings.rollback(entryState);
+                if (!attempt.advance()) {
+                    return false;
+                }
+            }
+            bindings.clear();
+            return false;
+        } finally {
+            attempt.end();
+        }
+    }
+
+    /**
+     * Level 3 check for one subquery-EXPRESSION plan pair. Inside a 
subquery's plan the
+     * LIMIT / OFFSET fields are compared EXACTLY (see checkPlan): they are 
plain long
+     * fields that mergeLimits cannot merge (the subquery plan does not sit on 
a
+     * plan-child path of the main tree), so a "subquery LIMIT 2" query must 
not match a
+     * baseline captured with a different subquery limit and replay the 
captured value.
+     */
+    public static boolean checkSubqueryPlan(LogicalPlan bindPlan, LogicalPlan 
userPlan,
+            Map<Long, Expression> placeholderValues) {
+        return checkPlan(bindPlan, userPlan, 
PlaceholderBindings.track(placeholderValues), true);
+    }
+
+    /** Node-by-node recursive structural check. */
+    private static boolean checkPlan(Plan bind, Plan user, Map<Long, 
Expression> placeholderValues,
+            boolean insideSubquery) {
+        if (bind.getClass() != user.getClass()) {
+            return false;
+        }
+        // LIMIT / OFFSET are plain long fields, not expressions, so the 
generic node check
+        // cannot see them. A top-level LIMIT is adopted from the user query 
later
+        // (mergeLimits); a LIMIT inside a subquery expression's plan is NOT 
reachable by
+        // that merge, so it must take part in the match exactly - otherwise a 
query with
+        // "subquery LIMIT 2" would replay a baseline captured with "subquery 
LIMIT 1"
+        // and return a truncated result.
+        if (insideSubquery && bind instanceof LogicalLimit && user instanceof 
LogicalLimit) {
+            if (((LogicalLimit<?>) bind).getLimit() != ((LogicalLimit<?>) 
user).getLimit()
+                    || ((LogicalLimit<?>) bind).getOffset() != 
((LogicalLimit<?>) user).getOffset()) {
+                return false;
+            }
+        }
+        // LogicalTopN carries its ORDER BY... LIMIT / OFFSET pair as a node 
of its own (it
+        // does not extend LogicalLimit). Inside a nested query block the 
positional merge
+        // gives up as soon as the frozen join order differs from the user's: 
the limited
+        // derived table then pairs with the OTHER relation, the 
class-mismatch guard
+        // leaves the captured TopN untouched and the replay returns the 
captured slice.
+        // Comparing the pair exactly keeps such a query from matching at all.
+        if (insideSubquery && bind instanceof LogicalTopN && user instanceof 
LogicalTopN) {
+            if (((LogicalTopN<?>) bind).getLimit() != ((LogicalTopN<?>) 
user).getLimit()
+                    || ((LogicalTopN<?>) bind).getOffset() != 
((LogicalTopN<?>) user).getOffset()) {
+                return false;
+            }
+        }
+        // LogicalRepeat.getExpressions flattens its grouping sets. Compare 
their
+        // boundaries before matching the member expressions, including empty 
sets.
+        if (bind instanceof LogicalRepeat) {
+            List<List<Expression>> bindSets = ((LogicalRepeat<?>) 
bind).getGroupingSets();
+            List<List<Expression>> userSets = ((LogicalRepeat<?>) 
user).getGroupingSets();
+            if (bindSets.size() != userSets.size()) {
+                return false;
+            }
+            for (int i = 0; i < bindSets.size(); i++) {
+                if (bindSets.get(i).size() != userSets.get(i).size()) {
+                    return false;
+                }
+            }
+        }
+        // compare this node's expressions first (bind side is parameterized)
+        if (!checkNodeExpressions(bind, user, placeholderValues)) {
+            return false;
+        }
+        List<Plan> bindChildren = bind.children();
+        List<Plan> userChildren = user.children();
+        if (bindChildren.size() != userChildren.size()) {
+            return false;
+        }
+        for (int i = 0; i < bindChildren.size(); i++) {
+            // A derived table (LogicalSubQueryAlias) opens a nested query 
block: its own
+            // LIMIT / OFFSET cannot rely on the positional merge (mergeLimits 
gives up on
+            // a class mismatch - e.g. a frozen join order that differs from 
the user's -
+            // and would silently keep the captured slice), so nested limits 
are part of
+            // the exact match (see the LIMIT check above). A SET OPERAND is a 
query block
+            // of its own too: (SELECT k FROM t1 LIMIT 1) UNION ALL SELECT k 
FROM t2
+            // parses as UnionAll(Limit(1, t1), t2) with no SubQueryAlias 
around that
+            // limit, and toDigest masks the limit value - without this the 
frozen set
+            // (wrapped as a derived table at replay) kept the captured LIMIT 
1 while the
+            // user asked LIMIT 2, silently losing a t1 row.
+            boolean childInsideSubquery = insideSubquery || bind instanceof 
LogicalSubQueryAlias
+                    || bind instanceof LogicalSetOperation;
+            if (!checkPlan(bindChildren.get(i), userChildren.get(i), 
placeholderValues,
+                    childInsideSubquery)) {
+                return false;
+            }
+        }
+        // CTE bodies are not children - compare them explicitly
+        if (bind instanceof LogicalCTE && user instanceof LogicalCTE) {
+            LogicalCTE<?> bindCte = (LogicalCTE<?>) bind;
+            LogicalCTE<?> userCte = (LogicalCTE<?>) user;
+            // WITH RECURSIVE changes how a self-reference binds (work table 
vs base
+            // table): the same syntax against a same-named real table means 
different
+            // queries, so the recursion flag is part of the identity
+            if (bindCte.isRecursive() != userCte.isRecursive()) {
+                return false;
+            }
+            List<LogicalSubQueryAlias<Plan>> bindAliases = 
bindCte.getAliasQueries();
+            List<LogicalSubQueryAlias<Plan>> userAliases = 
userCte.getAliasQueries();
+            if (bindAliases.size() != userAliases.size()) {
+                return false;
+            }
+            for (int i = 0; i < bindAliases.size(); i++) {
+                // CTE bodies are nested query blocks: their LIMIT / OFFSET 
are compared
+                // exactly (the positional LIMIT merge cannot reach them 
reliably)
+                if (!checkPlan(bindAliases.get(i), userAliases.get(i), 
placeholderValues, true)) {
+                    return false;
+                }
+            }
+        }
+        return true;
+    }
+
+    /**
+     * Compares slot names containing the parser-generated $c$ prefix and a 
numeric suffix. The prefix before $c$
+     * must agree; the counter value is ignored because separately parsed or 
analyzed trees can allocate different
+     * counters. Both suffixes must contain digits only.
+     */
+    private static boolean sameAutoGeneratedUnboundSlot(Expression bind, 
Expression user) {
+        if (!(bind instanceof UnboundSlot) || !(user instanceof UnboundSlot)) {
+            return false;
+        }
+        String bindName = ((UnboundSlot) bind).getName();
+        String userName = ((UnboundSlot) user).getName();
+        int bindIdx = bindName == null ? -1 : bindName.indexOf("$c$");
+        int userIdx = userName == null ? -1 : userName.indexOf("$c$");
+        if (bindIdx <= 0 || userIdx <= 0) {
+            return false;
+        }
+        // both sides carry "<qualifier>.$c$<digits>": the qualifier must 
match, the
+        // ordinal is the parser's internal counter
+        return bindName.substring(0, bindIdx).equals(userName.substring(0, 
userIdx))
+                && allDigits(bindName.substring(bindIdx + 3))
+                && allDigits(userName.substring(userIdx + 3));
+    }
+
+    /** Whether the text is a non-empty run of digits. */
+    private static boolean allDigits(String text) {
+        if (text.isEmpty()) {
+            return false;
+        }
+        for (int i = 0; i < text.length(); i++) {
+            if (!Character.isDigit(text.charAt(i))) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    /**
+     * Compares the expressions of one node pair. Set-typed conjuncts (filter 
/ having)
+     * are ordered deterministically before pairing; list-typed expressions 
(projections,
+     * group-by,...) keep their parse order.
+     */
+    private static boolean checkNodeExpressions(Plan bind, Plan user,
+            Map<Long, Expression> placeholderValues) {
+        // Base-table relation: UnboundRelation.toDigest omits partition names 
/ sample /
+        // hints and normalizes tablet / snapshot / scan-parameter values, and 
the
+        // namespace is only covered by the L1/L2 digest pre-filter. Compare 
every
+        // non-parameterizable scan identity field exactly here, so "t 
PARTITION(p1)" can
+        // never match "PARTITION(p2)" (the frozen replay would keep reading 
p1). The
+        // relation NAMES are deliberately not compared at this level: the 
stored bind
+        // tree is the raw parse while the user side is namespace-qualified; 
name
+        // equality is enforced by the digest pre-filter.
+        if (bind instanceof UnboundRelation && user instanceof 
UnboundRelation) {
+            return sameScanIdentity((UnboundRelation) bind, (UnboundRelation) 
user);

Review Comment:
   [P1] Preserve relation identity beneath BETWEEN expressions
   
   With `t(k)={1}` and `u(k)={2}`, capture `SELECT (SELECT max(k) FROM t) 
BETWEEN (SELECT max(k) FROM u) AND 10 AS ok`, then run the same query with only 
`t` and `u` exchanged. The reduced expression is:
   ```text
   Between(Scalar(Agg(max(k), Scan(t))), Scalar(Agg(max(k), Scan(u))), 10)
   ```
   `Between.toDigest()` inherits the empty `TreeNode` default, so both keys 
omit this entire subtree. Scalar matching reaches this branch, but 
`sameScanIdentity` skips table names; the metadata fingerprint also sees the 
same unordered `{t,u}` set. Replay therefore retains the captured pairing and 
returns FALSE where the caller requires TRUE, including through raw-tree 
fallback. Include BETWEEN operands in the SPM digest, or validate qualified 
relation identity per matched occurrence, and cover this table-swap case.



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