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


##########
fe/fe-core/src/main/java/org/apache/doris/mtmv/MTMVService.java:
##########
@@ -179,6 +194,40 @@ public void cancelMTMVTask(CancelMTMVTaskInfo info) throws 
MetaNotFoundException
         }
     }
 
+    public void beginRefresh(long mvId) {
+        refreshingMvs.compute(mvId, (k, state) -> {
+            if (state == null) {
+                state = new RefreshState();
+            }
+            state.running++;
+            return state;
+        });
+    }
+
+    public boolean finishRefresh(long mvId) {
+        boolean[] changed = {false};
+        refreshingMvs.computeIfPresent(mvId, (k, state) -> {
+            changed[0] = state.changed;
+            state.changed = false;

Review Comment:
   Fixed in 7e0acdecc8e. `finishRefresh` now only drains and returns 
`state.changed` when `--state.running <= 0`, and 
`MTMVServiceTest.testOverlappingRefreshesDoNotLoseChange` has been updated to 
cover this.



##########
regression-test/suites/mtmv_p0/test_chain_on_commit_coalesce.groovy:
##########
@@ -0,0 +1,169 @@
+// 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("test_chain_on_commit_coalesce") {
+    def dbName = context.config.getDbNameByFile(context.file)
+    def tableName = "test_chain_on_commit_coalesce_tbl"
+    def mvUp = "test_chain_on_commit_coalesce_mv_up"
+    def mvDown = "test_chain_on_commit_coalesce_mv_down"
+    def mvDown2 = "test_chain_on_commit_coalesce_mv_down2"
+
+    def getCommitTaskCount = { String mvName ->
+        def rows = sql_return_maparray """
+            SELECT TaskId FROM tasks('type'='mv')
+            WHERE MvDatabaseName='${dbName}' AND MvName='${mvName}'
+              AND TaskContext LIKE '%"triggerMode":"COMMIT"%'
+        """
+        return rows.size()
+    }
+
+    def waitCommitTaskReached = { String mvName, int minCount ->
+        long deadline = System.currentTimeMillis() + 60_000L
+        while (System.currentTimeMillis() < deadline) {
+            if (getCommitTaskCount(mvName) >= minCount) {
+                return
+            }
+            Thread.sleep(200)
+        }
+        assertTrue(getCommitTaskCount(mvName) >= minCount,
+                "Expected at least ${minCount} COMMIT tasks for ${mvName}, got 
${getCommitTaskCount(mvName)}")
+    }
+
+    sql """drop materialized view if exists ${mvDown2};"""
+    sql """drop materialized view if exists ${mvDown};"""
+    sql """drop materialized view if exists ${mvUp};"""
+    sql """drop table if exists ${tableName};"""
+
+    sql """
+        CREATE TABLE ${tableName} (
+            k1 INT NOT NULL,
+            dt DATE NOT NULL,
+            v1 INT NOT NULL
+        ) ENGINE=OLAP
+        DUPLICATE KEY(k1, dt)
+        PARTITION BY RANGE(dt) (
+            PARTITION p1 VALUES [('2024-01-01'), ('2024-01-02')),
+            PARTITION p2 VALUES [('2024-01-02'), ('2024-01-03')),
+            PARTITION p3 VALUES [('2024-01-03'), ('2024-01-04')),
+            PARTITION p4 VALUES [('2024-01-04'), ('2024-01-05')),
+            PARTITION p5 VALUES [('2024-01-05'), ('2024-01-06')),
+            PARTITION p6 VALUES [('2024-01-06'), ('2024-01-07'))
+        )
+        DISTRIBUTED BY HASH(k1) BUCKETS 2
+        PROPERTIES ('replication_num' = '1');
+    """
+
+    sql """
+        INSERT INTO ${tableName} VALUES
+            (1, '2024-01-01', 10),
+            (2, '2024-01-02', 20),
+            (3, '2024-01-03', 30),
+            (4, '2024-01-04', 40),
+            (5, '2024-01-05', 50),
+            (6, '2024-01-06', 60);
+    """
+
+    // Upstream partitioned MV refreshes 1 partition per batch (6 separate 
batch commits)
+    sql """
+        CREATE MATERIALIZED VIEW ${mvUp}
+        BUILD DEFERRED REFRESH AUTO ON MANUAL
+        PARTITION BY (dt)
+        DISTRIBUTED BY RANDOM BUCKETS 2
+        PROPERTIES (
+            'replication_num' = '1',
+            'refresh_partition_num' = '1'
+        )
+        AS SELECT k1, dt, v1 FROM ${tableName};
+    """
+
+    // Downstream 2nd-level and 3rd-level ON COMMIT MVs
+    sql """
+        CREATE MATERIALIZED VIEW ${mvDown}
+        BUILD DEFERRED REFRESH AUTO ON COMMIT
+        DISTRIBUTED BY RANDOM BUCKETS 2
+        PROPERTIES ('replication_num' = '1')
+        AS SELECT dt, SUM(v1) AS total_v1 FROM ${mvUp} GROUP BY dt;
+    """
+
+    sql """
+        CREATE MATERIALIZED VIEW ${mvDown2}
+        BUILD DEFERRED REFRESH AUTO ON COMMIT
+        DISTRIBUTED BY RANDOM BUCKETS 2
+        PROPERTIES ('replication_num' = '1')
+        AS SELECT COUNT(*) AS day_cnt, SUM(total_v1) AS grand_total FROM 
${mvDown};
+    """
+
+    def jobUp = getJobName(dbName, mvUp)
+    def jobDown = getJobName(dbName, mvDown)
+    def jobDown2 = getJobName(dbName, mvDown2)
+
+    // 1. Refresh all 6 partitions in 6 batches -> downstream MVs must each 
trigger only once
+    sql """REFRESH MATERIALIZED VIEW ${mvUp} AUTO;"""
+    waitingMTMVTaskFinishedByMvName(mvUp, dbName)

Review Comment:
   Updated in 7e0acdecc8e. Added assertions verifying `downTask.CreateTime >= 
upTask.FinishTime` (and `down2Task.CreateTime >= downTask.FinishTime`) so the 
suite checks that downstream tasks are created after the upstream multi-batch 
refresh completes, and also asserted `RefreshMode == 'NOT_REFRESH'` for the 
no-op refresh case.



##########
fe/fe-core/src/main/java/org/apache/doris/mtmv/MTMVService.java:
##########
@@ -199,6 +248,20 @@ public void processEvent(Event event) throws 
EventException {
         } catch (AnalysisException e) {
             throw new EventException(e);
         }
+        boolean suppressed = refreshingMvs.computeIfPresent(table.getId(), (k, 
state) -> {

Review Comment:
   Existing `ON COMMIT` event dispatch and queued `MTMVJob` tasks are already 
in-memory and non-persistent (`MTMVJob.needPersist()` is false), so losing 
pending/running `ON COMMIT` tasks on FE leader failover is pre-existing 
behavior rather than a new durability gap introduced here. Persisting deferred 
triggers in the edit log or reconciling all `ON COMMIT` MVs on leader startup 
is out of scope for this fix.



##########
fe/fe-core/src/main/java/org/apache/doris/mtmv/MTMVService.java:
##########
@@ -179,6 +194,40 @@ public void cancelMTMVTask(CancelMTMVTaskInfo info) throws 
MetaNotFoundException
         }
     }
 
+    public void beginRefresh(long mvId) {
+        refreshingMvs.compute(mvId, (k, state) -> {
+            if (state == null) {
+                state = new RefreshState();
+            }
+            state.running++;
+            return state;
+        });
+    }
+
+    public boolean finishRefresh(long mvId) {
+        boolean[] changed = {false};
+        refreshingMvs.computeIfPresent(mvId, (k, state) -> {
+            changed[0] = state.changed;
+            state.changed = false;
+            state.running--;
+            return state.running <= 0 ? null : state;

Review Comment:
   During `UpdateMvByPartitionCommand`, each batch inserts into a temporary 
partition (emitting `DataChangeEvent`) before synchronously calling 
`replaceTempPartition` (which emits `ReplacePartitionEvent`), so in the normal 
path `DataChangeEvent` arrives before `replaceTempPartition` finishes. Even in 
the rare publish-timeout window where a late `DataChangeEvent` arrives after 
`finishRefresh`, it does not lose data and at worst triggers one extra 
downstream `NOT_REFRESH` check, which is preferable to coupling MTMV refresh 
state into `DatabaseTransactionMgr`.



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