hello-stephen commented on code in PR #71241: URL: https://github.com/apache/doris/pull/71241#discussion_r4780155799
########## fe/fe-core/src/main/java/org/apache/doris/mtmv/ivm/IvmPlanSignEvaluator.java: ########## @@ -0,0 +1,259 @@ +// 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.BaseTableInfo; +import org.apache.doris.mtmv.MTMVPlanUtil; +import org.apache.doris.mtmv.MTMVRelation; +import org.apache.doris.mysql.privilege.PrivPredicate; +import org.apache.doris.nereids.NereidsPlanner; +import org.apache.doris.nereids.StatementContext; +import org.apache.doris.nereids.analyzer.UnboundSlot; +import org.apache.doris.nereids.exceptions.AnalysisException; +import org.apache.doris.nereids.parser.NereidsParser; +import org.apache.doris.nereids.properties.PhysicalProperties; +import org.apache.doris.nereids.trees.expressions.Expression; +import org.apache.doris.nereids.trees.plans.commands.ExplainCommand.ExplainLevel; +import org.apache.doris.nereids.trees.plans.logical.LogicalPlan; +import org.apache.doris.nereids.util.RelationUtil; +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.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +/** + * 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 IvmPlanSignEvaluator { + + private IvmPlanSignEvaluator() { + } + + /** + * 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) { + return evaluate(callerCtx, callerCtx == null ? null : callerCtx.getStatementContext(), qualifiedMvName); + } + + /** + * Computes the live canonical IVM layout signature for {@code qualifiedMvName}, enforcing that + * when {@code callerStmtCtx} already holds table locks, all tables needed by the MV were + * pre-collected before locking so table lock order is never inverted. + */ + public static Optional<String> evaluate(ConnectContext callerCtx, StatementContext callerStmtCtx, + String qualifiedMvName) { + ResolvedMtmv resolved = resolveMtmv(callerCtx, qualifiedMvName); + Database db = resolved.db; + MTMV mtmv = resolved.mtmv; + 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(); + } + verifyLockOrderSafety(mtmv, callerStmtCtx); + return Optional.of(computeCanonicalSignature(mtmv)); + } + + /** + * Best-effort lookup used during {@code CollectRelation} (before caller table locks are acquired) + * so the caller can lock the target MV and its base tables in the same ascending table-id order. + */ + public static Optional<MTMV> resolveIvmMtmvForLockCollection(ConnectContext callerCtx, String qualifiedMvName) { + if (callerCtx == null || StringUtils.isBlank(qualifiedMvName)) { + return Optional.empty(); + } + try { + MTMV mtmv = resolveMtmv(callerCtx, qualifiedMvName).mtmv; + if (!mtmv.isIvm() || mtmv.isIvmAppendOnlyDupTable()) { + return Optional.empty(); + } + return Optional.of(mtmv); + } catch (AnalysisException ignored) { + return Optional.empty(); + } + } + + private static ResolvedMtmv resolveMtmv(ConnectContext callerCtx, String qualifiedMvName) { + if (callerCtx == null) { + throw new AnalysisException("ivm_plan_signature requires an active session context"); + } + List<String> parts = parseQualifiedName(qualifiedMvName); + List<String> qualifier; + try { + qualifier = RelationUtil.getQualifierName(callerCtx, parts); + } catch (IllegalStateException e) { + throw new AnalysisException(e.getMessage(), e); + } + String catalogName = qualifier.get(0); + String dbName = qualifier.get(1); + String mvName = qualifier.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"); + } + return new ResolvedMtmv(db, (MTMV) table); + } + + private static final class ResolvedMtmv { + private final Database db; + private final MTMV mtmv; + + private ResolvedMtmv(Database db, MTMV mtmv) { + this.db = db; + this.mtmv = mtmv; + } + } + + private static void verifyLockOrderSafety(MTMV mtmv, StatementContext callerStmtCtx) { + if (callerStmtCtx == null || !callerStmtCtx.hasTableLocks()) { + return; + } + Set<Long> callerLockedIds = new HashSet<>(); + for (TableIf t : callerStmtCtx.getTables().values()) { + callerLockedIds.add(t.getId()); + } + for (TableIf t : callerStmtCtx.getMtmvRelatedTables().values()) { + callerLockedIds.add(t.getId()); + } + for (TableIf t : callerStmtCtx.getInsertTargetTables().values()) { + callerLockedIds.add(t.getId()); + } + if (!callerLockedIds.contains(mtmv.getId())) { + throw new AnalysisException("ivm_plan_signature cannot evaluate a non-literal MV name '" + + mtmv.getName() + "' while holding other table locks; pass a string literal MV name"); + } + List<BaseTableInfo> requiredTables = new ArrayList<>(); + mtmv.readMvLock(); + try { + MTMVRelation relation = mtmv.getRelation(); + if (relation != null) { + requiredTables.addAll(relation.getBaseTables()); + requiredTables.addAll(relation.getBaseViews()); + } + } finally { + mtmv.readMvUnlock(); + } + for (BaseTableInfo baseTable : requiredTables) { + if (baseTable.isValid() && !callerLockedIds.contains(baseTable.getTableId())) { + throw new AnalysisException("ivm_plan_signature cannot evaluate a non-literal MV name '" + + mtmv.getName() + "' while holding other table locks; pass a string literal MV name"); + } + } + } + + static List<String> parseQualifiedName(String rawName) { + if (StringUtils.isBlank(rawName)) { + throw new AnalysisException("ivm_plan_signature requires a non-empty materialized view name"); + } + Expression parsed; + try { + parsed = new NereidsParser().parseExpression(rawName.trim()); + } catch (RuntimeException e) { + throw new AnalysisException("Invalid materialized view name '" + rawName + "': " + e.getMessage(), e); + } + if (!(parsed instanceof UnboundSlot)) { + throw new AnalysisException("Invalid materialized view name '" + rawName + + "': expected mv, db.mv, or catalog.db.mv"); + } + List<String> parts = ((UnboundSlot) parsed).getNameParts(); + if (parts.isEmpty() || parts.size() > 3) { + throw new AnalysisException("Invalid materialized view name '" + rawName + + "': expected mv, db.mv, or catalog.db.mv"); + } + for (String part : parts) { + if (StringUtils.isBlank(part)) { + throw new AnalysisException("Invalid materialized view name '" + rawName + + "': empty identifier part"); + } + } + return parts; + } + + private static String computeCanonicalSignature(MTMV mtmv) { + ConnectContext previousCtx = ConnectContext.get(); + try { + ConnectContext internalCtx = MTMVPlanUtil.createMTMVContext( + mtmv, MTMVPlanUtil.DISABLE_RULES_WHEN_RUN_MTMV_TASK); + try (StatementContext stmtCtx = new StatementContext( + internalCtx, new OriginStatement(mtmv.getQuerySql(), 0))) { + internalCtx.setStatementContext(stmtCtx); + stmtCtx.setConnectContext(internalCtx); + stmtCtx.setIvmRewriteContext(Optional.of(IvmRewriteContext.completeExplain(mtmv))); + stmtCtx.setExcludedTriggerTables(mtmv.getExcludedTriggerTables()); + + LogicalPlan sinkPlan = new IvmIncrRefreshManager().buildInsertCommand(mtmv).getLogicalQuery(); + NereidsPlanner planner = new NereidsPlanner(stmtCtx); + planner.planWithLock(sinkPlan, PhysicalProperties.ANY, ExplainLevel.ANALYZED_PLAN); Review Comment: [P2] Keep rewrite-candidate locks out of the nested signature plan For a query that reads table B and projects `ivm_plan_signature('mv_on_a')`, the caller collects B, the target MV, and its stored dependency A before locking. The nested plan has a table sink, so `AddInitMaterializationHook` enables DML MV candidate collection by default. If a separate rewrite-eligible MV joins A with C, `collectMTMVCandidates` adds C to the nested lock set even though every dependency verified by the outer guard is already locked. When C sorts before B by table ID, concurrent table replacement can hold C while waiting for B, as this planner waits for C. That stalls the DDL and can fail the SELECT after the planner lock timeout. Disable MV candidate collection for this nested analyze-only plan, or include its actual lock set in the initial ordered acquisition. ########## fe/fe-core/src/main/java/org/apache/doris/mtmv/ivm/IvmPlanSignLineageResolver.java: ########## @@ -0,0 +1,556 @@ +// 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.Table; +import org.apache.doris.catalog.TableIf; +import org.apache.doris.catalog.info.TableNameInfo; +import org.apache.doris.info.TableNameInfoUtils; +import org.apache.doris.mtmv.ivm.IvmPlanSignCanonicalExpr.Node; +import org.apache.doris.mtmv.ivm.IvmPlanSignCanonicalExpr.Value; +import org.apache.doris.mtmv.ivm.IvmPlanSignCanonicalExpr.ValueList; +import org.apache.doris.nereids.trees.expressions.Alias; +import org.apache.doris.nereids.trees.expressions.ArrayItemReference; +import org.apache.doris.nereids.trees.expressions.Cast; +import org.apache.doris.nereids.trees.expressions.ExprId; +import org.apache.doris.nereids.trees.expressions.Expression; +import org.apache.doris.nereids.trees.expressions.IsNull; +import org.apache.doris.nereids.trees.expressions.Match; +import org.apache.doris.nereids.trees.expressions.NamedExpression; +import org.apache.doris.nereids.trees.expressions.OrderExpression; +import org.apache.doris.nereids.trees.expressions.SessionVarGuardExpr; +import org.apache.doris.nereids.trees.expressions.Slot; +import org.apache.doris.nereids.trees.expressions.SlotReference; +import org.apache.doris.nereids.trees.expressions.StatementScopeIdGenerator; +import org.apache.doris.nereids.trees.expressions.functions.BoundFunction; +import org.apache.doris.nereids.trees.expressions.functions.agg.AggregateFunction; +import org.apache.doris.nereids.trees.expressions.functions.scalar.Lambda; +import org.apache.doris.nereids.trees.expressions.functions.scalar.MurmurHash3128; +import org.apache.doris.nereids.trees.expressions.functions.scalar.Nvl; +import org.apache.doris.nereids.trees.expressions.literal.Literal; +import org.apache.doris.nereids.trees.expressions.literal.NullLiteral; +import org.apache.doris.nereids.trees.expressions.literal.VarcharLiteral; +import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor; +import org.apache.doris.nereids.trees.plans.Plan; +import org.apache.doris.nereids.trees.plans.logical.LogicalAggregate; +import org.apache.doris.nereids.trees.plans.logical.LogicalFilter; +import org.apache.doris.nereids.trees.plans.logical.LogicalJoin; +import org.apache.doris.nereids.trees.plans.logical.LogicalOlapScan; +import org.apache.doris.nereids.trees.plans.logical.LogicalOlapTableSink; +import org.apache.doris.nereids.trees.plans.logical.LogicalOneRowRelation; +import org.apache.doris.nereids.trees.plans.logical.LogicalProject; +import org.apache.doris.nereids.trees.plans.logical.LogicalRepeat; +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.collect.ImmutableList; +import org.apache.commons.lang3.StringUtils; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.TreeMap; + +/** + * Scope-aware unique-key lineage resolver that traces sink key slots down to base-table scan + * columns and canonicalizes expressions into interned {@link IvmPlanSignCanonicalExpr.Node} DAGs. + */ +final class IvmPlanSignLineageResolver { + + private final Map<Node, Node> internPool = new HashMap<>(); + private final IdentityHashMap<Plan, Map<ExprId, Node>> slotCache = new IdentityHashMap<>(); + private final SlotLineageVisitor slotLineageVisitor = new SlotLineageVisitor(); + private boolean usedRowIdHash; + + boolean usedRowIdHash() { + return usedRowIdHash; + } + + Node resolveSlot(Plan plan, Slot slot) { + return resolveSlot(plan, slot, Collections.emptyMap()); + } + + Node resolveExpr(Plan plan, Expression expression) { + return resolveExpr(plan, expression, Collections.emptyMap(), true); + } + + Node buildRowIdHashDef() { + SlotReference nonChar = new SlotReference(StatementScopeIdGenerator.newExprId(), + "x", DoubleType.INSTANCE, true, ImmutableList.of()); + SlotReference charSlot = new SlotReference(StatementScopeIdGenerator.newExprId(), + "s", StringType.INSTANCE, true, ImmutableList.of()); + Expression defExpr = IvmUtil.buildRowIdHash(ImmutableList.of(nonChar, charSlot)); + return resolveExpr(null, defExpr, Collections.emptyMap(), false); + } + + private Node intern(Node node) { + Node existing = internPool.get(node); + if (existing != null) { + return existing; + } + internPool.put(node, node); + return node; + } + + private Node resolveExpr(Plan plan, Expression expression, + Map<ExprId, Integer> lambdaBindings, boolean enableRowIdHashFolding) { + if (enableRowIdHashFolding) { + Optional<List<Expression>> rowIdHashKeys = extractRowIdHashKeys(expression); + if (rowIdHashKeys.isPresent()) { + usedRowIdHash = true; + ValueList args = IvmPlanSignCanonicalExpr.list(); + for (Expression key : rowIdHashKeys.get()) { + args.add(resolveExpr(plan, key, lambdaBindings, true)); + } + return intern(IvmPlanSignCanonicalExpr.node("ROW_ID_HASH").field("args", args)); + } + } + return expression.accept( + new ScopedExpressionVisitor(plan, lambdaBindings, enableRowIdHashFolding), null); + } + + private Node resolveSlot(Plan plan, Slot slot, Map<ExprId, Integer> lambdaBindings) { + Integer lambdaIndex = lambdaBindings.get(slot.getExprId()); + if (lambdaIndex != null) { + return intern(IvmPlanSignCanonicalExpr.leafNode("LAMBDA_PARAM").field("index", lambdaIndex)); + } + if (plan == null) { + return canonicalUnscopedSlot(slot); + } + Map<ExprId, Node> planCache = slotCache.computeIfAbsent(plan, k -> new HashMap<>()); + Node cached = planCache.get(slot.getExprId()); + if (cached != null && !(slot instanceof SlotReference && !((SlotReference) slot).getSubPath().isEmpty())) { + return cached; + } + Node resolved = plan.accept(slotLineageVisitor, slot); + if (!(slot instanceof SlotReference && !((SlotReference) slot).getSubPath().isEmpty())) { + planCache.put(slot.getExprId(), resolved); + } + return resolved; + } + + private Node resolveFromOutputExpressions(Plan child, List<NamedExpression> outputs, + Slot slot, String nodeName) { + NamedExpression matched = findByExprId(outputs, slot.getExprId()); + if (matched == null) { + throw new IllegalStateException("Slot " + slot + " not found in " + nodeName + " outputs"); + } + if (matched instanceof Alias) { + return resolveExpr(child, ((Alias) matched).child(), Collections.emptyMap(), true); + } + return resolveSlot(child, slot, Collections.emptyMap()); + } + + private Node resolveSlotInUnion(LogicalUnion union, Slot slot) { + List<Slot> unionOutputs = union.getOutput(); + int outputIndex = -1; + for (int i = 0; i < unionOutputs.size(); i++) { + if (unionOutputs.get(i).getExprId().equals(slot.getExprId())) { + outputIndex = i; + break; + } + } + if (outputIndex < 0) { + throw new IllegalStateException("Slot " + slot + " not found in LogicalUnion outputs"); + } + ValueList flatArms = IvmPlanSignCanonicalExpr.list(); + for (int arm = 0; arm < union.children().size(); arm++) { + List<SlotReference> armOutputs = union.getRegularChildOutput(arm); + if (outputIndex >= armOutputs.size()) { + throw new IllegalStateException("LogicalUnion arm " + arm + " output size " + armOutputs.size() + + " does not cover output index " + outputIndex); + } + Node armNode = resolveSlot( + union.child(arm), armOutputs.get(outputIndex), Collections.emptyMap()); + if (IvmPlanSignCanonicalExpr.NODE_UNION_ALL.equals(armNode.getName())) { + ValueList nestedArms = (ValueList) armNode.findField("arms"); + for (Value nestedArm : nestedArms.getValues()) { + flatArms.add(nestedArm); + } + } else { + flatArms.add(armNode); + } + } + return intern(IvmPlanSignCanonicalExpr.node(IvmPlanSignCanonicalExpr.NODE_UNION_ALL).field("arms", flatArms)); + } + + private Node resolveSlotInScan(LogicalOlapScan scan, Slot slot) { + Slot scanSlot = findSlotByExprId(scan.getOutput(), slot.getExprId()); + if (scanSlot == null) { + throw new IllegalStateException("Slot " + slot + " not found in LogicalOlapScan outputs for table " + + scan.getTable().getName()); + } + String colName = (scanSlot instanceof SlotReference + && ((SlotReference) scanSlot).getOriginalColumn().isPresent()) + ? ((SlotReference) scanSlot).getOriginalColumn().get().getName() + : scanSlot.getName(); + List<String> subPath = ImmutableList.of(); + if (slot instanceof SlotReference && !((SlotReference) slot).getSubPath().isEmpty()) { + subPath = ((SlotReference) slot).getSubPath(); + } else if (scanSlot instanceof SlotReference) { + subPath = ((SlotReference) scanSlot).getSubPath(); + } + String identity = tableIdentity(scan.getTable(), scan.getQualifier()) + "." + colName; Review Comment: [P3] Preserve identifier boundaries in scan lineage A single-key IVM over table `t.part` with key `id` and one over table `t` with key `part.id` can both project their INT key as `k`. With the same target schema, both signatures contain `SLOT(internal.db.t.part.id)` and yield the same digest, although the keys come from different columns. Both names are valid as quoted identifiers. Encode the catalog, database, table, and column as separate components in the scoped and unscoped slot paths. ########## regression-test/plugins/plugin_planner.groovy: ########## @@ -209,3 +209,11 @@ Suite.metaClass.ivm_hidden_qt = { String tag, String sqlText -> } } +Suite.metaClass.qtIvmPlanSignature = { String tag, String mvArgExpr -> + delegate.quickRunTest( + tag, + "SELECT line FROM (SELECT ivm_plan_signature(${mvArgExpr}) AS sig) t LATERAL VIEW EXPLODE_SPLIT_OUTER(sig, '\\n') e AS line".toString(), Review Comment: [P3] Normalize the suite database in signature golden output The regression runner derives the suite database from its supported `--defaultDb` option. The signature includes that actual database in each base-column reference, while the golden expects `internal.regression_test_mtmv_p0_ivm`. An alternate prefix therefore fails the golden comparison even when the query returns the correct layout. Use the `quickRunTest` row converter to mask the suite database component consistently during generation and comparison. ########## fe/fe-core/src/main/java/org/apache/doris/mtmv/ivm/IvmPlanSignEvaluator.java: ########## @@ -0,0 +1,259 @@ +// 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.BaseTableInfo; +import org.apache.doris.mtmv.MTMVPlanUtil; +import org.apache.doris.mtmv.MTMVRelation; +import org.apache.doris.mysql.privilege.PrivPredicate; +import org.apache.doris.nereids.NereidsPlanner; +import org.apache.doris.nereids.StatementContext; +import org.apache.doris.nereids.analyzer.UnboundSlot; +import org.apache.doris.nereids.exceptions.AnalysisException; +import org.apache.doris.nereids.parser.NereidsParser; +import org.apache.doris.nereids.properties.PhysicalProperties; +import org.apache.doris.nereids.trees.expressions.Expression; +import org.apache.doris.nereids.trees.plans.commands.ExplainCommand.ExplainLevel; +import org.apache.doris.nereids.trees.plans.logical.LogicalPlan; +import org.apache.doris.nereids.util.RelationUtil; +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.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +/** + * 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 IvmPlanSignEvaluator { + + private IvmPlanSignEvaluator() { + } + + /** + * 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) { + return evaluate(callerCtx, callerCtx == null ? null : callerCtx.getStatementContext(), qualifiedMvName); + } + + /** + * Computes the live canonical IVM layout signature for {@code qualifiedMvName}, enforcing that + * when {@code callerStmtCtx} already holds table locks, all tables needed by the MV were + * pre-collected before locking so table lock order is never inverted. + */ + public static Optional<String> evaluate(ConnectContext callerCtx, StatementContext callerStmtCtx, + String qualifiedMvName) { + ResolvedMtmv resolved = resolveMtmv(callerCtx, qualifiedMvName); + Database db = resolved.db; + MTMV mtmv = resolved.mtmv; + 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(); + } + verifyLockOrderSafety(mtmv, callerStmtCtx); + return Optional.of(computeCanonicalSignature(mtmv)); + } + + /** + * Best-effort lookup used during {@code CollectRelation} (before caller table locks are acquired) + * so the caller can lock the target MV and its base tables in the same ascending table-id order. + */ + public static Optional<MTMV> resolveIvmMtmvForLockCollection(ConnectContext callerCtx, String qualifiedMvName) { + if (callerCtx == null || StringUtils.isBlank(qualifiedMvName)) { + return Optional.empty(); + } + try { + MTMV mtmv = resolveMtmv(callerCtx, qualifiedMvName).mtmv; + if (!mtmv.isIvm() || mtmv.isIvmAppendOnlyDupTable()) { + return Optional.empty(); + } + return Optional.of(mtmv); + } catch (AnalysisException ignored) { + return Optional.empty(); + } + } + + private static ResolvedMtmv resolveMtmv(ConnectContext callerCtx, String qualifiedMvName) { + if (callerCtx == null) { + throw new AnalysisException("ivm_plan_signature requires an active session context"); + } + List<String> parts = parseQualifiedName(qualifiedMvName); + List<String> qualifier; + try { + qualifier = RelationUtil.getQualifierName(callerCtx, parts); + } catch (IllegalStateException e) { + throw new AnalysisException(e.getMessage(), e); + } + String catalogName = qualifier.get(0); + String dbName = qualifier.get(1); + String mvName = qualifier.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"); + } + return new ResolvedMtmv(db, (MTMV) table); + } + + private static final class ResolvedMtmv { + private final Database db; + private final MTMV mtmv; + + private ResolvedMtmv(Database db, MTMV mtmv) { + this.db = db; + this.mtmv = mtmv; + } + } + + private static void verifyLockOrderSafety(MTMV mtmv, StatementContext callerStmtCtx) { + if (callerStmtCtx == null || !callerStmtCtx.hasTableLocks()) { + return; + } + Set<Long> callerLockedIds = new HashSet<>(); + for (TableIf t : callerStmtCtx.getTables().values()) { + callerLockedIds.add(t.getId()); + } + for (TableIf t : callerStmtCtx.getMtmvRelatedTables().values()) { + callerLockedIds.add(t.getId()); + } + for (TableIf t : callerStmtCtx.getInsertTargetTables().values()) { + callerLockedIds.add(t.getId()); + } + if (!callerLockedIds.contains(mtmv.getId())) { + throw new AnalysisException("ivm_plan_signature cannot evaluate a non-literal MV name '" + + mtmv.getName() + "' while holding other table locks; pass a string literal MV name"); + } + List<BaseTableInfo> requiredTables = new ArrayList<>(); + mtmv.readMvLock(); + try { + MTMVRelation relation = mtmv.getRelation(); + if (relation != null) { + requiredTables.addAll(relation.getBaseTables()); + requiredTables.addAll(relation.getBaseViews()); + } + } finally { + mtmv.readMvUnlock(); + } + for (BaseTableInfo baseTable : requiredTables) { + if (baseTable.isValid() && !callerLockedIds.contains(baseTable.getTableId())) { + throw new AnalysisException("ivm_plan_signature cannot evaluate a non-literal MV name '" + + mtmv.getName() + "' while holding other table locks; pass a string literal MV name"); + } + } + } + + static List<String> parseQualifiedName(String rawName) { + if (StringUtils.isBlank(rawName)) { + throw new AnalysisException("ivm_plan_signature requires a non-empty materialized view name"); + } + Expression parsed; + try { + parsed = new NereidsParser().parseExpression(rawName.trim()); + } catch (RuntimeException e) { + throw new AnalysisException("Invalid materialized view name '" + rawName + "': " + e.getMessage(), e); + } + if (!(parsed instanceof UnboundSlot)) { + throw new AnalysisException("Invalid materialized view name '" + rawName + + "': expected mv, db.mv, or catalog.db.mv"); + } + List<String> parts = ((UnboundSlot) parsed).getNameParts(); + if (parts.isEmpty() || parts.size() > 3) { + throw new AnalysisException("Invalid materialized view name '" + rawName + + "': expected mv, db.mv, or catalog.db.mv"); + } + for (String part : parts) { + if (StringUtils.isBlank(part)) { + throw new AnalysisException("Invalid materialized view name '" + rawName + + "': empty identifier part"); + } + } + return parts; + } + + private static String computeCanonicalSignature(MTMV mtmv) { + ConnectContext previousCtx = ConnectContext.get(); + try { + ConnectContext internalCtx = MTMVPlanUtil.createMTMVContext( + mtmv, MTMVPlanUtil.DISABLE_RULES_WHEN_RUN_MTMV_TASK); + try (StatementContext stmtCtx = new StatementContext( + internalCtx, new OriginStatement(mtmv.getQuerySql(), 0))) { + internalCtx.setStatementContext(stmtCtx); + stmtCtx.setConnectContext(internalCtx); + stmtCtx.setIvmRewriteContext(Optional.of(IvmRewriteContext.completeExplain(mtmv))); Review Comment: [P2] Compute the layout signature without requiring refresh streams After an IVM MV loses one of its streams, the base tables and their key layout can still be analyzed. The existing `test_ivm_partitions_fallback_stream_unusable` suite creates exactly this state. `completeExplain` requests RESET stream scans, so after `IvmNormalizeMTMV` has generated the signature, `IvmFullRefreshMTMV` calls `IvmUtil.getIvmStream` and throws before the evaluator can return that signature. Use the normalize-only context here and cover a signature lookup while a stream is missing. -- 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]
