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


##########
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:
   [P3] Assert that no downstream task is queued between upstream batches. The 
suite first checks the count after the upstream task finishes. An 
implementation that sends one notification after the first batch can pass both 
the count and row checks if the downstream worker starts after the final batch. 
Hold the upstream task between batches and check the downstream task IDs before 
releasing it.



##########
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:
   [P2] Account for publish events that arrive after the refresh exits. In 
shared-nothing mode, the insert waiter can observe VISIBLE before the publish 
thread sends DataChangeEvent. If the worker swaps the final batch and closes 
this state first, the swap queues one downstream refresh and the late event can 
queue a second for the same batch. A publication timeout can also let the swap 
finish before the data becomes visible. Tie coalescing to the batch's 
publication lifecycle so a late event can still carry newly visible data when 
needed.



##########
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:
   [P2] Keep pending changes until the last overlapping refresh finishes. ALTER 
refresh info stops the old job without waiting for its worker and creates a 
replacement with the same MV ID and a separate lock. If the replacement 
publishes a batch before the old worker exits, the old worker clears the shared 
flag here and schedules downstream during the replacement's refresh. A later 
batch can trigger another task. Drain the flag when the active count reaches 
zero, or attribute changes to their owning refresh.



##########
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:
   [P2] Recover deferred ON COMMIT triggers after FE failover. If batch 1 has 
swapped its partitions and journaled that change when the leader dies during 
batch 2, this branch has already consumed batch 1's event into a map that dies 
with the leader. The new leader replays the swap without emitting an event, and 
ON COMMIT jobs have no periodic catch-up. The downstream MV can stay stale 
until another upstream change or a manual refresh. Make the pending trigger 
recoverable or reconcile dependent views on leader startup.



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