You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by li...@apache.org on 2026/09/01 14:26:29 UTC

(seatunnel) 02/02: [Fix][Zeta] Harden schema restore checkpoint handling

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

davidzollo pushed a commit to branch davidzollo_republish_11780_resolver_restore_fix
in repository https://gitbox.apache.org/repos/asf/seatunnel.git

commit d9bc23443d72f366532eefe5826b0ae9caf03523
Author: davidzollo <da...@gmail.com>
AuthorDate: Tue Sep 1 10:25:21 2026 -0400

    [Fix][Zeta] Harden schema restore checkpoint handling
---
 .../introduction/configuration/schema-evolution.md |  12 ++
 .../introduction/configuration/schema-evolution.md |   6 +
 .../apache/seatunnel/api/sink/SeaTunnelSink.java   |  11 ++
 .../org/apache/seatunnel/api/source/Collector.java |   4 +
 .../source/reader/IncrementalSourceReader.java     | 116 ++++++++++++++---
 .../source/reader/IncrementalSourceReaderTest.java | 143 +++++++++++++++++++++
 .../jdbc/sink/AbstractJdbcSinkWriter.java          |   2 +
 .../connectors/seatunnel/jdbc/sink/JdbcSink.java   |  73 ++++++++---
 .../seatunnel/jdbc/sink/JdbcSinkWriter.java        |  27 +++-
 .../seatunnel/jdbc/sink/JdbcSinkTest.java          |  78 +++++++++++
 .../server/task/SeaTunnelSourceCollector.java      |  18 ++-
 .../server/task/error/DefaultErrorSinkWriter.java  |   2 +-
 .../task/error/DefaultErrorSinkWriterTest.java     |  16 +++
 13 files changed, 468 insertions(+), 40 deletions(-)

diff --git a/docs/en/introduction/configuration/schema-evolution.md b/docs/en/introduction/configuration/schema-evolution.md
index 4cd6612059..9bb0b016ef 100644
--- a/docs/en/introduction/configuration/schema-evolution.md
+++ b/docs/en/introduction/configuration/schema-evolution.md
@@ -41,6 +41,18 @@ Otherwise, If your table name start with `ORA_TEMP_` will also has the same prob
 ## Enable schema evolution
 Schema evolution is disabled by default in CDC source. You need configure `schema-changes.enabled = true` which is only supported in CDC to enable it.
 
+## Checkpoint restore compatibility
+
+For Zeta jobs with CDC schema evolution enabled, a checkpoint records the evolved source schema.
+After restore, Zeta applies that schema to the CDC deserializer and source collector before it
+emits records. JDBC Sink also records its evolved writer schema after it has processed a schema
+change; exactly-once JDBC Sink continues to record XA recovery state on every checkpoint.
+
+Checkpoints from earlier SeaTunnel versions that do not contain the schema record fall back to
+their legacy row-type state or the job's configured schema. A checkpoint written with evolved JDBC
+writer schema is not downgrade-compatible with an earlier SeaTunnel release. Flink and Spark do
+not currently restore this collector schema state.
+
 ## Multi-database and multi-table routing
 
 Schema evolution can work with multi-table jobs as long as each upstream table can be mapped to a
diff --git a/docs/zh/introduction/configuration/schema-evolution.md b/docs/zh/introduction/configuration/schema-evolution.md
index 359d7c4991..be35f48146 100644
--- a/docs/zh/introduction/configuration/schema-evolution.md
+++ b/docs/zh/introduction/configuration/schema-evolution.md
@@ -41,6 +41,12 @@
 ## 启用Schema evolution功能
 在CDC源连接器中模式演进默认是关闭的。你需要在CDC连接器中配置`schema-changes.enabled = true`来启用它。
 
+## Checkpoint 恢复兼容性
+
+对于启用了 CDC 模式演进的 Zeta 作业,checkpoint 会记录演进后的源端 schema。恢复时,Zeta 会在发出记录前,将该 schema 同时应用到 CDC 反序列化器和 source collector。JDBC Sink 仅在处理过模式变更后才会记录演进后的 writer schema;exactly-once JDBC Sink 仍会在每个 checkpoint 记录 XA 恢复状态。
+
+早期 SeaTunnel 版本生成的 checkpoint 不包含该 schema 记录时,会回退到旧的 row-type 状态或作业配置中的 schema。包含 JDBC 演进 writer schema 的 checkpoint 不能回退恢复到更早的 SeaTunnel 版本。Flink 和 Spark 当前不会恢复这份 collector schema 状态。
+
 ## 多库多表路由
 
 只要每张上游表都能稳定映射到一个明确的物理下游表,模式演进就可以和多库多表任务一起工作。SeaTunnel 会在连接器启动前完成 Sink 占位符替换,因此你可以结合 [Sink 参数占位符](./sink-options-placeholders.md) 中的 `${database_name}`、`${schema_name}`、`${table_name}` 做路由。
