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

liaoxin01 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 b602ca4cbc2 [fix](fe) Stabilize materialized view column order across 
FEs (#70301)
b602ca4cbc2 is described below

commit b602ca4cbc24235b787b6b1d29f86e29666d393b
Author: Xin Liao <[email protected]>
AuthorDate: Thu Dec 3 21:45:56 2026 +0800

    [fix](fe) Stabilize materialized view column order across FEs (#70301)
    
    ### Background
    
    Group commit producers and consumers can be planned on different FEs.
    Their block layouts follow the table's full schema.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: #69660 (same layout issue)
    PR Type: Bugfix
    
    Problem Summary:
    
    Different index-map iteration orders can produce different MV column
    layouts across FEs, causing group commit cast errors or swapped values.
---
 .../java/org/apache/doris/catalog/OlapTable.java   |  10 +-
 .../doris/catalog/OlapTableFullSchemaTest.java     | 137 +++++++++++++++++++++
 .../test_group_commit_multi_mv_wal.out             |  25 ++++
 .../test_group_commit_multi_mv_wal.groovy          |  88 +++++++++++++
 4 files changed, 257 insertions(+), 3 deletions(-)

diff --git a/fe/fe-core/src/main/java/org/apache/doris/catalog/OlapTable.java 
b/fe/fe-core/src/main/java/org/apache/doris/catalog/OlapTable.java
index 71f6c07e6e8..9eeeb625ad7 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/catalog/OlapTable.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/OlapTable.java
@@ -577,8 +577,7 @@ public class OlapTable extends Table implements 
MTMVRelatedTableIf, GsonPostProc
         indexNameToId.put(indexName, indexId);
     }
 
-    // rebuild the full schema of table
-    // the order of columns in fullSchema is meaningless
+    // Keep base columns first, then append index columns in a deterministic 
order.
     public void rebuildFullSchema() {
         fullSchema.clear();
         nameToColumn.clear();
@@ -586,7 +585,9 @@ public class OlapTable extends Table implements 
MTMVRelatedTableIf, GsonPostProc
             fullSchema.add(baseColumn);
             nameToColumn.put(baseColumn.getName(), baseColumn);
         }
-        for (MaterializedIndexMeta indexMeta : getIndexIdToMeta().values()) {
+        // Fresh and Gson-restored metadata can have different map iteration 
orders.
+        // Group commit producers and consumers planned on different FEs need 
the same layout.
+        for (MaterializedIndexMeta indexMeta : new 
TreeMap<>(getIndexIdToMeta()).values()) {
             for (Column column : indexMeta.getSchema()) {
                 if (!nameToColumn.containsKey(column.getDefineName())) {
                     fullSchema.add(column);
@@ -1120,6 +1121,9 @@ public class OlapTable extends Table implements 
MTMVRelatedTableIf, GsonPostProc
             }
         }
 
+        // Remapping IDs can change index order. Rebuild before publishing the 
table
+        // so its layout matches the schema reconstructed by Gson on other FEs.
+        rebuildFullSchema();
         return Status.OK;
     }
 
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/catalog/OlapTableFullSchemaTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/catalog/OlapTableFullSchemaTest.java
new file mode 100644
index 00000000000..8ea27d52a6f
--- /dev/null
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/catalog/OlapTableFullSchemaTest.java
@@ -0,0 +1,137 @@
+// 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.
+
+package org.apache.doris.catalog;
+
+import org.apache.doris.persist.gson.GsonUtils;
+import org.apache.doris.thrift.TStorageType;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicLong;
+
+public class OlapTableFullSchemaTest {
+    @Test
+    public void testSameLayoutAfterMetadataRestoreAndAddingMv() {
+        OlapTable original = createTable();
+        addIndex(original, 1, "mv_a", column("mv_a", 1));
+        addIndex(original, 2, "mv_b", column("mv_b", 2));
+        original.rebuildFullSchema();
+
+        OlapTable restored = 
GsonUtils.GSON.fromJson(GsonUtils.GSON.toJson(original), OlapTable.class);
+        // Gson restores Map<Long, ...> as LinkedHashMap. A new index can 
appear before
+        // existing indexes in the original HashMap, but after them in the 
restored map.
+        for (OlapTable table : List.of(original, restored)) {
+            addIndex(table, 16, "mv_c", column("mv_c", 3));
+            table.rebuildFullSchema();
+        }
+        Assertions.assertEquals(original.getFullSchema(), 
restored.getFullSchema());
+        Assertions.assertEquals(List.of("k", "mv_a", "mv_b", "mv_c"), 
names(original));
+
+        OlapTable restarted = 
GsonUtils.GSON.fromJson(GsonUtils.GSON.toJson(restored), OlapTable.class);
+        Assertions.assertEquals(original.getFullSchema(), 
restarted.getFullSchema());
+        for (OlapTable table : List.of(original, restored, restarted)) {
+            table.deleteIndexInfo("mv_a");
+            Assertions.assertEquals(List.of("k", "mv_b", "mv_c"), 
names(table));
+        }
+    }
+
+    @Test
+    public void testBaseColumnsFirstAndSharedMvColumnSelection() {
+        OlapTable table = createTable();
+        Column baseColumn = table.getBaseSchema().get(0);
+        Column firstShared = column("mv_shared", 1);
+        Column secondShared = column("mv_shared", 2);
+        // Index 16 precedes index 1 in HashMap traversal. Both contain the 
same
+        // MV expression with different index-local IDs, and a copy of the 
base column.
+        addIndex(table, 16, "mv_second", column("k", 9), secondShared, 
column("mv_b", 3));
+        addIndex(table, 1, "mv_first", column("k", 8), firstShared, 
column("mv_a", 4));
+        table.rebuildFullSchema();
+
+        Assertions.assertEquals(List.of("k", "mv_shared", "mv_a", "mv_b"), 
names(table));
+        Assertions.assertSame(baseColumn, table.getFullSchema().get(0));
+        Assertions.assertSame(firstShared, table.getColumn("mv_shared"));
+        Assertions.assertEquals(2, 
table.getIndexMetaByIndexId(16).getSchema().get(1).getUniqueId());
+
+        table.deleteIndexInfo("mv_first");
+        Assertions.assertEquals(List.of("k", "mv_shared", "mv_b"), 
names(table));
+        Assertions.assertSame(secondShared, table.getColumn("mv_shared"));
+    }
+
+    @Test
+    public void testSameLayoutAfterRestoreRemapsIndexIds() {
+        OlapTable table = createTable();
+        Column baseColumn = table.getBaseSchema().get(0);
+        Column firstShared = column("mv_shared", 1);
+        Column secondShared = column("mv_shared", 2);
+        addIndex(table, 1, "mv_first", firstShared, column("mv_a", 3));
+        addIndex(table, 16, "mv_second", secondShared, column("mv_b", 4));
+        table.rebuildFullSchema();
+        Assertions.assertEquals(List.of("k", "mv_shared", "mv_a", "mv_b"), 
names(table));
+        Assertions.assertSame(firstShared, table.getColumn("mv_shared"));
+
+        Env env = Mockito.mock(Env.class);
+        AtomicLong nextId = new AtomicLong(1000);
+        Mockito.when(env.getNextId()).thenAnswer(invocation -> 
nextId.getAndIncrement());
+        // RESTORE allocates new IDs in HashMap order, visiting index 16 
before index 1.
+        try (MockedStatic<Env> envStatic = Mockito.mockStatic(Env.class)) {
+            envStatic.when(Env::getCurrentColocateIndex).thenReturn(new 
ColocateTableIndex());
+            Assertions.assertTrue(table.resetIdsForRestore(env, new 
Database(2000, "restored_db"),
+                    ReplicaAllocation.DEFAULT_ALLOCATION, false, false, new 
ArrayList<>(), "source_db").ok());
+        }
+        Assertions.assertTrue(table.getIndexIdByName("mv_second") < 
table.getIndexIdByName("mv_first"));
+
+        // The leader publishes this object; followers deserialize the same 
metadata.
+        OlapTable follower = 
GsonUtils.GSON.fromJson(GsonUtils.GSON.toJson(table), OlapTable.class);
+        Assertions.assertEquals(follower.getFullSchema(), 
table.getFullSchema());
+        Assertions.assertEquals(List.of("k", "mv_shared", "mv_b", "mv_a"), 
names(table));
+        Assertions.assertSame(baseColumn, table.getFullSchema().get(0));
+        Assertions.assertSame(secondShared, table.getColumn("mv_shared"));
+        Assertions.assertEquals(follower.getColumn("mv_shared").getUniqueId(),
+                table.getColumn("mv_shared").getUniqueId());
+    }
+
+    private static OlapTable createTable() {
+        List<Column> schema = new ArrayList<>(List.of(column("k", 0)));
+        OlapTable table = new OlapTable(100, "tbl", schema, KeysType.DUP_KEYS,
+                new SinglePartitionInfo(), new RandomDistributionInfo(1));
+        // Keep the base index ID above the MV IDs to verify that base columns 
stay first.
+        table.setBaseIndexId(32);
+        addIndex(table, 32, "tbl", schema.get(0));
+        return table;
+    }
+
+    private static Column column(String name, int uniqueId) {
+        Column column = new Column(name, PrimitiveType.INT);
+        column.setUniqueId(uniqueId);
+        return column;
+    }
+
+    private static void addIndex(OlapTable table, long id, String name, 
Column... columns) {
+        table.setIndexMeta(id, name, new ArrayList<>(List.of(columns)), 0, 1, 
(short) 1,
+                TStorageType.COLUMN, KeysType.DUP_KEYS);
+    }
+
+    private static List<String> names(OlapTable table) {
+        return table.getFullSchema().stream().map(Column::getName).toList();
+    }
+}
diff --git 
a/regression-test/data/insert_p0/group_commit/test_group_commit_multi_mv_wal.out
 
b/regression-test/data/insert_p0/group_commit/test_group_commit_multi_mv_wal.out
new file mode 100644
index 00000000000..f9b94fa8823
--- /dev/null
+++ 
b/regression-test/data/insert_p0/group_commit/test_group_commit_multi_mv_wal.out
@@ -0,0 +1,25 @@
+-- This file is automatically generated. You should know what you did if you 
want to edit this
+-- !before_replay --
+0
+
+-- !base --
+1      alpha   10
+1      alpha   40
+2      beta    20
+2      beta    50
+3      alpha   \N
+
+-- !mv_int --
+1      50
+2      70
+3      \N
+
+-- !mv_string --
+alpha  50
+beta   70
+
+-- !mv_count --
+1      2
+2      2
+3      0
+
diff --git 
a/regression-test/suites/insert_p0/group_commit/test_group_commit_multi_mv_wal.groovy
 
b/regression-test/suites/insert_p0/group_commit/test_group_commit_multi_mv_wal.groovy
new file mode 100644
index 00000000000..77e496525d8
--- /dev/null
+++ 
b/regression-test/suites/insert_p0/group_commit/test_group_commit_multi_mv_wal.groovy
@@ -0,0 +1,88 @@
+// 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.
+
+import org.awaitility.Awaitility
+import static java.util.concurrent.TimeUnit.SECONDS
+
+suite("test_group_commit_multi_mv_wal", "nonConcurrent") {
+    sql "DROP TABLE IF EXISTS test_group_commit_multi_mv_wal"
+    sql """
+        CREATE TABLE test_group_commit_multi_mv_wal (
+            k INT NOT NULL,
+            s VARCHAR(32) NOT NULL,
+            v INT NULL
+        ) DUPLICATE KEY(k)
+        DISTRIBUTED BY HASH(k) BUCKETS 1
+        PROPERTIES ("replication_num" = "1", "group_commit_interval_ms" = 
"2000")
+    """
+    createMV """CREATE MATERIALIZED VIEW multi_mv_int AS
+        SELECT k AS int_key, SUM(v) AS int_sum
+        FROM test_group_commit_multi_mv_wal GROUP BY k"""
+    createMV """CREATE MATERIALIZED VIEW multi_mv_string AS
+        SELECT s AS string_key, SUM(v) AS string_sum
+        FROM test_group_commit_multi_mv_wal GROUP BY s"""
+    createMV """CREATE MATERIALIZED VIEW multi_mv_count AS
+        SELECT k AS count_key, COUNT(v) AS value_count
+        FROM test_group_commit_multi_mv_wal GROUP BY k"""
+
+    String loadError = "LoadBlockQueue._finish_group_commit_load.load_error"
+    String replayStop = "WalTable.replay_wals.stop"
+    try {
+        GetDebugPoint().enableDebugPointForAllBEs(loadError)
+        GetDebugPoint().enableDebugPointForAllBEs(replayStop)
+        for (String data : ["1,alpha,10\n2,beta,20\n3,alpha,\\N\n", 
"1,alpha,40\n2,beta,50\n"]) {
+            long txnId = 0
+            streamLoad {
+                table "test_group_commit_multi_mv_wal"
+                set "column_separator", ","
+                set "group_commit", "async_mode"
+                unset "label"
+                inputStream new ByteArrayInputStream(data.getBytes("UTF-8"))
+                time 10000
+                check { result, exception, startTime, endTime ->
+                    assertNull(exception)
+                    def response = parseJson(result)
+                    assertEquals("Success", response.Status)
+                    assertEquals(data.readLines().size(), 
response.NumberTotalRows as int)
+                    txnId = response.TxnId as long
+                    assertTrue(txnId > 0)
+                }
+            }
+            Awaitility.await().atMost(30, SECONDS).pollInterval(1, 
SECONDS).until {
+                def txn = sql_return_maparray "SHOW TRANSACTION WHERE ID = 
${txnId}"
+                return txn.size() == 1 && txn[0].TransactionStatus == "ABORTED"
+            }
+        }
+        qt_before_replay "SELECT COUNT(*) FROM test_group_commit_multi_mv_wal"
+        // Original transactions remain forced to abort; only replay can 
publish these rows.
+        GetDebugPoint().disableDebugPointForAllBEs(replayStop)
+        Awaitility.await().atMost(90, SECONDS).pollInterval(1, SECONDS).until {
+            def rows = sql "SELECT COUNT(*) FROM 
test_group_commit_multi_mv_wal"
+            return rows[0][0] == 5
+        }
+        order_qt_base "SELECT * FROM test_group_commit_multi_mv_wal"
+        order_qt_mv_int "SELECT * FROM test_group_commit_multi_mv_wal INDEX 
multi_mv_int"
+        order_qt_mv_string "SELECT * FROM test_group_commit_multi_mv_wal INDEX 
multi_mv_string"
+        order_qt_mv_count "SELECT * FROM test_group_commit_multi_mv_wal INDEX 
multi_mv_count"
+    } finally {
+        try {
+            GetDebugPoint().disableDebugPointForAllBEs(replayStop)
+        } finally {
+            GetDebugPoint().disableDebugPointForAllBEs(loadError)
+        }
+    }
+}


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

Reply via email to