yujun777 commented on code in PR #71241: URL: https://github.com/apache/doris/pull/71241#discussion_r4781197866
########## fe/fe-core/src/main/java/org/apache/doris/mtmv/ivm/IvmPlanSignEvaluator.java: ########## @@ -0,0 +1,314 @@ +// 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.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.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 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) { + 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) { + 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(); + } + 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 { + 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) || StringUtils.isBlank(dbName)) { + return Optional.empty(); + } + Database db = Env.getCurrentInternalCatalog().getDbNullable(dbName); + if (db == null) { + return Optional.empty(); + } + TableIf table = db.getTableNullable(mvName); + if (!(table instanceof MTMV)) { + return Optional.empty(); + } + MTMV mtmv = (MTMV) table; + if (!mtmv.isIvm() || mtmv.isIvmAppendOnlyDupTable()) { + return Optional.empty(); + } + return Optional.of(mtmv); + } catch (AnalysisException ignored) { + return Optional.empty(); + } + } + + 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())) { Review Comment: Fixed in efcdc34c4ae: removed pre-lock collection and stale-ID comparison; ivm_plan_signature() is now restricted to standalone constant queries without reading tables (callerStmtCtx.hasTableLocks() == false), so standalone calls work cleanly after ALTER TABLE REPLACE. ########## fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/rules/FoldConstantRuleOnFE.java: ########## @@ -390,6 +395,30 @@ public Expression visitDatabase(Database database, ExpressionRewriteContext cont return new VarcharLiteral(res); } + @Override + public Expression visitIvmPlanSignatureFunc(IvmPlanSignatureFunc func, ExpressionRewriteContext context) { + IvmPlanSignatureFunc rewritten = rewriteChildren(func, context); + if (!foldContextDependentExpressions) { + return rewritten; + } + StatementContext callerStmtCtx = context.cascadesContext.getStatementContext(); + if (callerStmtCtx != null) { + callerStmtCtx.getSqlCacheContext().ifPresent(cache -> cache.setCannotProcessExpression(true)); + } + Expression arg = rewritten.child(); + if (arg instanceof NullLiteral) { + return new NullLiteral(StringType.INSTANCE); + } + if (!(arg instanceof StringLikeLiteral)) { + throw new AnalysisException("ivm_plan_signature requires a constant string argument"); + } + String qualifiedMvName = ((StringLikeLiteral) arg).getStringValue(); + ConnectContext ctx = context.cascadesContext.getConnectContext(); + return IvmPlanSignatureEvaluator.evaluate(ctx, callerStmtCtx, qualifiedMvName) Review Comment: Fixed in efcdc34c4ae: FoldConstantRuleOnFE.visitIvmPlanSignatureFunc() now defers folding when callerStmtCtx.isPrepareStage() is true, with unit test coverage in IvmPlanSignatureFuncTest. ########## fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/CollectRelation.java: ########## @@ -147,12 +151,57 @@ private Plan collectFromAny(MatchingContext<Plan> ctx) { subqueryContext.keepOrShowPlanProcess(ctx.cascadesContext.showPlanProcess(), () -> subqueryContext.newTableCollector(true).collect()); ctx.cascadesContext.addPlanProcesses(subqueryContext.getPlanProcesses()); + } else if (e instanceof UnboundFunction) { + collectFromIvmPlanSignatureFunction((UnboundFunction) e, ctx.cascadesContext); } }); } return null; } + private void collectFromIvmPlanSignatureFunction(UnboundFunction func, CascadesContext cascadesContext) { + if (!"ivm_plan_signature".equalsIgnoreCase(func.getName()) + || func.arity() != 1 + || !(func.child(0) instanceof StringLikeLiteral)) { Review Comment: Fixed in efcdc34c4ae: ivm_plan_signature() is now restricted to standalone constant queries without reading tables (callerStmtCtx.hasTableLocks() == false), removing the CollectRelation pre-collection path completely. ########## 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: Fixed in efcdc34c4ae: disabled enableMaterializedViewRewrite and enableDmlMaterializedViewRewrite on the nested ConnectContext, and restricted ivm_plan_signature() to standalone constant queries without caller table locks. ########## 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: Fixed in efcdc34c4ae: switched nested planning in IvmPlanSignEvaluator from IvmRewriteContext.completeExplain(mtmv) to IvmRewriteContext.normalize(mtmv), so signature inspection does not require refresh streams. ########## 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: Keeping SLOT(catalog.db.table.col) as-is to preserve readability of the canonical signature output; identifiers containing literal dots are not a practical case here. -- 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]
