This is an automated email from the ASF dual-hosted git repository.

yujun777 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/master by this push:
     new 2973c769f8d [fix](mtmv) Check MV partition coverage when union 
compensation is disabled (#71138)
2973c769f8d is described below

commit 2973c769f8dc8199b2cd41181b26fc91887e4a3d
Author: yujun <[email protected]>
AuthorDate: Tue Dec 1 07:12:57 2026 +0800

    [fix](mtmv) Check MV partition coverage when union compensation is disabled 
(#71138)
    
    ### Background
    
    An asynchronous materialized view (MV) tracks freshness by partition.
    The optimizer can use fresh MV partitions and, when UNION ALL
    compensation is enabled, read missing partitions from the base table.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: #49514 (introduced the partition-check gate)
    PR Type: Bugfix
    
    Problem Summary:
    
    With `enable_materialized_view_union_rewrite=false`, the optimizer could
    rewrite a query to scan a stale partition of a partially fresh MV. The
    rewrite now checks partition coverage before using the MV. A query
    covered by fresh partitions can still use the MV, and a query that needs
    data from a stale partition falls back to the base table when
    compensation is disabled.
    
    In the regression fixture, the MV contains `1` and `10`. The base table
    receives an additional `11` in its second partition after the MV
    refresh.
    
    ```sql
    SELECT SUM(k) FROM partition_freshness_base;
    ```
    
    | Before the fix | With the fix |
    |---|---|
    | `11` from the MV | `22` from the base table |
    
    ### Details
    
    - **Frequency:** Reproducible when UNION compensation is disabled and
    the optimizer selects a partially fresh MV for a query spanning a stale
    partition.
    - **Root cause:** `AbstractMaterializedViewRule` used the UNION switch
    to gate invalid-partition calculation. With the switch off, it could
    admit an MV scan with incomplete coverage.
    - **Why existing tests missed it:** `PartitionCompensatorTest` and
    `PartitionCompensatorBatchTest` cover partition calculation. The
    `grace_period` and `partition_curd_union_rewrite` suites cover freshness
    and compensation with the switch enabled.
    - **Fix:** Calculate partition coverage for eligible MV candidates and
    check the switch when the query needs base-table partitions. The same
    calculation can remove unused or stale MV partitions when the query is
    fully covered by the fresh ones.
    - **Other paths and branches:** The shared rule serves both pre-rewrite
    and CBO. The same gate is present in `branch-3.1`, `branch-4.0`,
    `branch-4.1`, and `branch-4.2` by source inspection.
    - **Behavior change:** EXPLAIN can report that a candidate was rejected
    because it requires compensation and UNION compensation is disabled.
    
    ### Testing
    
    - `partition_freshness_without_union` failed the base-table plan
    assertion on the unmodified master baseline and passed with the fix.
    With UNION compensation disabled, the fresh-only query scanned one MV
    partition and returned `1`. The stale-only and full-table queries
    scanned the base table and returned `21` and `22`.
    - Seven suites passed locally across the MV `availability` and
    `union_rewrite` directories in shared-nothing mode. The Hive-dependent
    suite was excluded.
    
    ### Release note
    
    With UNION compensation disabled, queries that need a stale asynchronous
    MV partition now read current data from the base table. Queries covered
    by fresh MV partitions remain eligible for MV rewrite.
---
 .../mv/AbstractMaterializedViewRule.java           | 13 +++-
 .../partition_freshness_without_union.out          | 10 +++
 .../partition_freshness_without_union.groovy       | 77 ++++++++++++++++++++++
 3 files changed, 97 insertions(+), 3 deletions(-)

diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/AbstractMaterializedViewRule.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/AbstractMaterializedViewRule.java
index 81b068194d2..c6fc1937f3b 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/AbstractMaterializedViewRule.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/AbstractMaterializedViewRule.java
@@ -326,9 +326,8 @@ public abstract class AbstractMaterializedViewRule 
implements ExplorationRuleFac
             if (rewrittenPlan == null) {
                 continue;
             }
-            Pair<Map<BaseTableInfo, Set<String>>, Map<BaseColInfo, 
Set<String>>> invalidPartitions;
-            if (PartitionCompensator.needUnionRewrite(materializationContext, 
cascadesContext.getStatementContext())
-                    && sessionVariable.isEnableMaterializedViewUnionRewrite()) 
{
+            // Validate partition coverage even when union compensation is 
disabled.
+            if (PartitionCompensator.needUnionRewrite(materializationContext, 
cascadesContext.getStatementContext())) {
                 MTMV mtmv = ((AsyncMaterializationContext) 
materializationContext).getMtmv();
                 Map<List<String>, Set<String>> queryUsedPartitions = 
PartitionCompensator.getQueryUsedPartitions(
                         cascadesContext.getStatementContext(), 
queryStructInfo.getRelationBitSet());
@@ -363,6 +362,7 @@ public abstract class AbstractMaterializedViewRule 
implements ExplorationRuleFac
                     }
                     return rewriteResults;
                 }
+                Pair<Map<BaseTableInfo, Set<String>>, Map<BaseColInfo, 
Set<String>>> invalidPartitions;
                 try {
                     invalidPartitions = 
calcInvalidPartitions(queryUsedPartitions, rewrittenPlan,
                             cascadesContext, (AsyncMaterializationContext) 
materializationContext);
@@ -383,6 +383,13 @@ public abstract class AbstractMaterializedViewRule 
implements ExplorationRuleFac
                 }
                 boolean needRemoveMvPartitions = 
!invalidPartitions.key().isEmpty();
                 boolean needBaseTableUnion = 
!invalidPartitions.value().isEmpty();
+                if (needBaseTableUnion && 
!sessionVariable.isEnableMaterializedViewUnionRewrite()) {
+                    materializationContext.recordFailReason(queryStructInfo,
+                            "Base table partition compensation is disabled",
+                            () -> String.format("base table partitions 
requiring compensation: %s",
+                                    invalidPartitions.value()));
+                    return rewriteResults;
+                }
                 if (needBaseTableUnion && !canUnionRewrite(queryPlan,
                         (AsyncMaterializationContext) materializationContext, 
cascadesContext)) {
                     materializationContext.recordFailReason(queryStructInfo,
diff --git 
a/regression-test/data/nereids_rules_p0/mv/availability/partition_freshness_without_union.out
 
b/regression-test/data/nereids_rules_p0/mv/availability/partition_freshness_without_union.out
new file mode 100644
index 00000000000..d331968ee23
--- /dev/null
+++ 
b/regression-test/data/nereids_rules_p0/mv/availability/partition_freshness_without_union.out
@@ -0,0 +1,10 @@
+-- This file is automatically generated. You should know what you did if you 
want to edit this
+-- !all_partitions --
+22
+
+-- !fresh_partition --
+1
+
+-- !stale_partition --
+21
+
diff --git 
a/regression-test/suites/nereids_rules_p0/mv/availability/partition_freshness_without_union.groovy
 
b/regression-test/suites/nereids_rules_p0/mv/availability/partition_freshness_without_union.groovy
new file mode 100644
index 00000000000..62273a239f0
--- /dev/null
+++ 
b/regression-test/suites/nereids_rules_p0/mv/availability/partition_freshness_without_union.groovy
@@ -0,0 +1,77 @@
+// 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.
+
+suite("partition_freshness_without_union") {
+    sql "SET enable_sql_cache = false"
+    sql "SET enable_materialized_view_rewrite = true"
+    sql "SET enable_materialized_view_union_rewrite = false"
+
+    sql "DROP MATERIALIZED VIEW IF EXISTS mv_partition_freshness_without_union"
+    sql "DROP TABLE IF EXISTS partition_freshness_base"
+    sql """
+        CREATE TABLE partition_freshness_base (k INT NOT NULL)
+        DUPLICATE KEY(k)
+        PARTITION BY RANGE(k) (
+            PARTITION p1 VALUES LESS THAN (10),
+            PARTITION p2 VALUES LESS THAN (20)
+        )
+        DISTRIBUTED BY HASH(k) BUCKETS 1
+        PROPERTIES ('replication_num' = '1')
+    """
+    sql "INSERT INTO partition_freshness_base VALUES (1), (10)"
+    sql """
+        CREATE MATERIALIZED VIEW mv_partition_freshness_without_union
+        BUILD IMMEDIATE REFRESH AUTO ON MANUAL
+        PARTITION BY (k)
+        DISTRIBUTED BY HASH(k) BUCKETS 1
+        PROPERTIES ('replication_num' = '1', 'grace_period' = '0')
+        AS SELECT k FROM partition_freshness_base
+    """
+    waitingMTMVTaskFinishedByMvName("mv_partition_freshness_without_union")
+
+    // Keep p1 fresh and make p2 stale without refreshing the view.
+    sql "INSERT INTO partition_freshness_base VALUES (11)"
+    sql "SYNC"
+
+    // Prefer the MV when it is eligible so plan assertions do not depend on 
small-table cost estimates.
+    def allQuery = """
+        SELECT /*+ USE_MV(mv_partition_freshness_without_union) */ SUM(k)
+        FROM partition_freshness_base
+    """
+    explain {
+        sql allQuery
+        contains "partition_freshness_base(partition_freshness_base)"
+        notContains 
"mv_partition_freshness_without_union(mv_partition_freshness_without_union)"
+    }
+    order_qt_all_partitions allQuery
+
+    def freshQuery = "${allQuery} WHERE k < 10"
+    explain {
+        sql freshQuery
+        contains 
"mv_partition_freshness_without_union(mv_partition_freshness_without_union)"
+        contains "partitions=1/2"
+    }
+    order_qt_fresh_partition freshQuery
+
+    def staleQuery = "${allQuery} WHERE k >= 10"
+    explain {
+        sql staleQuery
+        contains "partition_freshness_base(partition_freshness_base)"
+        notContains 
"mv_partition_freshness_without_union(mv_partition_freshness_without_union)"
+    }
+    order_qt_stale_partition staleQuery
+}


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

Reply via email to