diff --git a/seatunnel-api/src/main/java/org/apache/seatunnel/api/sink/SeaTunnelSink.java b/seatunnel-api/src/main/java/org/apache/seatunnel/api/sink/SeaTunnelSink.java
index 954bec748c..8527f13554 100644
--- a/seatunnel-api/src/main/java/org/apache/seatunnel/api/sink/SeaTunnelSink.java
+++ b/seatunnel-api/src/main/java/org/apache/seatunnel/api/sink/SeaTunnelSink.java
@@ -96,6 +96,17 @@ public interface SeaTunnelSink<IN, StateT, CommitInfoT, AggregatedCommitInfoT>
         return Optional.empty();
     }
 
+    /**
+     * Whether the sink requires its writer state lifecycle when it is used as a routed error sink.
+     *
+     * <p>By default, a writer-state serializer means that the sink requires state lifecycle. A sink
+     * with an optional recovery hint can override this method when the hint is not needed for error
+     * rows.
+     */
+    default boolean requiresWriterState() {
+        return getWriterStateSerializer().isPresent();
+    }
+
     /**
      * This method will be called to create {@link SinkCommitter}
      *
diff --git a/seatunnel-api/src/main/java/org/apache/seatunnel/api/source/Collector.java b/seatunnel-api/src/main/java/org/apache/seatunnel/api/source/Collector.java
index 8493c5ebb0..48c2c6f55b 100644
--- a/seatunnel-api/src/main/java/org/apache/seatunnel/api/source/Collector.java
+++ b/seatunnel-api/src/main/java/org/apache/seatunnel/api/source/Collector.java
@@ -40,6 +40,10 @@ public interface Collector<T> {
      *
      * <p>This method only refreshes local runtime state. It must not emit schema change events to
      * downstream operators because they restore their own checkpoint state independently.
+     *
+     * <p>Only the Zeta engine collector restores this state today. Flink and Spark retain the
+     * default no-op implementation until their translation-layer collectors support schema
+     * restoration.
      */
     default void restoreSchema(List<CatalogTable> catalogTables) {}
 
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/source/reader/IncrementalSourceReader.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/source/reader/IncrementalSourceReader.java
index 6726ba16bc..c704aecd7a 100644
--- a/seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/source/reader/IncrementalSourceReader.java
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/source/reader/IncrementalSourceReader.java
@@ -20,6 +20,10 @@ package org.apache.seatunnel.connectors.cdc.base.source.reader;
 import org.apache.seatunnel.api.source.Collector;
 import org.apache.seatunnel.api.source.SourceReader;
 import org.apache.seatunnel.api.table.catalog.CatalogTable;
+import org.apache.seatunnel.api.table.catalog.CatalogTableUtil;
+import org.apache.seatunnel.api.table.catalog.TablePath;
+import org.apache.seatunnel.api.table.type.MultipleRowType;
+import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
 import org.apache.seatunnel.connectors.cdc.base.config.SourceConfig;
 import org.apache.seatunnel.connectors.cdc.base.dialect.DataSourceDialect;
 import org.apache.seatunnel.connectors.cdc.base.source.event.CompletedSnapshotPhaseEvent;
@@ -40,15 +44,18 @@ import org.apache.seatunnel.connectors.seatunnel.common.source.reader.SingleThre
 import org.apache.seatunnel.connectors.seatunnel.common.source.reader.SourceReaderOptions;
 import org.apache.seatunnel.connectors.seatunnel.common.source.reader.fetcher.SingleThreadFetcherManager;
 
+import io.debezium.relational.TableId;
 import lombok.extern.slf4j.Slf4j;
 
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.BlockingQueue;
 import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
 import java.util.function.Supplier;
 import java.util.stream.Collectors;
 
@@ -77,7 +84,8 @@ public class IncrementalSourceReader<T, C extends SourceConfig>
 
     private final AtomicBoolean needSendSplitRequest = new AtomicBoolean(false);
 
