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

github-merge-queue[bot] pushed a commit to branch 
gh-readonly-queue/dev/pr-13358-64cd8b5325617a2c8bfd9ac3682479f428b47e56
in repository https://gitbox.apache.org/repos/asf/seatunnel.git

commit ef7b488cc9ff2f7ee2f09a356b585d957f75900a
Author: Goutam Adwant <[email protected]>
AuthorDate: Thu Nov 26 13:44:09 2026 +0000

    [Fix][Connector-V2][StarRocks] Flush buffered rows before applying a schema 
change (#13358)
---
 .../introduction/configuration/schema-evolution.md |   3 +
 .../introduction/configuration/schema-evolution.md |   2 +
 .../starrocks/sink/StarRocksSinkWriter.java        |  36 +++--
 .../starrocks/sink/StarRocksSinkWriterTest.java    | 176 +++++++++++++++++++++
 .../starrocks/StarRocksSchemaChangeIT.java         | 118 +++++++++++++-
 5 files changed, 321 insertions(+), 14 deletions(-)

diff --git a/docs/en/introduction/configuration/schema-evolution.md 
b/docs/en/introduction/configuration/schema-evolution.md
index 819ecabd1f..cdb06950fc 100644
--- a/docs/en/introduction/configuration/schema-evolution.md
+++ b/docs/en/introduction/configuration/schema-evolution.md
@@ -412,6 +412,9 @@ sink {
   }
 }
 ```
+
+> **Note (schema evolution + batching):** Before a DDL is applied, the 
StarRocks sink loads the rows it has buffered under the previous schema 
(`batch_max_rows` / `batch_max_bytes`), so a schema change cannot drop a 
partial batch. If that load fails, the DDL is not applied and the error is 
raised: the engine replays the rows from the last checkpoint, or the 
multi-table retry resends the batch under the same label.
+
 ### Mysql-CDC -> Doris
 ```
 env {
diff --git a/docs/zh/introduction/configuration/schema-evolution.md 
b/docs/zh/introduction/configuration/schema-evolution.md
index 50f88ce2f5..a1f881dc64 100644
--- a/docs/zh/introduction/configuration/schema-evolution.md
+++ b/docs/zh/introduction/configuration/schema-evolution.md
@@ -388,6 +388,8 @@ sink {
 }
 ```
 
+> **注意(schema 演进 + 批量写入):** 在应用 DDL 之前,StarRocks sink 会先把按旧 schema 
缓冲的数据(`batch_max_rows` / `batch_max_bytes`)加载到 StarRocks,因此 schema 
变更不会丢弃未写完的批次。如果这次加载失败,DDL 不会执行并抛出错误:引擎会从上一次 checkpoint 重放数据,多表重试则会用同一个 label 
重新发送该批次。
+
 ### Mysql-CDC -> Doris
 ```
 env {
diff --git 
a/seatunnel-connectors-v2/connector-starrocks/src/main/java/org/apache/seatunnel/connectors/seatunnel/starrocks/sink/StarRocksSinkWriter.java
 
b/seatunnel-connectors-v2/connector-starrocks/src/main/java/org/apache/seatunnel/connectors/seatunnel/starrocks/sink/StarRocksSinkWriter.java
index 695a4fd9c6..0189dcbe49 100644
--- 
a/seatunnel-connectors-v2/connector-starrocks/src/main/java/org/apache/seatunnel/connectors/seatunnel/starrocks/sink/StarRocksSinkWriter.java
+++ 
b/seatunnel-connectors-v2/connector-starrocks/src/main/java/org/apache/seatunnel/connectors/seatunnel/starrocks/sink/StarRocksSinkWriter.java
@@ -83,24 +83,36 @@ public class StarRocksSinkWriter extends 
AbstractSinkWriter<SeaTunnelRow, Void>
         manager.write(record);
     }
 
+    /**
+     * Rows buffered so far were serialized with the current schema and must 
reach StarRocks before
+     * the table changes, so the current manager is flushed first; the sink 
does not rely on the
+     * engine having flushed it. If that load fails the error is raised and 
nothing else changes.
+     * The new schema is validated before the DDL and adopted only after it, 
so a failure on either
+     * side leaves the writer and the table in step.
+     */
     @Override
     public void applySchemaChange(SchemaChangeEvent event) {
-        this.tableSchema = 
tableSchemaChangeEventDispatcher.reset(tableSchema).apply(event);
-        SeaTunnelRowType seaTunnelRowType = 
tableSchema.toPhysicalRowDataType();
-        this.serializer = createSerializer(sinkConfig, seaTunnelRowType);
+        try {
+            this.manager.close();
+        } catch (IOException e) {
+            throw 
CommonError.closeFailed(StarRocksBaseOptions.CONNECTOR_IDENTITY, e);
+        }
 
-        if (event instanceof RestoreTableSchemaEvent) {
-            try {
-                this.manager.close();
-            } catch (IOException e) {
-                throw 
CommonError.closeFailed(StarRocksBaseOptions.CONNECTOR_IDENTITY, e);
-            }
-            this.manager = new StarRocksSinkManager(sinkConfig, tableSchema);
-            return;
+        TableSchema newSchema = 
tableSchemaChangeEventDispatcher.reset(tableSchema).apply(event);
+        StarRocksISerializer newSerializer =
+                createSerializer(sinkConfig, 
newSchema.toPhysicalRowDataType());
+
+        if (!(event instanceof RestoreTableSchemaEvent)) {
+            applySchemaChangeToStarRocks(event);
         }
 
-        this.manager = new StarRocksSinkManager(sinkConfig, tableSchema);
+        this.tableSchema = newSchema;
+        this.serializer = newSerializer;
+        this.manager = new StarRocksSinkManager(sinkConfig, newSchema);
+    }
 
+    /** Runs the DDL on the StarRocks table over JDBC. */
+    protected void applySchemaChangeToStarRocks(SchemaChangeEvent event) {
         try {
             Class.forName("com.mysql.cj.jdbc.Driver");
         } catch (ClassNotFoundException e) {
diff --git 
a/seatunnel-connectors-v2/connector-starrocks/src/test/java/org/apache/seatunnel/connectors/seatunnel/starrocks/sink/StarRocksSinkWriterTest.java
 
b/seatunnel-connectors-v2/connector-starrocks/src/test/java/org/apache/seatunnel/connectors/seatunnel/starrocks/sink/StarRocksSinkWriterTest.java
index e7fa042c0a..2c3233df4b 100644
--- 
a/seatunnel-connectors-v2/connector-starrocks/src/test/java/org/apache/seatunnel/connectors/seatunnel/starrocks/sink/StarRocksSinkWriterTest.java
+++ 
b/seatunnel-connectors-v2/connector-starrocks/src/test/java/org/apache/seatunnel/connectors/seatunnel/starrocks/sink/StarRocksSinkWriterTest.java
@@ -18,13 +18,21 @@
 package org.apache.seatunnel.connectors.seatunnel.starrocks.sink;
 
 import org.apache.seatunnel.api.sink.SinkWriter;
+import org.apache.seatunnel.api.table.catalog.CatalogTable;
 import org.apache.seatunnel.api.table.catalog.PhysicalColumn;
+import org.apache.seatunnel.api.table.catalog.TableIdentifier;
 import org.apache.seatunnel.api.table.catalog.TablePath;
 import org.apache.seatunnel.api.table.catalog.TableSchema;
+import org.apache.seatunnel.api.table.schema.event.AlterTableAddColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.RestoreTableSchemaEvent;
+import org.apache.seatunnel.api.table.schema.event.SchemaChangeEvent;
 import org.apache.seatunnel.api.table.type.BasicType;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
 import org.apache.seatunnel.common.utils.function.RunnableWithException;
 import 
org.apache.seatunnel.connectors.seatunnel.starrocks.client.StarRocksSinkManager;
 import org.apache.seatunnel.connectors.seatunnel.starrocks.config.SinkConfig;
+import 
org.apache.seatunnel.connectors.seatunnel.starrocks.exception.StarRocksConnectorErrorCode;
+import 
org.apache.seatunnel.connectors.seatunnel.starrocks.exception.StarRocksConnectorException;
 
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.Test;
@@ -33,9 +41,15 @@ import org.mockito.MockedConstruction;
 import org.mockito.Mockito;
 
 import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
 
+import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.doThrow;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 
@@ -77,6 +91,168 @@ public class StarRocksSinkWriterTest {
         }
     }
 
+    @Test
+    void 
schemaChangeFlushesTheOldManagerBeforeTheDdlAndWritesNewRowsWithTheNewSchema()
+            throws Exception {
+        List<String> events = new ArrayList<>();
+        try (MockedConstruction<StarRocksSinkManager> mockedManager =
+                Mockito.mockConstruction(
+                        StarRocksSinkManager.class,
+                        (manager, ctx) -> {
+                            int index = ctx.getCount() - 1;
+                            events.add("new-manager-" + index);
+                            doAnswer(
+                                            invocation -> {
+                                                events.add("close-manager-" + 
index);
+                                                return null;
+                                            })
+                                    .when(manager)
+                                    .close();
+                        })) {
+            RecordingWriter writer = 
createWriter(mock(SinkWriter.Context.class), events);
+            StarRocksSinkManager before = mockedManager.constructed().get(0);
+            writer.write(row(1));
+
+            writer.applySchemaChange(addColumn("name"));
+            writer.write(rowWithName(2, "n"));
+
+            StarRocksSinkManager after = mockedManager.constructed().get(1);
+            // old rows loaded, table altered, only then a manager for the new 
schema
+            Assertions.assertEquals(
+                    Arrays.asList("new-manager-0", "close-manager-0", "ddl", 
"new-manager-1"),
+                    events);
+            verify(before).write("{\"id\":1}");
+            verify(after).write("{\"id\":2,\"name\":\"n\"}");
+            verify(before, never()).write("{\"id\":2,\"name\":\"n\"}");
+        }
+    }
+
+    @Test
+    void restoreEventFlushesTheOldManagerWithoutRunningDdl() throws Exception {
+        List<String> events = new ArrayList<>();
+        try (MockedConstruction<StarRocksSinkManager> mockedManager =
+                Mockito.mockConstruction(
+                        StarRocksSinkManager.class,
+                        (manager, ctx) -> {
+                            int index = ctx.getCount() - 1;
+                            events.add("new-manager-" + index);
+                            doAnswer(
+                                            invocation -> {
+                                                events.add("close-manager-" + 
index);
+                                                return null;
+                                            })
+                                    .when(manager)
+                                    .close();
+                        })) {
+            RecordingWriter writer = 
createWriter(mock(SinkWriter.Context.class), events);
+
+            writer.applySchemaChange(
+                    new RestoreTableSchemaEvent(
+                            CatalogTable.of(
+                                    TABLE_IDENTIFIER,
+                                    schema("id", "name"),
+                                    Collections.emptyMap(),
+                                    Collections.emptyList(),
+                                    "")));
+
+            Assertions.assertEquals(
+                    Arrays.asList("new-manager-0", "close-manager-0", 
"new-manager-1"), events);
+            Assertions.assertEquals(2, mockedManager.constructed().size());
+        }
+    }
+
+    @Test
+    void failedFlushBeforeSchemaChangeKeepsTheOldManagerAndSkipsTheDdl() 
throws Exception {
+        List<String> events = new ArrayList<>();
+        try (MockedConstruction<StarRocksSinkManager> mockedManager =
+                Mockito.mockConstruction(
+                        StarRocksSinkManager.class,
+                        (manager, ctx) -> {
+                            events.add("new-manager-" + (ctx.getCount() - 1));
+                            // StarRocksSinkManager reports a failed Stream 
Load this way
+                            doThrow(
+                                            new StarRocksConnectorException(
+                                                    StarRocksConnectorErrorCode
+                                                            
.WRITE_RECORDS_FAILED,
+                                                    "stream load failed"))
+                                    .when(manager)
+                                    .close();
+                        })) {
+            RecordingWriter writer = 
createWriter(mock(SinkWriter.Context.class), events);
+            StarRocksSinkManager before = mockedManager.constructed().get(0);
+
+            StarRocksConnectorException thrown =
+                    Assertions.assertThrows(
+                            StarRocksConnectorException.class,
+                            () -> writer.applySchemaChange(addColumn("name")));
+
+            // The failure reaches the engine untouched; no DDL ran and no 
manager was replaced, so
+            // the retained rows are still in the manager that keeps their 
label.
+            Assertions.assertTrue(thrown.getMessage().contains("stream load 
failed"));
+            
Assertions.assertEquals(Collections.singletonList("new-manager-0"), events);
+            Assertions.assertEquals(1, mockedManager.constructed().size());
+            writer.write(row(3));
+            verify(before).write("{\"id\":3}");
+        }
+    }
+
+    private static final TableIdentifier TABLE_IDENTIFIER =
+            TableIdentifier.of("starrocks", TablePath.of("test", 
"timer_flush"));
+
+    private static TableSchema schema(String... names) {
+        TableSchema.Builder builder = TableSchema.builder();
+        for (String name : names) {
+            builder.column(
+                    PhysicalColumn.of(
+                            name,
+                            "id".equals(name) ? BasicType.INT_TYPE : 
BasicType.STRING_TYPE,
+                            (Long) null,
+                            false,
+                            null,
+                            null));
+        }
+        return builder.build();
+    }
+
+    private static AlterTableAddColumnEvent addColumn(String name) {
+        return AlterTableAddColumnEvent.add(
+                TABLE_IDENTIFIER,
+                PhysicalColumn.of(name, BasicType.STRING_TYPE, (Long) null, 
true, null, null));
+    }
+
+    private static SeaTunnelRow row(int id) {
+        return new SeaTunnelRow(new Object[] {id});
+    }
+
+    private static SeaTunnelRow rowWithName(int id, String name) {
+        return new SeaTunnelRow(new Object[] {id, name});
+    }
+
+    /** Records the DDL call instead of opening a JDBC connection. */
+    private static class RecordingWriter extends StarRocksSinkWriter {
+        private final List<String> events;
+
+        RecordingWriter(
+                SinkWriter.Context context,
+                SinkConfig sinkConfig,
+                TableSchema tableSchema,
+                List<String> events) {
+            super(context, sinkConfig, tableSchema, 
TABLE_IDENTIFIER.toTablePath());
+            this.events = events;
+        }
+
+        @Override
+        protected void applySchemaChangeToStarRocks(SchemaChangeEvent event) {
+            events.add("ddl");
+        }
+    }
+
+    private RecordingWriter createWriter(SinkWriter.Context context, 
List<String> events) {
+        SinkConfig sinkConfig = new SinkConfig();
+        sinkConfig.setLoadFormat(SinkConfig.StreamLoadFormat.JSON);
+        return new RecordingWriter(context, sinkConfig, schema("id"), events);
+    }
+
     private StarRocksSinkWriter createWriter(SinkWriter.Context context) {
         SinkConfig sinkConfig = new SinkConfig();
         sinkConfig.setLoadFormat(SinkConfig.StreamLoadFormat.JSON);
diff --git 
a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-starrocks-e2e/src/test/java/org/apache/seatunnel/e2e/connector/starrocks/StarRocksSchemaChangeIT.java
 
b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-starrocks-e2e/src/test/java/org/apache/seatunnel/e2e/connector/starrocks/StarRocksSchemaChangeIT.java
index 7351230942..ca3ff022c6 100644
--- 
a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-starrocks-e2e/src/test/java/org/apache/seatunnel/e2e/connector/starrocks/StarRocksSchemaChangeIT.java
+++ 
b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-starrocks-e2e/src/test/java/org/apache/seatunnel/e2e/connector/starrocks/StarRocksSchemaChangeIT.java
@@ -17,9 +17,20 @@
 
 package org.apache.seatunnel.e2e.connector.starrocks;
 
+import org.apache.seatunnel.api.configuration.ReadonlyConfig;
+import org.apache.seatunnel.api.sink.SinkWriter;
+import org.apache.seatunnel.api.table.catalog.PhysicalColumn;
+import org.apache.seatunnel.api.table.catalog.TableIdentifier;
+import org.apache.seatunnel.api.table.catalog.TablePath;
+import org.apache.seatunnel.api.table.catalog.TableSchema;
+import org.apache.seatunnel.api.table.schema.event.AlterTableAddColumnEvent;
+import org.apache.seatunnel.api.table.type.BasicType;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
 import 
org.apache.seatunnel.connectors.seatunnel.cdc.mysql.testutils.MySqlContainer;
 import 
org.apache.seatunnel.connectors.seatunnel.cdc.mysql.testutils.MySqlVersion;
 import 
org.apache.seatunnel.connectors.seatunnel.cdc.mysql.testutils.UniqueDatabase;
+import org.apache.seatunnel.connectors.seatunnel.starrocks.config.SinkConfig;
+import 
org.apache.seatunnel.connectors.seatunnel.starrocks.sink.StarRocksSinkWriter;
 import org.apache.seatunnel.e2e.common.TestResource;
 import org.apache.seatunnel.e2e.common.TestSuiteBase;
 import org.apache.seatunnel.e2e.common.container.ContainerExtendedFactory;
@@ -33,6 +44,7 @@ import org.apache.seatunnel.e2e.common.util.JobIdGenerator;
 import org.junit.jupiter.api.AfterAll;
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.TestTemplate;
 import org.testcontainers.containers.GenericContainer;
 import org.testcontainers.containers.output.Slf4jLogConsumer;
@@ -52,13 +64,17 @@ import java.time.LocalDateTime;
 import java.time.OffsetDateTime;
 import java.time.format.DateTimeFormatter;
 import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
 import java.util.List;
+import java.util.Map;
 import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.TimeUnit;
 import java.util.stream.Stream;
 
 import static org.awaitility.Awaitility.await;
 import static org.awaitility.Awaitility.given;
+import static org.mockito.Mockito.mock;
 
 @Slf4j
 @DisabledOnContainer(
@@ -154,6 +170,104 @@ public class StarRocksSchemaChangeIT extends 
TestSuiteBase implements TestResour
                 .untilAsserted(this::initializeJdbcConnection);
     }
 
+    @Test
+    public void flushesRowsBufferedBelowBatchThresholdBeforeSchemaChange() 
throws Exception {
+        String table = "schema_change_buffered_rows";
+        String qualifiedTable = DATABASE + "." + table;
+        try (Statement statement = starRocksConnection.createStatement()) {
+            statement.execute(
+                    "CREATE TABLE "
+                            + qualifiedTable
+                            + " (id INT NOT NULL, quantity INT NOT NULL)"
+                            + " DUPLICATE KEY(id) DISTRIBUTED BY HASH(id) 
BUCKETS 1"
+                            + " PROPERTIES (\"replication_num\" = \"1\")");
+        }
+
+        TablePath tablePath = TablePath.of(DATABASE, table);
+        TableSchema schema =
+                TableSchema.builder()
+                        .column(
+                                PhysicalColumn.of(
+                                        "id", BasicType.INT_TYPE, (Long) null, 
false, null, null))
+                        .column(
+                                PhysicalColumn.of(
+                                        "quantity",
+                                        BasicType.INT_TYPE,
+                                        (Long) null,
+                                        false,
+                                        null,
+                                        null))
+                        .build();
+        SinkConfig config =
+                SinkConfig.of(
+                        ReadonlyConfig.fromMap(
+                                Map.of(
+                                        "nodeUrls",
+                                        Collections.singletonList(
+                                                starRocksServer.getHost()
+                                                        + ":"
+                                                        + 
starRocksServer.getMappedPort(
+                                                                BE_HTTP_PORT)),
+                                        "base-url",
+                                        "jdbc:mysql://"
+                                                + starRocksServer.getHost()
+                                                + ":"
+                                                + 
starRocksServer.getMappedPort(QUERY_PORT),
+                                        "database",
+                                        DATABASE,
+                                        "table",
+                                        table,
+                                        "username",
+                                        USERNAME,
+                                        "password",
+                                        PASSWORD,
+                                        "batch_max_rows",
+                                        10,
+                                        "batch_max_bytes",
+                                        1048576L,
+                                        "starrocks.config.format",
+                                        "JSON")));
+        String select = "SELECT id, quantity, note FROM " + qualifiedTable + " 
ORDER BY id";
+        List<List<Object>> beforeChange =
+                Arrays.asList(Arrays.asList(1, 10, null), Arrays.asList(2, 20, 
null));
+
+        // No engine callback runs between these writes and the DDL. The real 
writer must flush
+        // them.
+        StarRocksSinkWriter writer =
+                new StarRocksSinkWriter(mock(SinkWriter.Context.class), 
config, schema, tablePath);
+        try (AutoCloseable closeWriter = writer::close) {
+            writer.write(new SeaTunnelRow(new Object[] {1, 10}));
+            writer.write(new SeaTunnelRow(new Object[] {2, 20}));
+            Assertions.assertTrue(
+                    query("SELECT id FROM " + qualifiedTable, 
starRocksConnection).isEmpty(),
+                    "The old rows must still be buffered when the schema 
changes");
+
+            writer.applySchemaChange(
+                    AlterTableAddColumnEvent.add(
+                            TableIdentifier.of("starrocks", tablePath),
+                            PhysicalColumn.of(
+                                    "note", BasicType.STRING_TYPE, 64L, true, 
null, null)));
+            await().ignoreExceptions()
+                    .atMost(30, TimeUnit.SECONDS)
+                    .untilAsserted(
+                            () ->
+                                    Assertions.assertEquals(
+                                            beforeChange, query(select, 
starRocksConnection)));
+
+            writer.write(new SeaTunnelRow(new Object[] {3, 30, "new schema"}));
+            writer.prepareCommit();
+        }
+
+        List<List<Object>> expected = new ArrayList<>(beforeChange);
+        expected.add(Arrays.asList(3, 30, "new schema"));
+        await().ignoreExceptions()
+                .atMost(30, TimeUnit.SECONDS)
+                .untilAsserted(
+                        () ->
+                                Assertions.assertEquals(
+                                        expected, query(select, 
starRocksConnection)));
+    }
+
     @TestTemplate
     public void testStarRocksSinkWithSchemaEvolutionCase(TestContainer 
container)
             throws InterruptedException, IOException, SQLException {
@@ -418,8 +532,8 @@ public class StarRocksSchemaChangeIT extends TestSuiteBase 
implements TestResour
     }
 
     private List<List<Object>> query(String sql, Connection connection) {
-        try {
-            ResultSet resultSet = 
connection.createStatement().executeQuery(sql);
+        try (Statement statement = connection.createStatement();
+                ResultSet resultSet = statement.executeQuery(sql)) {
             List<List<Object>> result = new ArrayList<>();
             int columnCount = resultSet.getMetaData().getColumnCount();
             while (resultSet.next()) {

Reply via email to