hello-stephen commented on code in PR #71241: URL: https://github.com/apache/doris/pull/71241#discussion_r4756053776
########## 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); + } else if (part.indexOf('`') >= 0) { + throw new AnalysisException("Invalid materialized view name '" + fullName + "'"); + } + if (StringUtils.isBlank(part)) { + throw new AnalysisException("Invalid materialized view name '" + fullName + + "': empty identifier part"); + } + return part; + } + + 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] Preserve the caller's table lock order during signature evaluation For the valid plan ```text Project(ivm_plan_signature('mv_on_a')) Scan(b) ``` where `mv_on_a` reads `a` and `a.id < b.id`, the caller's `planWithLock` already holds a read lock on `b` when constant folding reaches this nested planner. The MV name is a string, so `CollectRelation` has not added `a` to the caller's lock set. If concurrent `ALTER TABLE a REPLACE WITH TABLE b` acquires `a` first, it waits for `b` while this planner waits for `a`. `StatementContext.lock()` breaks the cycle only after its one-minute timeout, failing the SELECT and stalling the DDL. REPLACE is allowed on changelog tables, so an IVM base table can reach this case. Please discover these dependencies before acquiring caller locks, or evaluate the signature before those locks are held, so all involved tables follow one lock order. -- 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]
