yujun777 commented on code in PR #71190:
URL: https://github.com/apache/doris/pull/71190#discussion_r4750063551


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/properties/SelectHintSetVar.java:
##########
@@ -50,13 +51,17 @@ public Map<String, Optional<String>> getParameters() {
      * @param context statement context
      */
     public void setVarOnceInSql(StatementContext context) {
-        SessionVariable sessionVariable = 
context.getConnectContext().getSessionVariable();
+        ConnectContext connectContext = context.getConnectContext();
+        SessionVariable sessionVariable = connectContext.getSessionVariable();
         // set temporary session value, and then revert value in the 'finally 
block' of StmtExecutor#execute
         sessionVariable.setIsSingleSetVar(true);
         for (Map.Entry<String, Optional<String>> kv : 
getParameters().entrySet()) {
             String key = kv.getKey();
             Optional<String> value = kv.getValue();
             if (value.isPresent()) {
+                if (connectContext.isSessionVarOverridden(key)) {

Review Comment:
   Fixed in ef1b694e506. Added bidirectional coupled-variable expansion for 
`query_timeout` and `max_execution_time` in 
`ConnectContext.expandCoupledSessionVars`, so an MV SQL 
`SET_VAR(max_execution_time=...)` cannot overwrite a `REFRESH` hint's 
`query_timeout` (and vice versa). Covered both directions in 
`RefreshMTMVCommandTest.testRefreshHintCoupledTimeoutPrecedenceBothDirections`.



##########
fe/fe-core/src/main/java/org/apache/doris/mtmv/MTMVPlanUtil.java:
##########
@@ -156,6 +163,135 @@ 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;
+        }
+        ConnectContext previousContext = ConnectContext.get();
+        boolean switched = previousContext != ctx;
+        if (switched) {
+            ctx.setThreadLocalInfo();
+        }
+        try {
+            Set<String> overriddenCanonicalNames = 
Sets.newHashSetWithExpectedSize(refreshSessionVariables.size());
+            SessionVariable sessionVariable = ctx.getSessionVariable();
+            for (Map.Entry<String, String> entry : 
refreshSessionVariables.entrySet()) {
+                String key = entry.getKey();
+                String value = entry.getValue();
+                try {
+                    VariableMgr.setVar(sessionVariable, new SetVar(key, new 
StringLiteral(value)));

Review Comment:
   Fixed in 9d20a58ac53. Added a pre-check in 
`MTMVPlanUtil.applyRefreshSessionVariables` via `VariableMgr.getVarContext` to 
reject any static-backed session variable field (such as 
`enable_multi_cluster_sync_load`) before applying any hint entry, preventing 
failed or mixed hints from mutating process-wide static state. Added unit test 
coverage in 
`RefreshMTMVInfoAnalyzeTest.testAnalyzeStaticSessionVarRejectedWithoutMutatingSharedState`.



-- 
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