github-actions[bot] commented on code in PR #68499:
URL: https://github.com/apache/doris/pull/68499#discussion_r4675013456


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/spm/builder/SPMExprSqlBuilder.java:
##########
@@ -0,0 +1,1020 @@
+// 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.builder;
+
+import org.apache.doris.nereids.analyzer.UnboundFunction;
+import org.apache.doris.nereids.spm.matcher.SPMFrozenTreeReplacer;
+import org.apache.doris.nereids.spm.placeholder.SPMSubquerySupport;
+import org.apache.doris.nereids.trees.expressions.Add;
+import org.apache.doris.nereids.trees.expressions.AggregateExpression;
+import org.apache.doris.nereids.trees.expressions.Alias;
+import org.apache.doris.nereids.trees.expressions.And;
+import org.apache.doris.nereids.trees.expressions.Between;
+import org.apache.doris.nereids.trees.expressions.BinaryArithmetic;
+import org.apache.doris.nereids.trees.expressions.BinaryOperator;
+import org.apache.doris.nereids.trees.expressions.BitAnd;
+import org.apache.doris.nereids.trees.expressions.BitNot;
+import org.apache.doris.nereids.trees.expressions.BitOr;
+import org.apache.doris.nereids.trees.expressions.BitXor;
+import org.apache.doris.nereids.trees.expressions.CaseWhen;
+import org.apache.doris.nereids.trees.expressions.Cast;
+import org.apache.doris.nereids.trees.expressions.ComparisonPredicate;
+import org.apache.doris.nereids.trees.expressions.CompoundPredicate;
+import org.apache.doris.nereids.trees.expressions.Divide;
+import org.apache.doris.nereids.trees.expressions.EqualTo;
+import org.apache.doris.nereids.trees.expressions.Exists;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.GreaterThan;
+import org.apache.doris.nereids.trees.expressions.GreaterThanEqual;
+import org.apache.doris.nereids.trees.expressions.InPredicate;
+import org.apache.doris.nereids.trees.expressions.InSubquery;
+import org.apache.doris.nereids.trees.expressions.IntegralDivide;
+import org.apache.doris.nereids.trees.expressions.IsFalse;
+import org.apache.doris.nereids.trees.expressions.IsNull;
+import org.apache.doris.nereids.trees.expressions.IsTrue;
+import org.apache.doris.nereids.trees.expressions.LessThan;
+import org.apache.doris.nereids.trees.expressions.LessThanEqual;
+import org.apache.doris.nereids.trees.expressions.Like;
+import org.apache.doris.nereids.trees.expressions.Match;
+import org.apache.doris.nereids.trees.expressions.Mod;
+import org.apache.doris.nereids.trees.expressions.Multiply;
+import org.apache.doris.nereids.trees.expressions.Not;
+import org.apache.doris.nereids.trees.expressions.NullSafeEqual;
+import org.apache.doris.nereids.trees.expressions.OrderExpression;
+import org.apache.doris.nereids.trees.expressions.SessionVarGuardExpr;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+import org.apache.doris.nereids.trees.expressions.StringRegexPredicate;
+import org.apache.doris.nereids.trees.expressions.SubqueryExpr;
+import org.apache.doris.nereids.trees.expressions.Subtract;
+import org.apache.doris.nereids.trees.expressions.TryCast;
+import org.apache.doris.nereids.trees.expressions.WhenClause;
+import org.apache.doris.nereids.trees.expressions.WindowExpression;
+import org.apache.doris.nereids.trees.expressions.functions.BoundFunction;
+import org.apache.doris.nereids.trees.expressions.functions.Function;
+import org.apache.doris.nereids.trees.expressions.functions.Udf;
+import 
org.apache.doris.nereids.trees.expressions.functions.agg.AggregateFunction;
+import org.apache.doris.nereids.trees.expressions.functions.agg.GroupConcat;
+import 
org.apache.doris.nereids.trees.expressions.functions.agg.MultiDistinctGroupConcat;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.Nullable;
+import org.apache.doris.nereids.trees.expressions.functions.window.Lag;
+import org.apache.doris.nereids.trees.expressions.functions.window.Lead;
+import org.apache.doris.nereids.trees.expressions.literal.ArrayLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.DateLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.DateTimeLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.DateTimeV2Literal;
+import org.apache.doris.nereids.trees.expressions.literal.DateV2Literal;
+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.MapLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.StringLikeLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.StructLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.TimeV2Literal;
+import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
+import org.apache.doris.nereids.types.ArrayType;
+import org.apache.doris.nereids.types.DataType;
+import org.apache.doris.nereids.types.DateTimeType;
+import org.apache.doris.nereids.types.DateTimeV2Type;
+import org.apache.doris.nereids.types.DateType;
+import org.apache.doris.nereids.types.DateV2Type;
+import org.apache.doris.nereids.types.DecimalV2Type;
+import org.apache.doris.nereids.types.LargeIntType;
+import org.apache.doris.nereids.types.MapType;
+import org.apache.doris.nereids.types.StructField;
+import org.apache.doris.nereids.types.StructType;
+import org.apache.doris.nereids.types.VarBinaryType;
+import org.apache.doris.nereids.types.VarcharType;
+import org.apache.doris.nereids.util.ExpressionUtils;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+/**
+ * Renders supported expressions using the ExprId reference mapping of a 
SQLRelation. Marker payloads are omitted
+ * in favor of id-only calls. Composite expressions recurse through the 
visitor; a generic toSql fallback rejects
+ * registered slots that require remapping.
+ *
+ * Subquery expressions have only a compact diagnostic digest rendering here, 
not executable subquery SQL. The
+ * physical-plan decompiler rejects residual subquery expressions before 
invoking this printer.
+ */
+public class SPMExprSqlBuilder extends ExpressionVisitor<String, SQLRelation> {
+
+    /**
+     * The INTERNAL pseudo function names visitSubqueryExpr emits for a 
subquery: the
+     * structural DIGEST form, never SQL.
+     *
+     * They are reserved by SPM. A frozen SQL must never be readable as - or 
shadowed by - a user
+     * function of one of these names: INSUBQUERY(x)[...] is an ordinary 
unreserved call, so
+     * a compatible user alias UDF made a frozen text validate and every 
replay evaluated that UDF
+     * (and its array access) instead of the original IN (SELECT...). 
Subqueries are
+     * therefore refused before decompilation and a plan calling a function of 
these names is not
+     * freezable either (see SPMPlan2SQLBuilder.rejectSubqueryExpressions /
+     * #rejectReservedInternalFunctionNames).
+     */
+    public static final java.util.Set<String> INTERNAL_PSEUDO_FUNCTION_NAMES =
+            java.util.Set.of("insubquery", "scalarsubquery");
+
+    /**
+     * Prints a single expression.
+     *
+     * Parameter expr: the expression to print
+     * Parameter relation: the SQLRelation carrying the columnNames mapping
+     * Returns: the SQL text
+     */
+    public String print(Expression expr, SQLRelation relation) {
+        return expr.accept(this, relation);
+    }
+
+    /**
+     * Renders one function's argument list.
+     *
+     * Parameter aggregate: whether the arguments belong to an AGGREGATE call
+     * Parameter arguments: the arguments to render
+     * Parameter context: the relation of the enclosing scope
+     * Returns: the comma separated argument text
+     */
+    private String renderArguments(boolean aggregate, List<Expression> 
arguments,
+            SQLRelation context) {
+        return arguments.stream()
+                .map(argument -> renderArgument(argument, context, aggregate))
+                .collect(Collectors.joining(", "));
+    }
+
+    /**
+     * Renders one function argument. At an aggregate argument root, preserves 
a recognized LARGEINT accumulator
+     * widening; other casts follow visitCast. This root-only rule avoids 
retaining ordinary nested coercions that
+     * would pin a captured operand type.
+     */
+    private String renderArgument(Expression argument, SQLRelation context, 
boolean aggregate) {
+        if (aggregate && argument instanceof Cast && 
preservesLoweredAccumulator((Cast) argument)) {
+            Cast cast = (Cast) argument;
+            return "CAST(" + cast.child().accept(this, context) + " AS "
+                    + cast.getDataType().toSql() + ")";
+        }
+        return argument.accept(this, context);
+    }
+
+    @Override
+    public String visit(Expression expr, SQLRelation context) {
+        // SPM placeholder: render as the id-only function call 
"_spm_const_var(id)" /
+        // "_spm_const_list(id)" (the value does not participate in the digest 
/ planSql
+        // serialization). The id-only form keeps the digest value-independent 
AND makes
+        // the frozen planSql parseable at replay: the text carries the id and 
the
+        // replay substitutes the matched expression under that id.
+        if (expr instanceof 
org.apache.doris.nereids.spm.placeholder.SpmConstVar) {
+            org.apache.doris.nereids.spm.placeholder.SpmConstVar ph =
+                    (org.apache.doris.nereids.spm.placeholder.SpmConstVar) 
expr;
+            return "_spm_const_var(" + ph.getId() + ")";
+        }
+        if (expr instanceof 
org.apache.doris.nereids.spm.placeholder.SpmConstList) {
+            org.apache.doris.nereids.spm.placeholder.SpmConstList list =
+                    (org.apache.doris.nereids.spm.placeholder.SpmConstList) 
expr;
+            // IN-list placeholder: render size-independently 
(_spm_const_list(id)) so
+            // the digest / planSql stays value AND list-length independent: a 
baseline
+            // "IN (1, 2, 3)" matches a user "IN (10, 20)" regardless of list 
length.
+            return "_spm_const_list(" + list.getId() + ")";
+        }
+        // Default fallback: use toSql of the expression itself (no column 
mapping).
+        // toSql bypasses the ExprId -> column mapping, so a composite shape 
whose
+        // children need remapping (e.g. ~left.a above a join that renamed the 
colliding
+        // a to c_N / qualified it) would freeze a stale, unresolvable column 
and - with
+        // the default enable_spm_fallback = false - fail the rewritten query. 
Reject
+        // such shapes so CREATE keeps the user planSql and the rewrite 
degrades to the
+        // parameterized-tree path.
+        ensureNoRemappedSlots(expr, context);
+        return expr.toSql();
+    }
+
+    /**
+     * Safety net of the generic toSql fallback: rejects the expression when 
any slot
+     * below it is registered under a reference that toSql would NOT reproduce 
(the
+     * collision-renaming / quoting / qualification case), because toSql would 
then emit
+     * a stale or differently-shaped name. Only a byte-identical registered 
reference is
+     * renderable through the fallback. Public for tests.
+     *
+     * Parameter expr: the expression about to fall back to toSql
+     * Parameter context: the relation carrying the ExprId -> column-reference 
mapping
+     * Throws UnsupportedOperationException: when a child slot needs remapping
+     */
+    public static void ensureNoRemappedSlots(Expression expr, SQLRelation 
context) {
+        if (expr instanceof SlotReference) {
+            SlotReference slot = (SlotReference) expr;
+            String mapped = context.getColumnNames().get(slot.getExprId());
+            // toSql prints the BARE slot name, so a registered reference is 
only safe
+            // when it is byte-identical to that rendering. A 
special-character column
+            // maps to a QUOTED reference (a-b) and a disambiguated one to a 
QUALIFIED
+            // reference (l.x): both still "name" the column, but freezing 
their unquoted /
+            // unqualified toSql text produces SQL that no longer resolves 
after reload
+            // ("a-b MATCH 'foo'" parses as a subtraction; a bare x may be 
ambiguous).
+            // Reject the generic fallback for those shapes - CREATE keeps the 
user planSql
+            // and the rewrite degrades to the parameterized-tree path.
+            if (mapped != null && !mapped.equals(slot.getName())) {
+                throw new UnsupportedOperationException(
+                        "SPM decompile: expression " + expr.toSql() + " needs 
column remapping ("
+                                + mapped + " -> " + slot.getName() + ") which 
toSql() cannot apply");
+            }
+        }
+        for (Expression child : expr.children()) {
+            ensureNoRemappedSlots(child, context);
+        }
+    }
+
+    // column references.
+
+    @Override
+    public String visitSlotReference(SlotReference slotReference, SQLRelation 
context) {
+        String mapped = 
context.getColumnNames().get(slotReference.getExprId());
+        if (mapped != null) {
+            return mapped;
+        }
+        // Doris rollup materializes "GROUPING(col)" as an internal slot named
+        // GROUPING_PREFIX_<col>; when such a slot was not registered by the 
repeat
+        // decompiler (defensive fallback), render it back to GROUPING(col).
+        String name = slotReference.getName();
+        if (name != null && name.startsWith("GROUPING_PREFIX_")) {
+            return "GROUPING(" + name.substring("GROUPING_PREFIX_".length()) + 
")";
+        }
+        // An unregistered slot whose name is Doris's internal mark-slot naming
+        // ("$c$N", e.g. the EXISTS marker of an uncorrelated subquery folded 
into a
+        // constant CROSS JOIN) can never be resolved in the decompiled SQL - 
emitting
+        // the raw name would freeze a planSql that fails on replay ("Unknown 
column
+        // '$c$1'"). Such a shape has no faithful SQL rendering here, so fail 
the
+        // decompile: CREATE BASELINE then falls back to the user-supplied 
planSql
+        // (which is exactly the original query for these constant boolean 
outputs).
+        if (name != null && name.startsWith("$c$")) {
+            throw new UnsupportedOperationException(
+                    "SPM decompile: unresolvable internal mark slot " + name);
+        }
+        // Unregistered column reference (e.g. a CTE output column) degrades 
to the raw
+        // column name
+        return slotReference.toSql();
+    }
+
+    // binary operations (arithmetic / comparison / logic).
+
+    @Override
+    public String visitComparisonPredicate(ComparisonPredicate 
comparisonPredicate, SQLRelation context) {
+        return "(" + renderValueOperand(comparisonPredicate.left(), context)
+                + " " + operatorSymbol(comparisonPredicate)
+                + " " + renderValueOperand(comparisonPredicate.right(), 
context) + ")";
+    }
+
+    @Override
+    public String visitBinaryArithmetic(BinaryArithmetic binaryArithmetic, 
SQLRelation context) {
+        return "(" + renderValueOperand(binaryArithmetic.left(), context)
+                + " " + operatorSymbol(binaryArithmetic)
+                + " " + renderValueOperand(binaryArithmetic.right(), context) 
+ ")";
+    }
+
+    /**
+     * BitNot (~x): the generic fallback would print the expression through 
toSql and
+     * bypass the column mapping; above a join whose colliding column was 
renamed, that
+     * freezes the stale slot text. Render the child recursively instead so 
the mapped
+     * column reference stays mapped.
+     */
+    @Override
+    public String visitBitNot(BitNot bitNot, SQLRelation context) {
+        return "~(" + bitNot.child().accept(this, context) + ")";
+    }
+
+    @Override
+    public String visitCompoundPredicate(CompoundPredicate compoundPredicate, 
SQLRelation context) {
+        // And / Or are n-ary in Nereids: a single node can hold more than two 
children,
+        // so child(0)/child(1) alone would drop the rest. Flatten the 
same-type operators
+        // into a list of operands with ExpressionUtils.extract (see 
extractConjunction /
+        // extractDisjunction) and join them with the operator symbol. extract 
stops at a
+        // different operator type, so e.g. (a or b) and c keeps the inner Or 
intact.
+        //
+        // CompoundPredicate is not a BinaryOperator (And/Or extend 
CompoundPredicate
+        // directly), so resolve the symbol here instead of using 
operatorSymbol.
+        String symbol = compoundPredicate instanceof And ? "AND" : "OR";
+        String joined = ExpressionUtils.extract(compoundPredicate).stream()
+                .map(operand -> operand.accept(this, context))
+                .collect(Collectors.joining(" " + symbol + " "));
+        // AND / OR need parentheses to keep the precedence
+        return "(" + joined + ")";
+    }
+
+    @Override
+    public String visitNot(Not not, SQLRelation context) {
+        return "(NOT (" + not.child().accept(this, context) + "))";
+    }
+
+    @Override
+    public String visitIsNull(IsNull isNull, SQLRelation context) {
+        return renderValueOperand(isNull.child(), context) + " IS NULL";
+    }
+
+    @Override
+    public String visitIsTrue(IsTrue isTrue, SQLRelation context) {
+        return renderValueOperand(isTrue.child(), context) + " IS TRUE";
+    }
+
+    @Override
+    public String visitIsFalse(IsFalse isFalse, SQLRelation context) {
+        return renderValueOperand(isFalse.child(), context) + " IS FALSE";
+    }
+
+    // predicates.
+
+    @Override
+    public String visitInPredicate(InPredicate inPredicate, SQLRelation 
context) {
+        String compareExpr = renderValueOperand(inPredicate.getCompareExpr(), 
context);
+        List<String> options = inPredicate.getOptions().stream()
+                .map(o -> o.accept(this, context))
+                .collect(Collectors.toList());
+        // A literal-only IN option list may be stored in a set-backed 
collection whose
+        // iteration order is NOT stable across runs / FE restarts (observed: 
TPCDS q75's
+        // "d_year IN (2001, 2002)" decompiled as (2001, 2002) one run and 
(2002, 2001)
+        // the next, flipping the frozen planSql and failing the.out 
comparison). IN
+        // semantics are order-independent, so a literal-only list is emitted 
in sorted
+        // order to keep the decompiled planSql deterministic.
+        boolean allLiterals = inPredicate.getOptions().stream()
+                .allMatch(o -> o instanceof Literal);
+        if (allLiterals && options.size() > 1) {
+            Collections.sort(options);
+        }
+        return compareExpr + " IN (" + String.join(", ", options) + ")";
+    }
+
+    @Override
+    public String visitBetween(Between between, SQLRelation context) {
+        String compareExpr = renderValueOperand(between.getCompareExpr(), 
context);
+        String lower = renderValueOperand(between.getLowerBound(), context);
+        String upper = renderValueOperand(between.getUpperBound(), context);
+        return compareExpr + " BETWEEN " + lower + " AND " + upper;
+    }
+
+    @Override
+    public String visitLike(Like like, SQLRelation context) {
+        String rendered = renderValueOperand(like.left(), context)
+                + " LIKE " + renderValueOperand(like.right(), context);
+        if (like.children().size() > 2) {
+            // The third child is the ESCAPE character. Dropping it froze a 
three-argument
+            // LIKE as a two-child predicate: parameterizing the escape 
literal fails
+            // LIKE's literal-only legality check, so creation fell back to 
the raw plan and
+            // persisted the ALTERED predicate - a column-pattern LIKE 
replayed without
+            // ESCAPE can match different rows. Its syntax requires a bare 
string literal.
+            Expression escape = like.child(2);
+            if (!(escape instanceof StringLikeLiteral)) {
+                throw new UnsupportedOperationException("SPM decompile: LIKE 
ESCAPE must be a string literal");
+            }
+            rendered += " ESCAPE " + 
SPMPlan2SQLBuilder.quoteSqlString(((StringLikeLiteral) 
escape).getStringValue());
+        }
+        return rendered;
+    }
+
+    /** Parentheses let a predicate occupy a value-expression position in the 
parser. */
+    private String renderValueOperand(Expression operand, SQLRelation context) 
{
+        if (operand instanceof Nullable) {
+            return renderValueOperand(operand.child(0), context);
+        }
+        String rendered = operand.accept(this, context);
+        if (operand instanceof IsNull || operand instanceof IsTrue || operand 
instanceof IsFalse
+                || operand instanceof InPredicate || operand instanceof Between
+                || operand instanceof StringRegexPredicate || operand 
instanceof Match) {
+            return "(" + rendered + ")";
+        }
+        return rendered;
+    }
+
+    // function calls.
+
+    @Override
+    public String visitBoundFunction(BoundFunction boundFunction, SQLRelation 
context) {
+        // The Nullable marker (nullable(x) wraps a column to make it 
nullable, e.g. on a
+        // recursive CTE union branch) has no SQL equivalent: decompile the 
inner
+        // expression only.
+        if (boundFunction instanceof Nullable) {
+            return boundFunction.child(0).accept(this, context);
+        }
+        if (boundFunction instanceof GroupConcat || boundFunction instanceof 
MultiDistinctGroupConcat) {
+            String rendered = renderGroupConcat((AggregateFunction) 
boundFunction, context);
+            if (rendered == null) {
+                throw new UnsupportedOperationException(
+                        "SPM decompile: group_concat shape is not supported 
yet");
+            }
+            return rendered;
+        }
+        String args = renderArguments(boundFunction instanceof 
AggregateFunction,
+                boundFunction.children(), context);

Review Comment:
   [P1] Preserve omitted AI-resource defaults when freezing calls
   
   Capture `SELECT ai_sentiment(s) AS c FROM t` with `default_ai_resource='A'`, 
then execute identical SQL with default `B`, with both resources valid and 
accessible. `AISentiment`'s one-argument constructor injects 
`StringLiteral(AIFunction.getResourceName())` after parameterization:
   ```text
   Project[AISentiment('A', s) AS c] -> Scan(t)
   ```
   Serializing all bound children freezes `ai_sentiment('A', s)`. The column 
prevents folding, the planning probe accepts the explicit resource, and 
function fingerprints omit `default_ai_resource`; the current omitted-default 
guard covers encryption calls only. Replay's two-argument constructor 
consequently retains A and invokes its configured resource/model instead of the 
caller's B. Preserve omitted-resource provenance or retain raw replay for these 
AI forms, and cover capture under A followed by replay under B. This 
first-argument AI-resource injection is distinct from the repaired AES/SM4 
mode-default report.



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