-    private transient volatile List<CatalogTable> restoredCheckpointTables;
+    private final AtomicReference<List<CatalogTable>> restoredCheckpointTables =
+            new AtomicReference<>();
 
     public IncrementalSourceReader(
             DataSourceDialect<C> dataSourceDialect,
@@ -124,12 +132,11 @@ public class IncrementalSourceReader<T, C extends SourceConfig>
     }
 
     private void restoreCollectorSchema(Collector<T> output) {
-        List<CatalogTable> checkpointTables = restoredCheckpointTables;
-        if (checkpointTables == null) {
+        List<CatalogTable> checkpointTables = restoredCheckpointTables.getAndSet(null);
+        if (checkpointTables == null || checkpointTables.isEmpty()) {
             return;
         }
         output.restoreSchema(checkpointTables);
-        restoredCheckpointTables = null;
     }
 
     @Override
@@ -226,18 +233,10 @@ public class IncrementalSourceReader<T, C extends SourceConfig>
             return new SnapshotSplitState(split.asSnapshotSplit());
         } else {
             IncrementalSplit incrementalSplit = split.asIncrementalSplit();
-            if (incrementalSplit.getCheckpointTables() != null) {
-                log.info(
-                        "The incremental split[{}] has checkpoint tables {} for restore.",
-                        incrementalSplit.splitId(),
-                        incrementalSplit.getCheckpointTables());
-                debeziumDeserializationSchema.restoreCheckpointProducedType(
-                        incrementalSplit.getCheckpointTables());
-                // Only roll the collector back to checkpointed tables when the dialect can also
-                // restore the deserializer's produced type from the same checkpoint snapshot.
-                if (debeziumDeserializationSchema.getSchemaChangeResolver() != null) {
-                    restoredCheckpointTables = incrementalSplit.getCheckpointTables();
-                }
+            List<CatalogTable> checkpointTables =
+                    restoreCheckpointState(incrementalSplit, debeziumDeserializationSchema);
+            if (!checkpointTables.isEmpty()) {
+                restoredCheckpointTables.set(checkpointTables);
             }
             IncrementalSplitState splitState = new IncrementalSplitState(incrementalSplit);
             if (splitState.autoEnterPureIncrementPhaseIfAllowed()) {
@@ -255,6 +254,91 @@ public class IncrementalSourceReader<T, C extends SourceConfig>
         }
     }
 
+    /**
+     * Restores schema-evolution state from the current or legacy incremental split checkpoint.
+     *
+     * <p>Both the Debezium deserializer and the engine collector must restore the same table list.
+     * Resolver-less CDC dialects deliberately keep their current table definition, so this method
+     * returns no tables for them.
+     */
+    static <T> List<CatalogTable> restoreCheckpointState(
+            IncrementalSplit incrementalSplit,
+            DebeziumDeserializationSchema<T> debeziumDeserializationSchema) {
+        if (debeziumDeserializationSchema.getSchemaChangeResolver() == null) {
+            return Collections.emptyList();
+        }
+
+        List<CatalogTable> checkpointTables = incrementalSplit.getCheckpointTables();
+        if (checkpointTables != null && !checkpointTables.isEmpty()) {
+            log.info(
+                    "The incremental split[{}] has checkpoint tables {} for restore.",
+                    incrementalSplit.splitId(),
+                    checkpointTables);
+        } else if (incrementalSplit.getCheckpointDataType() != null) {
+            checkpointTables = restoreLegacyCheckpointTables(incrementalSplit);
+            if (checkpointTables.isEmpty()) {
+                log.warn(
+                        "Skip restoring the legacy checkpoint data type for incremental split[{}] because the table identity cannot be recovered from split state.",
+                        incrementalSplit.splitId());
+            } else {
+                log.info(
+                        "The incremental split[{}] restores {} legacy checkpoint table(s): {}.",
+                        incrementalSplit.splitId(),
+                        checkpointTables.size(),
+                        toCheckpointTablePaths(checkpointTables));
+            }
+        }
+
+        if (checkpointTables == null || checkpointTables.isEmpty()) {
+            return Collections.emptyList();
+        }
+        debeziumDeserializationSchema.restoreCheckpointProducedType(checkpointTables);
+        return checkpointTables;
+    }
+
+    private static List<CatalogTable> restoreLegacyCheckpointTables(
+            IncrementalSplit incrementalSplit) {
+        if (incrementalSplit.getCheckpointDataType() instanceof MultipleRowType) {
+            MultipleRowType checkpointTables =
+                    (MultipleRowType) incrementalSplit.getCheckpointDataType();
+            return Arrays.stream(checkpointTables.getTableIds())
+                    .map(
+                            tableId ->
+                                    toLegacyCheckpointTable(
+                                            tableId, checkpointTables.getRowType(tableId)))
+                    .collect(Collectors.toList());
+        }
+
+        List<TableId> tableIds = incrementalSplit.getTableIds();
+        if (tableIds == null || tableIds.size() != 1) {
+            return Collections.emptyList();
+        }
+
+        return Collections.singletonList(
+                CatalogTableUtil.getCatalogTable(
+                        "schema",
+                        tableIds.get(0).catalog(),
+                        tableIds.get(0).schema(),
+                        tableIds.get(0).table(),
+                        (SeaTunnelRowType) incrementalSplit.getCheckpointDataType()));
+    }
+
+    private static CatalogTable toLegacyCheckpointTable(String tableId, SeaTunnelRowType rowType) {
+        TablePath tablePath = TablePath.of(tableId);
+        return CatalogTableUtil.getCatalogTable(
+                "schema",
+                tablePath.getDatabaseName(),
+                tablePath.getSchemaName(),
+                tablePath.getTableName(),
+                rowType);
+    }
+
+    private static List<String> toCheckpointTablePaths(List<CatalogTable> checkpointTables) {
+        return checkpointTables.stream()
+                .map(table -> table.getTablePath().getFullName())
+                .collect(Collectors.toList());
+    }
+
     @Override
     public List<SourceSplitBase> snapshotState(long checkpointId) {
         List<SourceSplitBase> stateSplits = super.snapshotState(checkpointId);
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/test/java/org/apache/seatunnel/connectors/cdc/base/source/reader/IncrementalSourceReaderTest.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/test/java/org/apache/seatunnel/connectors/cdc/base/source/reader/IncrementalSourceReaderTest.java
new file mode 100644
index 0000000000..fb46c9f5a3
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/test/java/org/apache/seatunnel/connectors/cdc/base/source/reader/IncrementalSourceReaderTest.java
@@ -0,0 +1,143 @@
+/*
+ * 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.seatunnel.connectors.cdc.base.source.reader;
+
+import org.apache.seatunnel.api.table.catalog.CatalogTable;
+import org.apache.seatunnel.api.table.type.BasicType;
+import org.apache.seatunnel.api.table.type.SeaTunnelDataType;
+import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
+import org.apache.seatunnel.connectors.cdc.base.schema.SchemaChangeResolver;
+import org.apache.seatunnel.connectors.cdc.base.source.offset.Offset;
+import org.apache.seatunnel.connectors.cdc.base.source.split.IncrementalSplit;
+import org.apache.seatunnel.connectors.cdc.debezium.DebeziumDeserializationSchema;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mockito;
+
+import io.debezium.relational.TableId;
+
+import java.util.Collections;
+import java.util.List;
+
+class IncrementalSourceReaderTest {
+
+    @Test
+    void shouldRestoreCheckpointTablesOnlyForSchemaAwareDeserializer() {
+        @SuppressWarnings("unchecked")
+        DebeziumDeserializationSchema<Object> schema =
+                Mockito.mock(DebeziumDeserializationSchema.class);
+        Mockito.when(schema.getSchemaChangeResolver())
+                .thenReturn(Mockito.mock(SchemaChangeResolver.class));
+        List<CatalogTable> checkpointTables =
+                Collections.singletonList(Mockito.mock(CatalogTable.class));
+        IncrementalSplit split =
+                new IncrementalSplit(
+                        "incremental-split-0",
+                        Collections.emptyList(),
+                        Mockito.mock(Offset.class),
+                        Mockito.mock(Offset.class),
+                        Collections.emptyList(),
+                        checkpointTables,
+                        Collections.emptyMap());
+
+        List<CatalogTable> restored = IncrementalSourceReader.restoreCheckpointState(split, schema);
+
+        Assertions.assertEquals(checkpointTables, restored);
+        Mockito.verify(schema).restoreCheckpointProducedType(checkpointTables);
+    }
+
+    @Test
+    void shouldIgnoreEmptyCheckpointTables() {
+        @SuppressWarnings("unchecked")
+        DebeziumDeserializationSchema<Object> schema =
+                Mockito.mock(DebeziumDeserializationSchema.class);
+        Mockito.when(schema.getSchemaChangeResolver())
+                .thenReturn(Mockito.mock(SchemaChangeResolver.class));
+        IncrementalSplit split =
+                new IncrementalSplit(
+                        "incremental-split-0",
+                        Collections.emptyList(),
+                        Mockito.mock(Offset.class),
+                        Mockito.mock(Offset.class),
+                        Collections.emptyList(),
+                        Collections.emptyList(),
+                        Collections.emptyMap());
+
+        Assertions.assertTrue(
+                IncrementalSourceReader.restoreCheckpointState(split, schema).isEmpty());
+        Mockito.verify(schema, Mockito.never()).restoreCheckpointProducedType(Mockito.anyList());
+    }
+
+    @Test
+    void shouldRestoreLegacyCheckpointDataType() {
+        @SuppressWarnings("unchecked")
+        DebeziumDeserializationSchema<Object> schema =
+                Mockito.mock(DebeziumDeserializationSchema.class);
+        Mockito.when(schema.getSchemaChangeResolver())
+                .thenReturn(Mockito.mock(SchemaChangeResolver.class));
+        SeaTunnelRowType checkpointRowType =
+                new SeaTunnelRowType(
+                        new String[] {"id", "name"},
+                        new SeaTunnelDataType[] {BasicType.INT_TYPE, BasicType.STRING_TYPE});
+        IncrementalSplit split =
+                new IncrementalSplit(
+                        "incremental-split-0",
+                        Collections.singletonList(new TableId("catalog", "database", "customers")),
+                        Mockito.mock(Offset.class),
+                        Mockito.mock(Offset.class),
+                        Collections.emptyList(),
+                        checkpointRowType);
+
+        IncrementalSourceReader.restoreCheckpointState(split, schema);
+
+        @SuppressWarnings("unchecked")
+        ArgumentCaptor<List<CatalogTable>> captor = ArgumentCaptor.forClass(List.class);
+        Mockito.verify(schema).restoreCheckpointProducedType(captor.capture());
+        List<CatalogTable> restoredTables = captor.getValue();
+        Assertions.assertEquals(1, restoredTables.size());
+        Assertions.assertEquals(
+                "catalog.database.customers", restoredTables.get(0).getTablePath().getFullName());
+        Assertions.assertArrayEquals(
+                checkpointRowType.getFieldNames(),
+                restoredTables.get(0).getSeaTunnelRowType().getFieldNames());
+    }
+
+    @Test
+    void shouldSkipRestoreForResolverlessDeserializer() {
+        @SuppressWarnings("unchecked")
+        DebeziumDeserializationSchema<Object> schema =
+                Mockito.mock(DebeziumDeserializationSchema.class);
+        List<CatalogTable> checkpointTables =
+                Collections.singletonList(Mockito.mock(CatalogTable.class));
+        IncrementalSplit split =
+                new IncrementalSplit(
+                        "incremental-split-0",
+                        Collections.emptyList(),
+                        Mockito.mock(Offset.class),
+                        Mockito.mock(Offset.class),
+                        Collections.emptyList(),
+                        checkpointTables,
+                        Collections.emptyMap());
+
+        Assertions.assertTrue(
+                IncrementalSourceReader.restoreCheckpointState(split, schema).isEmpty());
+        Mockito.verify(schema, Mockito.never()).restoreCheckpointProducedType(Mockito.anyList());
+    }
+}
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/AbstractJdbcSinkWriter.java b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/AbstractJdbcSinkWriter.java
index 48193d6d35..76872de161 100644
--- a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/AbstractJdbcSinkWriter.java
+++ b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/AbstractJdbcSinkWriter.java
@@ -58,11 +58,13 @@ public abstract class AbstractJdbcSinkWriter<ResourceT>
     protected JdbcOutputFormat<SeaTunnelRow, JdbcBatchStatementExecutor<SeaTunnelRow>> outputFormat;
     protected TableSchemaChangeEventDispatcher tableSchemaChanger =
             new TableSchemaChangeEventDispatcher();
+    protected boolean schemaEvolutionApplied;
 
     @Override
     public void applySchemaChange(SchemaChangeEvent event) throws IOException {
         this.tableSchema = tableSchemaChanger.reset(tableSchema).apply(event);
         reOpenOutputFormat(event);
+        this.schemaEvolutionApplied = true;
     }
 
     /**
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSink.java b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSink.java
index 9ff92b85cc..0dce4d6a61 100644
--- a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSink.java
+++ b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSink.java
@@ -34,6 +34,7 @@ import org.apache.seatunnel.api.sink.SupportSaveMode;
 import org.apache.seatunnel.api.sink.SupportSchemaEvolutionSink;
 import org.apache.seatunnel.api.table.catalog.Catalog;
 import org.apache.seatunnel.api.table.catalog.CatalogTable;
+import org.apache.seatunnel.api.table.catalog.PrimaryKey;
 import org.apache.seatunnel.api.table.catalog.TablePath;
 import org.apache.seatunnel.api.table.catalog.TableSchema;
 import org.apache.seatunnel.api.table.catalog.exception.TableNotExistException;
@@ -60,6 +61,7 @@ import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
 import java.util.Optional;
+import java.util.stream.Collectors;
 
 import static org.apache.seatunnel.api.common.SeaTunnelAPIErrorCode.HANDLE_SAVE_MODE_FAILED;
 
@@ -134,6 +136,10 @@ public class JdbcSink
         TablePath sinkTablePath = catalogTable.getTablePath();
         AbstractJdbcSinkWriter sinkWriter;
         if (jdbcSinkConfig.isExactlyOnce()) {
+            List<JdbcSinkState> xidStates =
+                    states.stream()
+                            .filter(state -> state.getXid() != null)
+                            .collect(Collectors.toList());
             sinkWriter =
                     new JdbcExactlyOnceSinkWriter(
                             sinkTablePath,
@@ -143,17 +149,12 @@ public class JdbcSink
                             jdbcSinkConfig,
                             writerTableSchema,
                             getDatabaseTableSchema().orElse(null),
-                            states);
+                            xidStates);
 
         } else {
-            Integer primaryKeyIndex = null;
-            if (writerTableSchema.getPrimaryKey() != null) {
-                String keyName = writerTableSchema.getPrimaryKey().getColumnNames().get(0);
-                int index = writerTableSchema.toPhysicalRowDataType().indexOf(keyName);
-                if (index > -1) {
-                    primaryKeyIndex = index;
-                }
-            }
+            Integer primaryKeyIndex = resolvePrimaryKeyIndex(writerTableSchema);
+            boolean hasRestoredSchema =
+                    states.stream().anyMatch(state -> state.getTableSchema() != null);
             sinkWriter =
                     new JdbcSinkWriter(
                             sinkTablePath,
@@ -162,7 +163,8 @@ public class JdbcSink
                             jdbcSinkConfig,
                             writerTableSchema,
                             getDatabaseTableSchema().orElse(null),
-                            primaryKeyIndex);
+                            primaryKeyIndex,
+                            hasRestoredSchema);
         }
         return sinkWriter;
     }
@@ -170,20 +172,59 @@ public class JdbcSink
     @Override
     public SinkWriter<SeaTunnelRow, XidInfo, JdbcSinkState> restoreWriter(
             SinkWriter.Context context, List<JdbcSinkState> states) throws IOException {
-        TableSchema restoredTableSchema =
-                states.stream()
-                        .map(JdbcSinkState::getTableSchema)
-                        .filter(schema -> schema != null)
-                        .findFirst()
-                        .orElse(tableSchema);
+        TableSchema restoredTableSchema = resolveRestoredTableSchema(tableSchema, states);
         return createWriter(context, restoredTableSchema, states);
     }
 
+    static TableSchema resolveRestoredTableSchema(
+            TableSchema initialTableSchema, List<JdbcSinkState> states) {
+        TableSchema restoredTableSchema = null;
+        for (JdbcSinkState state : states) {
+            TableSchema stateTableSchema = state.getTableSchema();
+            if (stateTableSchema == null) {
+                continue;
+            }
+            if (restoredTableSchema == null) {
+                restoredTableSchema = stateTableSchema;
+            } else if (!restoredTableSchema.equals(stateTableSchema)) {
+                throw new IllegalStateException(
+                        "JDBC sink cannot restore divergent table schemas from the same checkpoint");
+            }
+        }
+        return restoredTableSchema == null ? initialTableSchema : restoredTableSchema;
+    }
+
+    private Integer resolvePrimaryKeyIndex(TableSchema writerTableSchema) {
+        PrimaryKey primaryKey = writerTableSchema.getPrimaryKey();
+        if (primaryKey == null) {
+            primaryKey = tableSchema.getPrimaryKey();
+            if (primaryKey != null) {
+                log.warn(
+                        "Restored JDBC table schema for {} has no primary-key metadata; using the configured primary key {}",
+                        catalogTable.getTablePath(),
+                        primaryKey.getColumnNames());
+            }
+        }
+        if (primaryKey == null) {
+            return null;
+        }
+        int index =
+                writerTableSchema
+                        .toPhysicalRowDataType()
+                        .indexOf(primaryKey.getColumnNames().get(0));
+        return index > -1 ? index : null;
+    }
+
     @Override
     public Optional<Serializer<JdbcSinkState>> getWriterStateSerializer() {
         return Optional.of(new DefaultSerializer<>());
     }
 
+    @Override
+    public boolean requiresWriterState() {
+        return jdbcSinkConfig.isExactlyOnce();
+    }
+
     private Optional<TableSchema> getDatabaseTableSchema() {
         Optional<Catalog> catalogOptional = getCatalog();
         FieldIdeEnum fieldIdeEnumEnum = config.get(JdbcSinkOptions.FIELD_IDE);
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkWriter.java b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkWriter.java
index 248ed729a9..0a8770285a 100644
--- a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkWriter.java
+++ b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkWriter.java
@@ -85,7 +85,8 @@ public class JdbcSinkWriter extends AbstractJdbcSinkWriter<ConnectionPoolManager
                 jdbcSinkConfig,
                 tableSchema,
                 databaseTableSchema,
-                primaryKeyIndex);
+                primaryKeyIndex,
+                false);
     }
 
     public JdbcSinkWriter(
@@ -96,12 +97,33 @@ public class JdbcSinkWriter extends AbstractJdbcSinkWriter<ConnectionPoolManager
             TableSchema tableSchema,
             TableSchema databaseTableSchema,
             Integer primaryKeyIndex) {
+        this(
+                sinkTablePath,
+                context,
+                dialect,
+                jdbcSinkConfig,
+                tableSchema,
+                databaseTableSchema,
+                primaryKeyIndex,
+                false);
+    }
+
+    JdbcSinkWriter(
+            TablePath sinkTablePath,
+            SinkWriter.Context context,
+            JdbcDialect dialect,
+            JdbcSinkConfig jdbcSinkConfig,
+            TableSchema tableSchema,
+            TableSchema databaseTableSchema,
+            Integer primaryKeyIndex,
+            boolean schemaEvolutionApplied) {
         this.sinkTablePath = sinkTablePath;
         this.dialect = dialect;
         this.tableSchema = tableSchema;
         this.databaseTableSchema = databaseTableSchema;
         this.jdbcSinkConfig = jdbcSinkConfig;
         this.primaryKeyIndex = primaryKeyIndex;
+        this.schemaEvolutionApplied = schemaEvolutionApplied;
         this.rowErrorCollector =
                 context == null ? Optional.empty() : context.getRowErrorCollector();
         this.batchSize = jdbcSinkConfig.getJdbcConnectionConfig().getBatchSize();
@@ -211,6 +233,9 @@ public class JdbcSinkWriter extends AbstractJdbcSinkWriter<ConnectionPoolManager
 
     @Override
     public List<JdbcSinkState> snapshotState(long checkpointId) {
+        if (!schemaEvolutionApplied) {
+            return Collections.emptyList();
+        }
         return Collections.singletonList(new JdbcSinkState(null, tableSchema));
     }
 
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkTest.java b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkTest.java
new file mode 100644
index 0000000000..bf45263e93
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkTest.java
@@ -0,0 +1,78 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.jdbc.sink;
+
+import org.apache.seatunnel.api.table.catalog.PhysicalColumn;
+import org.apache.seatunnel.api.table.catalog.TableSchema;
+import org.apache.seatunnel.api.table.type.BasicType;
+import org.apache.seatunnel.connectors.seatunnel.jdbc.state.JdbcSinkState;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+class JdbcSinkTest {
+
+    @Test
+    void shouldUseTheOnlyRestoredSchemaOrTheInitialSchema() {
+        TableSchema initialSchema = tableSchema("id");
+        TableSchema restoredSchema = tableSchema("id", "email");
+
+        Assertions.assertEquals(
+                initialSchema,
+                JdbcSink.resolveRestoredTableSchema(
+                        initialSchema, Collections.singletonList(new JdbcSinkState(null))));
+        Assertions.assertEquals(
+                restoredSchema,
+                JdbcSink.resolveRestoredTableSchema(
+                        initialSchema,
+                        Arrays.asList(
+                                new JdbcSinkState(null, restoredSchema),
+                                new JdbcSinkState(null, restoredSchema))));
+    }
+
+    @Test
+    void shouldRejectDivergentRestoredSchemas() {
+        TableSchema initialSchema = tableSchema("id");
+
+        IllegalStateException exception =
+                Assertions.assertThrows(
+                        IllegalStateException.class,
+                        () ->
+                                JdbcSink.resolveRestoredTableSchema(
+                                        initialSchema,
+                                        Arrays.asList(
+                                                new JdbcSinkState(null, tableSchema("id", "email")),
+                                                new JdbcSinkState(
+                                                        null, tableSchema("id", "phone")))));
+
+        Assertions.assertTrue(exception.getMessage().contains("divergent table schemas"));
+    }
+
+    private static TableSchema tableSchema(String... columnNames) {
+        TableSchema.Builder builder = TableSchema.builder();
+        for (String columnName : columnNames) {
+            builder.column(
+                    PhysicalColumn.of(
+                            columnName, BasicType.STRING_TYPE, (Long) null, true, null, null));
+        }
+        return builder.build();
+    }
+}
diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/SeaTunnelSourceCollector.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/SeaTunnelSourceCollector.java
index 8b9b5b8bd4..37cf956141 100644
--- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/SeaTunnelSourceCollector.java
+++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/SeaTunnelSourceCollector.java
@@ -56,6 +56,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.function.LongSupplier;
+import java.util.stream.Collectors;
 
 import static org.apache.seatunnel.api.common.metrics.MetricNames.FLUSH_SIGNAL_QPS;
 import static org.apache.seatunnel.api.common.metrics.MetricNames.FLUSH_SIGNAL_TOTAL;
@@ -362,15 +363,20 @@ public class SeaTunnelSourceCollector<T> implements Collector<T> {
                         "Single-table source collector cannot restore multiple table schemas: "
                                 + catalogTables.stream()
                                         .map(CatalogTable::getTablePath)
-                                        .collect(java.util.stream.Collectors.toList()));
+                                        .collect(Collectors.toList()));
             }
             this.rowType = catalogTables.get(0).getTableSchema().toPhysicalRowDataType();
         } else if (rowType instanceof MultipleRowType) {
             catalogTables.forEach(
-                    table ->
-                            rowTypeMap.put(
-                                    table.getTablePath().toString(),
-                                    table.getTableSchema().toPhysicalRowDataType()));
+                    table -> {
+                        String tableId = table.getTablePath().toString();
+                        if (!rowTypeMap.containsKey(tableId)) {
+                            throw new SeaTunnelEngineException(
+                                    "Multi-table source collector cannot restore an unknown table schema: "
+                                            + tableId);
+                        }
+                        rowTypeMap.put(tableId, table.getTableSchema().toPhysicalRowDataType());
+                    });
         } else {
             throw new SeaTunnelEngineException(
                     "Unsupported row type: " + rowType.getClass().getName());
@@ -379,7 +385,7 @@ public class SeaTunnelSourceCollector<T> implements Collector<T> {
                 "Restored source collector schema from checkpoint for tables: {}",
                 catalogTables.stream()
                         .map(CatalogTable::getTablePath)
-                        .collect(java.util.stream.Collectors.toList()));
+                        .collect(Collectors.toList()));
     }
 
     @Override
diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/error/DefaultErrorSinkWriter.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/error/DefaultErrorSinkWriter.java
index 0e2859a070..020ae7f7af 100644
--- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/error/DefaultErrorSinkWriter.java
+++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/error/DefaultErrorSinkWriter.java
@@ -452,7 +452,7 @@ public class DefaultErrorSinkWriter<T> implements ErrorSinkRowWriter<T> {
     static void validateSupportedErrorSinkLifecycle(
             String pluginName, SeaTunnelSink<SeaTunnelRow, ?, ?, ?> sink) throws Exception {
         List<String> unsupportedFeatures = new ArrayList<>();
-        if (sink.getWriterStateSerializer().isPresent()) {
+        if (sink.requiresWriterState()) {
             unsupportedFeatures.add("writer state serializer");
         }
         if (sink.getCommitInfoSerializer().isPresent()) {
diff --git a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/task/error/DefaultErrorSinkWriterTest.java b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/task/error/DefaultErrorSinkWriterTest.java
index 123dd00afd..c53f5d29e0 100644
--- a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/task/error/DefaultErrorSinkWriterTest.java
+++ b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/task/error/DefaultErrorSinkWriterTest.java
@@ -69,6 +69,22 @@ public class DefaultErrorSinkWriterTest {
         assertTrue(ex.getMessage().contains("writer state serializer"));
     }
 
+    @Test
+    public void testValidateSupportedErrorSinkLifecycleAllowsOptionalWriterState() {
+        SeaTunnelSink<SeaTunnelRow, String, String, String> sink =
+                new TestSink(true, false, false) {
+                    @Override
+                    public boolean requiresWriterState() {
+                        return false;
+                    }
+                };
+
+        assertDoesNotThrow(
+                () ->
+                        DefaultErrorSinkWriter.validateSupportedErrorSinkLifecycle(
+                                "optional-state", sink));
+    }
+
     @Test
     public void testValidateSupportedErrorSinkLifecycleRejectsCommittingSink() {
         RuntimeException ex =