hello-stephen commented on code in PR #71190:
URL: https://github.com/apache/doris/pull/71190#discussion_r4750910731


##########
fe/fe-core/src/main/java/org/apache/doris/mtmv/MTMVPlanUtil.java:
##########
@@ -156,6 +165,172 @@ public static ConnectContext createMTMVContext(MTMV mtmv, 
List<RuleType> disable
         return ctx;
     }
 
+    /**
+     * Create an internal MTMV context for refresh execution, dry run, or 
EXPLAIN REFRESH.
+     * Explicit REFRESH SET_VAR hints are applied on top of MTMV defaults so 
they take
+     * precedence over both MTMV defaults and MV query SQL SET_VAR hints. 
Materialized view
+     * rewrite remains forcibly disabled to prevent self-rewrite during 
refresh and keep
+     * REFRESH, DRY RUN, and EXPLAIN REFRESH behavior consistent.
+     */
+    public static ConnectContext createMTMVRefreshContext(MTMV mtmv, 
List<RuleType> disableRules,
+            @Nullable Map<String, String> refreshSessionVariables) {
+        ConnectContext previousContext = ConnectContext.get();
+        ConnectContext ctx = createMTMVContext(mtmv, disableRules);
+        try {
+            applyRefreshSessionVariables(ctx, null, refreshSessionVariables);
+            ctx.getSessionVariable().setEnableMaterializedViewRewrite(false);
+            
ctx.getSessionVariable().setEnableDmlMaterializedViewRewrite(false);
+            ctx.addOverriddenSessionVars(ImmutableSet.of(
+                    SessionVariable.ENABLE_MATERIALIZED_VIEW_REWRITE,
+                    SessionVariable.ENABLE_DML_MATERIALIZED_VIEW_REWRITE));
+            return ctx;
+        } catch (RuntimeException | Error e) {
+            if (previousContext == null) {
+                ConnectContext.remove();
+            } else {
+                previousContext.setThreadLocalInfo();
+            }
+            throw e;
+        }
+    }
+
+    /**
+     * Validate SET_VAR hint parameters from REFRESH MATERIALIZED VIEW against 
a throwaway
+     * ConnectContext carrying the caller's identity, so invalid variables and 
privilege-gated
+     * overrides fail fast without mutating the caller's session or query 
state.
+     */
+    public static void validateRefreshSessionVariables(ConnectContext 
callerCtx,
+            @Nullable Map<String, String> refreshSessionVariables) {
+        if (refreshSessionVariables == null || 
refreshSessionVariables.isEmpty()) {
+            return;
+        }
+        ConnectContext validationCtx = new ConnectContext();
+        validationCtx.setEnv(callerCtx.getEnv());
+        
validationCtx.setCurrentUserIdentity(callerCtx.getCurrentUserIdentity());
+        validationCtx.setSessionVariable(VariableMgr.newSessionVariable());
+        applyRefreshSessionVariables(validationCtx, null, 
refreshSessionVariables);
+        validateRefreshPrivilegedSessionVariables(callerCtx, validationCtx);
+    }
+
+    private static void 
validateRefreshPrivilegedSessionVariables(ConnectContext callerCtx,
+            ConnectContext validationCtx) {
+        SessionVariable sv = validationCtx.getSessionVariable();
+        if 
(validationCtx.isSessionVarOverridden(SessionVariable.CLOUD_CLUSTER) && 
Config.isCloudMode()) {
+            String targetCluster = sv.getCloudCluster();
+            if (Strings.isNullOrEmpty(targetCluster)) {
+                throw new AnalysisException(
+                        "Session variable 'cloud_cluster' cannot be empty in 
REFRESH MATERIALIZED VIEW");
+            }
+            try {
+                
ComputeGroupBindingUtil.validateDeclaredComputeGroup(callerCtx, targetCluster);
+            } catch (UserException e) {
+                throw new AnalysisException(e.getMessage(), e);
+            }
+        }
+        if 
(validationCtx.isSessionVarOverridden(SessionVariable.WORKLOAD_VARIABLE)) {
+            String targetWorkloadGroup = sv.getWorkloadGroup();
+            if (Strings.isNullOrEmpty(targetWorkloadGroup)) {
+                throw new AnalysisException(
+                        "Session variable 'workload_group' cannot be empty in 
REFRESH MATERIALIZED VIEW");
+            }
+            if (!Env.getCurrentEnv().getAccessManager()
+                    .checkWorkloadGroupPriv(callerCtx, targetWorkloadGroup, 
PrivPredicate.USAGE)) {
+                throw new AnalysisException(String.format(
+                        "Access denied; you need (at least one of) the %s 
privilege(s) to use workload group '%s'.",
+                        "USAGE/ADMIN", targetWorkloadGroup));
+            }
+        }
+        if 
(validationCtx.isSessionVarOverridden(SessionVariable.DEFAULT_AI_RESOURCE)) {
+            String targetAiResource = sv.defaultAIResource;
+            if (!Strings.isNullOrEmpty(targetAiResource)
+                    && !Env.getCurrentEnv().getAccessManager()
+                            .checkResourcePriv(callerCtx, targetAiResource, 
PrivPredicate.USAGE)) {
+                throw new 
AnalysisException(ErrorCode.ERR_RESOURCE_ACCESS_DENIED_ERROR.formatErrorMsg(
+                        PrivPredicate.USAGE.getPrivs().toString(), 
targetAiResource));
+            }
+        }
+    }
+
+    /**
+     * Apply REFRESH SET_VAR hints to an internal refresh ConnectContext and 
mark their
+     * canonical names as overridden so MV definition SQL SET_VAR hints cannot 
clobber them.
+     */
+    public static void applyRefreshSessionVariables(ConnectContext ctx, 
@Nullable StatementContext statementContext,
+            @Nullable Map<String, String> refreshSessionVariables) {
+        if (refreshSessionVariables == null || 
refreshSessionVariables.isEmpty()) {
+            return;
+        }
+        // Reject static-backed and result-affecting session variables before 
applying any entry
+        // so hints cannot mutate FE-wide static state or diverge from the 
MV's maintained baseline
+        // semantics (e.g. timezone/sql_mode/skip_delete_* changes breaking 
IVM retractions or
+        // transparent rewrite equivalence).
+        for (String key : refreshSessionVariables.keySet()) {
+            VariableMgr.VarContext varCtx = VariableMgr.getVarContext(key);
+            if (varCtx != null) {
+                if (Modifier.isStatic(varCtx.getField().getModifiers())) {
+                    throw new AnalysisException(
+                            "Static session variable '" + key + "' is not 
supported in REFRESH MATERIALIZED VIEW");
+                }
+                VarAttrDef.VarAttr varAttr = 
varCtx.getField().getAnnotation(VarAttrDef.VarAttr.class);
+                if (varAttr != null && (varAttr.affectQueryResultInPlan() || 
varAttr.affectQueryResultInExecution())) {

Review Comment:
   [P1] Reject dry_run_query before running a mutating refresh
   
   `dry_run_query` is an instance variable without either result-affecting 
annotation, so this guard accepts `REFRESH /*+ SET_VAR(dry_run_query=true) */ 
MATERIALIZED VIEW mv COMPLETE`. For a populated MV over a nonempty base table, 
the option reaches `SessionVariable.toThrift`, and both `VTabletWriter::write` 
and `VTabletWriterV2::write` return OK before writing any rows. The normal 
insert path accepts zero loaded rows/empty tablet commit info, and 
`InsertOverwriteTableCommand` then swaps the empty temporary partitions into 
the MV, reporting a successful refresh. The same option on incremental refresh 
can commit consumed stream offsets without applying the delta. Please reject 
this write-suppressing option before scheduling a refresh (or restrict refresh 
hints to known-safe tuning variables), and add a populated COMPLETE-refresh 
regression that checks the MV retains its expected rows. This is separate from 
the earlier timezone issue: evaluation is unchanged here; the sink discards th
 e writes.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to