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


##########
fe/fe-core/src/main/java/org/apache/doris/job/extensions/mtmv/MTMVTask.java:
##########
@@ -1009,8 +1010,8 @@ private IvmIncrRefreshResult 
executeSingleIvmAttempt(MTMVRefreshContext refreshC
         try {
             ivmResult = executeWithRetry(() -> {
                 signatureRef.set(null);
-                ConnectContext ivmConnectContext = 
MTMVPlanUtil.createMTMVContext(mtmv,
-                        MTMVPlanUtil.DISABLE_RULES_WHEN_RUN_MTMV_TASK);
+                ConnectContext ivmConnectContext = 
MTMVPlanUtil.createMTMVRefreshContext(mtmv,
+                        MTMVPlanUtil.DISABLE_RULES_WHEN_RUN_MTMV_TASK, 
taskContext.getSessionVariables());

Review Comment:
   [P1] Keep the IVM delta rewrite mandatory for incremental refresh
   
   For a populated append-only DUP-key IVM view defined by `SELECT id FROM 
base`, append a new base row and issue `REFRESH /*+ 
SET_VAR(disable_nereids_rules='IVM_INCR_REFRESH_MTMV') */ MATERIALIZED VIEW mv 
INCREMENTAL`. The new context accepts the setting and `CustomRewriteJob` skips 
the delta rule. Detail normalization leaves the base scan in place, so the 
planned write becomes:
   
   ```text
   InsertInto(mv)
     Project(id)
       OlapScan(base)  [old rows plus new rows]
   ```
   
   The DUP-key sink appends the full result, duplicating old rows. With no 
stream scan, `InsertIntoTableCommand` attaches no stream offsets, and 
`MTMVTask` can still report success. Keep the required IVM rules outside user 
control for refreshes, or fail the operation before inserting if the delta 
rewrite did not run. Cover this with a populated append-only view and a pending 
append.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java:
##########
@@ -1911,6 +1921,191 @@ public LogicalPlan 
visitRefreshMTMVDryRun(RefreshMTMVDryRunContext ctx) {
         return new RefreshMTMVCommand(refreshMTMVInfo, false, true, 
dryRunLimit);
     }
 
+    private Map<String, String> extractRefreshSetVarHints(ParserRuleContext 
stmtCtx,
+            TerminalNode refreshToken, TerminalNode materializedToken) {
+        if (selectHintMap == null || selectHintMap.isEmpty()) {
+            return ImmutableMap.of();
+        }
+        Pair<Integer, Integer> statementBounds = 
getStatementHintBounds(stmtCtx);
+        int stmtLowerBound = statementBounds.first;
+        int stmtUpperBound = statementBounds.second;
+        int refreshStopIndex = refreshToken.getSymbol().getStopIndex();
+        int materializedStartIndex = 
materializedToken.getSymbol().getStartIndex();
+
+        List<Map.Entry<Integer, ParserRuleContext>> sortedHints = new 
ArrayList<>(selectHintMap.entrySet());
+        sortedHints.sort(Map.Entry.comparingByKey());
+
+        Map<String, String> sessionVariables = Maps.newLinkedHashMap();
+        Map<String, String> originalKeyByLower = Maps.newHashMap();
+        for (Map.Entry<Integer, ParserRuleContext> entry : sortedHints) {
+            int hintStartIndex = entry.getKey();
+            if (hintStartIndex <= stmtLowerBound || hintStartIndex >= 
stmtUpperBound) {
+                continue;
+            }
+            if (hintStartIndex <= refreshStopIndex || hintStartIndex >= 
materializedStartIndex) {
+                throw new AnalysisException(
+                        "Hint must be placed right after REFRESH in REFRESH 
MATERIALIZED VIEW");
+            }
+            ParserRuleContext hintCtx = entry.getValue();
+            if (!(hintCtx instanceof SelectHintContext)) {
+                throw new AnalysisException("Invalid hint syntax in REFRESH 
MATERIALIZED VIEW");
+            }
+            SelectHintContext selectHintContext = (SelectHintContext) hintCtx;
+            if (hasParseError(selectHintContext) || 
selectHintContext.HINT_END() == null
+                    || selectHintContext.hintStatements.isEmpty()) {
+                throw new AnalysisException("Invalid hint syntax in REFRESH 
MATERIALIZED VIEW");
+            }
+            for (HintStatementContext hintStatement : 
selectHintContext.hintStatements) {
+                if (hintStatement.USE_MV() != null || 
hintStatement.NO_USE_MV() != null
+                        || hintStatement.hintName() == null
+                        || 
!hintStatement.hintName().getText().equalsIgnoreCase("set_var")) {
+                    throw new AnalysisException(
+                            "Only SET_VAR hint is supported in REFRESH 
MATERIALIZED VIEW");
+                }
+                SelectHintSetVar setVar = buildSelectHintSetVar(hintStatement, 
true);
+                for (Map.Entry<String, Optional<String>> kv : 
setVar.getParameters().entrySet()) {
+                    String parameterName = kv.getKey();
+                    String lowerKey = parameterName.toLowerCase(Locale.ROOT);
+                    String prevKey = originalKeyByLower.put(lowerKey, 
parameterName);
+                    if (prevKey != null) {
+                        sessionVariables.remove(prevKey);
+                    }
+                    sessionVariables.put(parameterName, kv.getValue().get());
+                }
+            }
+        }
+        return sessionVariables;
+    }
+
+    /**
+     * Parse and construct a {@link SelectHintSetVar} without applying it to 
the current statement.
+     * Callers that want statement-level application invoke {@link 
SelectHintSetVar#setVarOnceInSql}
+     * separately. When {@code strict} is true (used by REFRESH MATERIALIZED 
VIEW), empty parameter
+     * lists, keyless constants, missing values, and null values are rejected 
explicitly.
+     */
+    private SelectHintSetVar buildSelectHintSetVar(HintStatementContext 
hintStatement, boolean strict) {
+        if (strict && hintStatement.parameters.isEmpty()) {
+            throw new AnalysisException(
+                    "SET_VAR hint requires at least one parameter in REFRESH 
MATERIALIZED VIEW");
+        }
+        String hintName = 
hintStatement.hintName().getText().toLowerCase(Locale.ROOT);
+        Map<String, Optional<String>> parameters = Maps.newLinkedHashMap();
+        Map<String, String> originalKeyByLower = strict ? Maps.newHashMap() : 
null;
+        for (HintAssignmentContext kv : hintStatement.parameters) {
+            if (kv.key == null) {
+                if (strict) {
+                    throw new AnalysisException(
+                            "Invalid SET_VAR hint parameter in REFRESH 
MATERIALIZED VIEW");
+                }
+                continue;
+            }
+            if (strict && kv.skew != null) {
+                throw new AnalysisException(
+                        "Invalid SET_VAR hint parameter: skew is not supported 
in SET_VAR");
+            }
+            if (strict && kv.constantValue == null && kv.identifierValue == 
null) {
+                throw new AnalysisException(
+                        "Invalid SET_VAR hint parameter in REFRESH 
MATERIALIZED VIEW");
+            }
+            String parameterName = visitIdentifierOrText(kv.key);
+            Optional<String> value = Optional.empty();
+            if (kv.constantValue != null) {
+                if (strict && !(kv.constantValue instanceof 
DorisParser.NullLiteralContext
+                        || kv.constantValue instanceof 
DorisParser.TypeConstructorContext
+                        || kv.constantValue instanceof 
DorisParser.NumericLiteralContext
+                        || kv.constantValue instanceof 
DorisParser.BooleanLiteralContext
+                        || kv.constantValue instanceof 
DorisParser.StringLiteralContext)) {
+                    throw new AnalysisException(
+                            "Invalid SET_VAR hint parameter value for '" + 
parameterName + "'");
+                }
+                Object visited = visit(kv.constantValue);
+                if (strict && !(visited instanceof Literal)) {
+                    throw new AnalysisException(
+                            "Invalid SET_VAR hint parameter value for '" + 
parameterName + "'");
+                }
+                value = Optional.ofNullable(((Literal) 
visited).toLegacyLiteral().getStringValue());
+            } else if (kv.identifierValue != null) {
+                // maybe we should throw exception when the identifierValue is 
quoted identifier
+                value = Optional.ofNullable(kv.identifierValue.getText());
+            }
+            if (strict && !value.isPresent()) {
+                throw new AnalysisException(
+                        "Invalid SET_VAR hint parameter value for '" + 
parameterName + "'");
+            }
+            // Remove any prior entry before putting so LinkedHashMap moves 
the repeated key to
+            // its final source position (preserving last-wins order across 
case variants/aliases).
+            if (strict) {
+                String lowerKey = parameterName.toLowerCase(Locale.ROOT);
+                String prevKey = originalKeyByLower.put(lowerKey, 
parameterName);
+                if (prevKey != null) {
+                    parameters.remove(prevKey);
+                }
+            } else {
+                parameters.remove(parameterName);

Review Comment:
   [P2] Preserve existing SELECT hint assignment order
   
   `SELECT /*+ SET_VAR(query_timeout=100, max_execution_time=3600000, 
query_timeout=1) */ @@query_timeout` previously applied the final 
`query_timeout` value in the first key's slot, then set `max_execution_time`, 
which also writes the timeout and left it at 3600 seconds. The non-strict 
removal moves `query_timeout` after `max_execution_time` and changes the 
effective timeout to one second. This can terminate an existing SELECT that 
previously completed. Keep removal and reinsertion in strict REFRESH parsing 
and add a SELECT check for the coupled setters.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java:
##########
@@ -1911,6 +1921,191 @@ public LogicalPlan 
visitRefreshMTMVDryRun(RefreshMTMVDryRunContext ctx) {
         return new RefreshMTMVCommand(refreshMTMVInfo, false, true, 
dryRunLimit);
     }
 
+    private Map<String, String> extractRefreshSetVarHints(ParserRuleContext 
stmtCtx,
+            TerminalNode refreshToken, TerminalNode materializedToken) {
+        if (selectHintMap == null || selectHintMap.isEmpty()) {
+            return ImmutableMap.of();
+        }
+        Pair<Integer, Integer> statementBounds = 
getStatementHintBounds(stmtCtx);
+        int stmtLowerBound = statementBounds.first;
+        int stmtUpperBound = statementBounds.second;
+        int refreshStopIndex = refreshToken.getSymbol().getStopIndex();
+        int materializedStartIndex = 
materializedToken.getSymbol().getStartIndex();
+
+        List<Map.Entry<Integer, ParserRuleContext>> sortedHints = new 
ArrayList<>(selectHintMap.entrySet());
+        sortedHints.sort(Map.Entry.comparingByKey());
+
+        Map<String, String> sessionVariables = Maps.newLinkedHashMap();
+        Map<String, String> originalKeyByLower = Maps.newHashMap();
+        for (Map.Entry<Integer, ParserRuleContext> entry : sortedHints) {
+            int hintStartIndex = entry.getKey();
+            if (hintStartIndex <= stmtLowerBound || hintStartIndex >= 
stmtUpperBound) {
+                continue;
+            }
+            if (hintStartIndex <= refreshStopIndex || hintStartIndex >= 
materializedStartIndex) {
+                throw new AnalysisException(

Review Comment:
   [P2] Restore temporary SELECT hints after a rejected REFRESH in the same 
request
   
   Send `SELECT /*+ SET_VAR(sql_select_limit=1) */ 1; REFRESH MATERIALIZED VIEW 
db1.mv COMPLETE /*+ SET_VAR(query_timeout=10) */` in one MySQL request. 
`visitMultiStatements` visits the SELECT first, and `withHints` immediately 
changes the caller's `sql_select_limit`. The new placement error aborts the 
request before any executor runs. `ConnectProcessor.parseWithFallback` restores 
temporary values for audit-policy failures only. On the next request, an 
ordinary SELECT against a table with two or more rows can silently return just 
one row before executor cleanup restores the original limit. Restore temporary 
hint values on this failure path and test the next query on the same connection.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java:
##########
@@ -1911,6 +1921,191 @@ public LogicalPlan 
visitRefreshMTMVDryRun(RefreshMTMVDryRunContext ctx) {
         return new RefreshMTMVCommand(refreshMTMVInfo, false, true, 
dryRunLimit);
     }
 
+    private Map<String, String> extractRefreshSetVarHints(ParserRuleContext 
stmtCtx,
+            TerminalNode refreshToken, TerminalNode materializedToken) {
+        if (selectHintMap == null || selectHintMap.isEmpty()) {
+            return ImmutableMap.of();
+        }
+        Pair<Integer, Integer> statementBounds = 
getStatementHintBounds(stmtCtx);
+        int stmtLowerBound = statementBounds.first;
+        int stmtUpperBound = statementBounds.second;
+        int refreshStopIndex = refreshToken.getSymbol().getStopIndex();
+        int materializedStartIndex = 
materializedToken.getSymbol().getStartIndex();
+
+        List<Map.Entry<Integer, ParserRuleContext>> sortedHints = new 
ArrayList<>(selectHintMap.entrySet());
+        sortedHints.sort(Map.Entry.comparingByKey());
+
+        Map<String, String> sessionVariables = Maps.newLinkedHashMap();
+        Map<String, String> originalKeyByLower = Maps.newHashMap();
+        for (Map.Entry<Integer, ParserRuleContext> entry : sortedHints) {
+            int hintStartIndex = entry.getKey();
+            if (hintStartIndex <= stmtLowerBound || hintStartIndex >= 
stmtUpperBound) {
+                continue;
+            }
+            if (hintStartIndex <= refreshStopIndex || hintStartIndex >= 
materializedStartIndex) {
+                throw new AnalysisException(
+                        "Hint must be placed right after REFRESH in REFRESH 
MATERIALIZED VIEW");
+            }
+            ParserRuleContext hintCtx = entry.getValue();
+            if (!(hintCtx instanceof SelectHintContext)) {
+                throw new AnalysisException("Invalid hint syntax in REFRESH 
MATERIALIZED VIEW");
+            }
+            SelectHintContext selectHintContext = (SelectHintContext) hintCtx;
+            if (hasParseError(selectHintContext) || 
selectHintContext.HINT_END() == null
+                    || selectHintContext.hintStatements.isEmpty()) {
+                throw new AnalysisException("Invalid hint syntax in REFRESH 
MATERIALIZED VIEW");
+            }
+            for (HintStatementContext hintStatement : 
selectHintContext.hintStatements) {
+                if (hintStatement.USE_MV() != null || 
hintStatement.NO_USE_MV() != null
+                        || hintStatement.hintName() == null
+                        || 
!hintStatement.hintName().getText().equalsIgnoreCase("set_var")) {
+                    throw new AnalysisException(
+                            "Only SET_VAR hint is supported in REFRESH 
MATERIALIZED VIEW");
+                }
+                SelectHintSetVar setVar = buildSelectHintSetVar(hintStatement, 
true);
+                for (Map.Entry<String, Optional<String>> kv : 
setVar.getParameters().entrySet()) {
+                    String parameterName = kv.getKey();
+                    String lowerKey = parameterName.toLowerCase(Locale.ROOT);
+                    String prevKey = originalKeyByLower.put(lowerKey, 
parameterName);
+                    if (prevKey != null) {
+                        sessionVariables.remove(prevKey);
+                    }
+                    sessionVariables.put(parameterName, kv.getValue().get());
+                }
+            }
+        }
+        return sessionVariables;
+    }
+
+    /**
+     * Parse and construct a {@link SelectHintSetVar} without applying it to 
the current statement.
+     * Callers that want statement-level application invoke {@link 
SelectHintSetVar#setVarOnceInSql}
+     * separately. When {@code strict} is true (used by REFRESH MATERIALIZED 
VIEW), empty parameter
+     * lists, keyless constants, missing values, and null values are rejected 
explicitly.
+     */
+    private SelectHintSetVar buildSelectHintSetVar(HintStatementContext 
hintStatement, boolean strict) {
+        if (strict && hintStatement.parameters.isEmpty()) {
+            throw new AnalysisException(
+                    "SET_VAR hint requires at least one parameter in REFRESH 
MATERIALIZED VIEW");
+        }
+        String hintName = 
hintStatement.hintName().getText().toLowerCase(Locale.ROOT);
+        Map<String, Optional<String>> parameters = Maps.newLinkedHashMap();
+        Map<String, String> originalKeyByLower = strict ? Maps.newHashMap() : 
null;
+        for (HintAssignmentContext kv : hintStatement.parameters) {
+            if (kv.key == null) {
+                if (strict) {
+                    throw new AnalysisException(
+                            "Invalid SET_VAR hint parameter in REFRESH 
MATERIALIZED VIEW");
+                }
+                continue;
+            }
+            if (strict && kv.skew != null) {
+                throw new AnalysisException(
+                        "Invalid SET_VAR hint parameter: skew is not supported 
in SET_VAR");
+            }
+            if (strict && kv.constantValue == null && kv.identifierValue == 
null) {
+                throw new AnalysisException(
+                        "Invalid SET_VAR hint parameter in REFRESH 
MATERIALIZED VIEW");
+            }
+            String parameterName = visitIdentifierOrText(kv.key);
+            Optional<String> value = Optional.empty();
+            if (kv.constantValue != null) {
+                if (strict && !(kv.constantValue instanceof 
DorisParser.NullLiteralContext

Review Comment:
   [P3] Reject unquoted SQL NULL in REFRESH hints
   
   `REFRESH /*+ SET_VAR(disable_nereids_rules=NULL) */ MATERIALIZED VIEW mv 
COMPLETE` accepts the null literal because legacy 
`NullLiteral.getStringValue()` yields the string `"NULL"`. Validation accepts 
that string, queues the refresh, and the worker then fails when 
`getDisableNereidsRules` interprets it as a rule name. Reject 
`NullLiteralContext` in strict parsing and test a string-valued setting so the 
test exercises literal validation.



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