hello-stephen commented on code in PR #71241:
URL: https://github.com/apache/doris/pull/71241#discussion_r4756332465
##########
fe/fe-core/src/main/java/org/apache/doris/mtmv/ivm/IvmPlanSignatureGenerator.java:
##########
@@ -41,171 +58,668 @@
import org.apache.doris.nereids.trees.plans.logical.LogicalResultSink;
import org.apache.doris.nereids.trees.plans.logical.LogicalSubQueryAlias;
import org.apache.doris.nereids.trees.plans.logical.LogicalUnion;
-import org.apache.doris.nereids.trees.plans.visitor.PlanVisitor;
+import org.apache.doris.nereids.types.DoubleType;
+import org.apache.doris.nereids.types.StringType;
+import org.apache.doris.nereids.types.VarcharType;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableList;
import org.apache.commons.lang3.StringUtils;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
-import java.util.Comparator;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
/**
- * Builds the stable IVM maintenance-layout signature.
+ * Builds the stable IVM maintenance-layout signature from a normalized {@link
LogicalOlapTableSink}.
*
- * <p>The signature is determined only by the normalized MV plan. It is
unrelated to delta rewrite: once the
- * normalized plan is fixed, the row-id computation is fixed, so the signature
is fixed as well. The signature only
- * tracks the row-id generation path because row-id is used to locate existing
MV rows when incremental refresh
- * retracts or merges data. Delta rewrite may evolve independently; its
generated row-id must adapt to the normalized
- * plan instead of changing the normalized-plan signature.
+ * <p>Instead of serializing intermediate plan operators (such as {@code
PROJECT}, {@code FILTER},
+ * {@code JOIN}, {@code AGG}, {@code REPEAT}, or {@code SCAN}), the signature
records only:
+ * <ul>
+ * <li>{@code TABLE_SINK}: ordered target table column names and types (plus
{@code EXTRA_OUTPUTS}
+ * if the normalized plan emits trailing columns beyond the target
schema).</li>
+ * <li>{@code ROW_ID_HASH_DEF}: live definition derived from {@link
IvmUtil#buildRowIdHash}
+ * whenever any traced key expression uses {@code RowIdHash}.</li>
+ * <li>{@code UNIQUE_KEYS}: every target-table {@code UNIQUE KEY} column
(including
+ * {@code __DORIS_IVM_ROW_ID_COL__}, visible keys, and {@code
ivm_use_full_keys} hidden keys)
+ * resolved through demand-driven scoped lineage down to base table
columns and literals.</li>
+ * </ul>
+ *
+ * <p>Intermediate plan-shape changes (extra/merged projects, alias renames,
filter placement, or
+ * join reordering under an aggregate) do not alter the signature as long as
the target schema and
+ * key derivation expressions remain equivalent.
*/
public class IvmPlanSignatureGenerator {
public static final int CURRENT_VERSION = 1;
@VisibleForTesting
public static final String DEBUG_POINT_SIGNATURE_SALT =
"IvmPlanSignatureGenerator.generate.signature_salt";
private static final String HEADER = "IVM_LAYOUT_SIGNATURE_V" +
CURRENT_VERSION;
-
- private final CanonicalExpressionVisitor canonicalExpressionVisitor = new
CanonicalExpressionVisitor();
- private final CanonicalPlanVisitor canonicalPlanVisitor = new
CanonicalPlanVisitor();
+ private static final String NODE_UNION_ALL = "UNION_ALL";
public IvmPlanSignatureGenerator() {
}
public IvmPlanSignature generate(Plan normalizedPlan) {
- CanonicalNode root = CanonicalNode.node("ROOT")
- .field("plan", canonicalPlan(normalizedPlan));
- String canonical = HEADER + "\n" + root.encoded();
+ if (!(normalizedPlan instanceof LogicalOlapTableSink)) {
Review Comment:
[P2] Migrate the remaining task-test fixture to a table sink
The new guard breaks the existing
`MTMVTaskTest.testDebugPlanSignatureDriftFallsBackToFullRefresh`. Its first
call to `signatureForDebugDriftTest()` reaches
`generate(rewriteResult.getNormalizedPlan())`, but `buildSignaturePlan()` still
constructs a `LogicalResultSink` (`MTMVTaskTest.java:2172–2187`). Consequently
this now throws `IllegalStateException` before either signature is produced or
any fallback assertion runs. Please migrate that fixture to a bound
`LogicalOlapTableSink` with the required target schema and IVM row-id key, as
the other signature-test fixtures were migrated in this PR.
##########
fe/fe-core/src/main/java/org/apache/doris/mtmv/ivm/IvmPlanSignatureEvaluator.java:
##########
@@ -0,0 +1,194 @@
+// 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.mtmv.ivm;
+
+import org.apache.doris.catalog.Database;
+import org.apache.doris.catalog.Env;
+import org.apache.doris.catalog.MTMV;
+import org.apache.doris.catalog.TableIf;
+import org.apache.doris.datasource.InternalCatalog;
+import org.apache.doris.mtmv.MTMVPlanUtil;
+import org.apache.doris.mysql.privilege.PrivPredicate;
+import org.apache.doris.nereids.NereidsPlanner;
+import org.apache.doris.nereids.StatementContext;
+import org.apache.doris.nereids.exceptions.AnalysisException;
+import org.apache.doris.nereids.properties.PhysicalProperties;
+import
org.apache.doris.nereids.trees.plans.commands.ExplainCommand.ExplainLevel;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+import org.apache.doris.qe.ConnectContext;
+import org.apache.doris.qe.OriginStatement;
+
+import org.apache.commons.lang3.StringUtils;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * Evaluates the live canonical IVM layout signature text for a materialized
view without
+ * executing a refresh, mutating metadata, or consuming stream offsets.
+ */
+public final class IvmPlanSignatureEvaluator {
+
+ private IvmPlanSignatureEvaluator() {
+ }
+
+ /**
+ * Computes the live canonical IVM layout signature for {@code
qualifiedMvName}, which may be
+ * {@code mv}, {@code db.mv}, or {@code catalog.db.mv} (each part
optionally backtick-quoted).
+ *
+ * @param callerCtx caller's session context (used for default catalog/db
and privilege checks)
+ * @param qualifiedMvName materialized view name in 1-, 2-, or 3-part
qualified form
+ * @return the canonical signature string for unique-key IVM MVs, or empty
for append-only detail IVM MVs
+ */
+ public static Optional<String> evaluate(ConnectContext callerCtx, String
qualifiedMvName) {
+ if (callerCtx == null) {
+ throw new AnalysisException("ivm_plan_signature requires an active
session context");
+ }
+ List<String> parts = parseQualifiedName(qualifiedMvName);
+ String catalogName;
+ String dbName;
+ String mvName;
+ if (parts.size() == 1) {
+ catalogName = StringUtils.defaultIfBlank(
+ callerCtx.getDefaultCatalog(),
InternalCatalog.INTERNAL_CATALOG_NAME);
+ dbName = callerCtx.getDatabase();
+ mvName = parts.get(0);
+ } else if (parts.size() == 2) {
+ catalogName = StringUtils.defaultIfBlank(
+ callerCtx.getDefaultCatalog(),
InternalCatalog.INTERNAL_CATALOG_NAME);
+ dbName = parts.get(0);
+ mvName = parts.get(1);
+ } else {
+ catalogName = parts.get(0);
+ dbName = parts.get(1);
+ mvName = parts.get(2);
+ }
+
+ if (!InternalCatalog.INTERNAL_CATALOG_NAME.equals(catalogName)) {
+ throw new AnalysisException("Unsupported catalog '" + catalogName
+ + "' for ivm_plan_signature: IVM materialized views only
exist in internal catalog");
+ }
+ if (StringUtils.isBlank(dbName)) {
+ throw new AnalysisException("No database selected for
ivm_plan_signature");
+ }
+
+ InternalCatalog catalog = Env.getCurrentInternalCatalog();
+ Database db = catalog.getDbNullable(dbName);
+ if (db == null) {
+ throw new AnalysisException("Unknown database '" + dbName + "'");
+ }
+ TableIf table = db.getTableNullable(mvName);
+ if (!(table instanceof MTMV)) {
+ throw new AnalysisException("Materialized view '" + dbName + "." +
mvName + "' does not exist");
+ }
+ MTMV mtmv = (MTMV) table;
+ if (!Env.getCurrentEnv().getAccessManager().checkTblPriv(
+ callerCtx, InternalCatalog.INTERNAL_CATALOG_NAME,
db.getFullName(), mtmv.getName(),
+ PrivPredicate.SHOW)) {
+ throw new AnalysisException("Permission denied: SHOW privilege
required on materialized view '"
+ + db.getFullName() + "." + mtmv.getName() + "'");
+ }
+ if (!mtmv.isIvm()) {
+ throw new AnalysisException("Materialized view '" +
db.getFullName() + "." + mtmv.getName()
+ + "' is not an IVM materialized view");
+ }
+ if (mtmv.isIvmAppendOnlyDupTable()) {
+ return Optional.empty();
+ }
+ return Optional.of(computeCanonicalSignature(mtmv));
+ }
+
+ static List<String> parseQualifiedName(String rawName) {
+ if (StringUtils.isBlank(rawName)) {
+ throw new AnalysisException("ivm_plan_signature requires a
non-empty materialized view name");
+ }
+ String trimmed = rawName.trim();
+ List<String> parts = new ArrayList<>(3);
+ StringBuilder current = new StringBuilder();
+ boolean inBacktick = false;
+ for (int i = 0; i < trimmed.length(); i++) {
+ char c = trimmed.charAt(i);
+ if (c == '`') {
+ inBacktick = !inBacktick;
+ current.append(c);
+ } else if (c == '.' && !inBacktick) {
+ parts.add(normalizeIdentifierPart(current.toString(),
rawName));
+ current.setLength(0);
+ } else {
+ current.append(c);
+ }
+ }
+ if (inBacktick) {
+ throw new AnalysisException("Invalid materialized view name '" +
rawName + "': unclosed backtick");
+ }
+ parts.add(normalizeIdentifierPart(current.toString(), rawName));
+ if (parts.size() > 3) {
+ throw new AnalysisException("Invalid materialized view name '" +
rawName
+ + "': expected mv, db.mv, or catalog.db.mv");
+ }
+ return parts;
+ }
+
+ private static String normalizeIdentifierPart(String rawPart, String
fullName) {
+ String part = rawPart.trim();
+ if (part.startsWith("`") && part.endsWith("`") && part.length() >= 2) {
+ part = part.substring(1, part.length() - 1);
Review Comment:
[P2] Decode escaped backticks in quoted MV names
With the default Unicode-name support, an MV name containing a backtick is
valid, and its SQL identifier escapes that character by doubling it. For
example:
```sql
SELECT ivm_plan_signature('`sig``mv`');
```
This branch removes only the outer quotes, so `getTableNullable` receives
two interior backticks instead of one and reports that the existing MV does not
exist (or resolves a different MV if both names exist). Ordinary SQL explicitly
decodes doubled backticks in `DorisParser.g4:42`, covered by
`NereidsParserTest.testQuotedIdentifierNormalization`. Please reuse that
identifier parsing behavior or decode the escaped characters here, and add an
escaped-name 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]