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

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


The following commit(s) were added to refs/heads/dev by this push:
     new 5cf050be3f [Fix][Connector-V2] Handle JDBC transaction deadlock 
retries safely (#12769)
5cf050be3f is described below

commit 5cf050be3ffc77c0065d67d4eb8af83f24a2a620
Author: yzeng1618 <[email protected]>
AuthorDate: Sat Nov 28 13:59:28 2026 +0800

    [Fix][Connector-V2] Handle JDBC transaction deadlock retries safely (#12769)
    
    Co-authored-by: zengyi <[email protected]>
---
 docs/en/connectors/sink/Jdbc.md                    |   7 +-
 docs/zh/connectors/sink/Jdbc.md                    |   7 +-
 .../seatunnel/jdbc/config/JdbcSinkConfig.java      |   2 +
 .../seatunnel/jdbc/config/JdbcSinkOptions.java     |   8 +
 .../seatunnel/jdbc/internal/JdbcOutputFormat.java  | 106 ++++-
 .../jdbc/internal/JdbcOutputFormatBuilder.java     |   8 +-
 .../BufferReducedBatchStatementExecutor.java       | 116 ++++-
 .../executor/BufferedBatchStatementExecutor.java   |  15 +
 .../executor/JdbcBatchStatementExecutor.java       |  17 +
 .../seatunnel/jdbc/sink/JdbcSinkFactory.java       |   1 +
 .../JdbcOutputFormatReconnectSafetyTest.java       | 174 ++++++++
 .../internal/JdbcOutputFormatReconnectTest.java    |  74 ++-
 .../BufferReducedBatchStatementExecutorTest.java   | 108 +++++
 .../connectors/seatunnel/jdbc/JdbcPostgresIT.java  | 494 +++++++++++++++++++++
 14 files changed, 1123 insertions(+), 14 deletions(-)

diff --git a/docs/en/connectors/sink/Jdbc.md b/docs/en/connectors/sink/Jdbc.md
index c608440428..7f268d17bc 100644
--- a/docs/en/connectors/sink/Jdbc.md
+++ b/docs/en/connectors/sink/Jdbc.md
@@ -252,6 +252,7 @@ Exactly-once delivery uses XA transactions and therefore 
requires XA support fro
 | enable_upsert                             | Boolean | No       | true        
                 |
 | is_primary_key_updated                    | Boolean | No       | true        
                 |
 | support_upsert_by_insert_only             | Boolean | No       | false       
                 |
+| upsert_batch_key_ordered                  | Boolean | No       | false       
                 |
 | table_options                             | Map     | No       | -           
                 |
 | use_copy_statement                        | Boolean | No       | false       
                 |
 | oracle_insert_mode                        | Enum    | No       | 
CONVENTIONAL                 |
@@ -375,7 +376,7 @@ Socket read timeout in milliseconds after the JDBC 
connection is established. Th
 
 ### max_retries [int]
 
-The number of retries after a failed JDBC `executeBatch`. Exactly-once mode 
requires this option to be `0`; retrying a failed XA batch can violate 
transaction guarantees.
+The number of retries after a failed JDBC `executeBatch`. In auto-commit mode, 
transaction conflicts such as PostgreSQL `40P01` keep the existing generic 
retry behavior. On manual-commit connections, conflicts are retried only when 
the sink can roll back and replay the complete flush transaction; otherwise 
they are propagated. When a checkpoint transaction spans multiple flushes, 
checkpoint recovery replays the complete transaction safely. Exactly-once mode 
requires this option to be `0` [...]
 
 A non-XA manual-commit failure at `Connection.commit()` is treated as a system 
error, even with SQLState class `22` or `23`. The failed writer cannot retry 
the commit as if it restored the transaction. With checkpointing enabled, any 
flushed work sharing that transaction is marked unsafe, and other writers on 
the same queue also refuse to commit until recovery.
 
@@ -640,6 +641,10 @@ Whether primary key fields are included when generating 
update statements. Keep
 
 Whether to support upsert behavior through insert-only statements for 
compatible dialects. This is an advanced compatibility option and is disabled 
by default.
 
+### upsert_batch_key_ordered [boolean]
+
+Sorts standard primary-key upsert and delete entries in each flush by a 
deterministic primary-key order before executing them. This reduces lock-order 
deadlocks between concurrent JDBC writers. A batch that mixes upserts and 
deletes may execute more child batches when the change flag alternates. The 
option defaults to `false` for compatibility and applies to the generated 
primary-key upsert path; custom `query` statements keep their configured 
ordering. Sorting only orders records within [...]
+
 ### use_copy_statement [boolean]
 
 Use `COPY ${table} FROM STDIN` statement to import data. Only drivers with 
`getCopyAPI()` method connections are supported.  e.g.: Postgresql driver 
`org.postgresql.Driver`.
diff --git a/docs/zh/connectors/sink/Jdbc.md b/docs/zh/connectors/sink/Jdbc.md
index 36ea11b59c..45e928fb3e 100644
--- a/docs/zh/connectors/sink/Jdbc.md
+++ b/docs/zh/connectors/sink/Jdbc.md
@@ -252,6 +252,7 @@ Exactly-once 依赖 XA 事务,因此数据库和 JDBC 驱动都必须支持 XA
 | enable_upsert                             | Boolean | 否    | true            
             |
 | is_primary_key_updated                    | Boolean | 否    | true            
             |
 | support_upsert_by_insert_only             | Boolean | 否    | false           
             |
+| upsert_batch_key_ordered                  | Boolean | 否    | false           
             |
 | table_options                             | Map     | 否    | -               
             |
 | use_copy_statement                        | Boolean | 否    | false           
             |
 | oracle_insert_mode                        | Enum    | 否    | CONVENTIONAL    
             |
@@ -376,7 +377,7 @@ JDBC 连接建立后的 socket 读取超时时间,单位毫秒。默认值为
 
 ### max_retries [int]
 
-JDBC `executeBatch` 失败后的重试次数。Exactly-once 模式要求设置为 `0`,重试失败的 XA batch 可能破坏事务保证。
+JDBC `executeBatch` 失败后的重试次数。在自动提交模式下,PostgreSQL `40P01` 
等事务冲突保持原有的通用重试行为。在手动提交连接上,只有 sink 能够回滚并完整重放本次 flush 事务时才会重试,否则会直接抛出。当一个 
checkpoint 事务跨越多个 flush 时,由 checkpoint 恢复机制安全重放完整事务。Exactly-once 模式要求设置为 
`0`,重试失败的 XA batch 可能破坏事务保证。
 
 非 XA 手动提交连接在 `Connection.commit()` 阶段失败时,一律按系统错误处理,即使 SQLState 属于 `22` 或 `23` 
类也不能作为行级错误丢弃。失败的 writer 不能通过再次提交来假定事务已恢复。开启 checkpoint 时,该共享事务中已 flush 
的数据会被标记为不安全,同队列的其他 writer 也会拒绝提交,直到作业恢复。
 
@@ -636,6 +637,10 @@ sink {
 
 是否通过仅 insert 的语句支持 upsert 行为。该参数属于高级兼容选项,默认关闭。
 
+### upsert_batch_key_ordered [boolean]
+
+在每次 flush 前,按确定性的主键顺序执行标准主键 upsert 和 delete 条目,降低并发 JDBC writer 
之间因加锁顺序不同导致死锁的概率。当 batch 同时包含 upsert 和 delete 且变更类型交替时,可能执行更多子 batch。为保持兼容,默认值为 
`false`,仅作用于自动生成的主键 upsert 路径;自定义 `query` 仍按其配置顺序执行。排序只覆盖一次 flush,不能替代事务冲突处理。
+
 ### use_copy_statement [boolean]
 
 使用 `COPY ${table} FROM STDIN` 语句导入数据。仅支持具有 `getCopyAPI()` 
方法连接的驱动程序。例如:Postgresql
diff --git 
a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/config/JdbcSinkConfig.java
 
b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/config/JdbcSinkConfig.java
index 51b35b5d6f..236650765a 100644
--- 
a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/config/JdbcSinkConfig.java
+++ 
b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/config/JdbcSinkConfig.java
@@ -39,6 +39,7 @@ public class JdbcSinkConfig implements Serializable {
     private boolean enableUpsert;
     @Builder.Default private boolean isPrimaryKeyUpdated = true;
     private boolean supportUpsertByInsertOnly;
+    @Builder.Default private boolean upsertBatchKeyOrdered = false;
     private boolean useCopyStatement;
     @Builder.Default private boolean createIndex = true;
     @Builder.Default private OracleInsertMode oracleInsertMode = 
OracleInsertMode.CONVENTIONAL;
@@ -54,6 +55,7 @@ public class JdbcSinkConfig implements Serializable {
         
builder.isPrimaryKeyUpdated(config.get(JdbcSinkOptions.IS_PRIMARY_KEY_UPDATED));
         builder.supportUpsertByInsertOnly(
                 config.get(JdbcSinkOptions.SUPPORT_UPSERT_BY_INSERT_ONLY));
+        
builder.upsertBatchKeyOrdered(config.get(JdbcSinkOptions.UPSERT_BATCH_KEY_ORDERED));
         builder.simpleSql(config.get(JdbcSinkOptions.QUERY));
         
builder.useCopyStatement(config.get(JdbcSinkOptions.USE_COPY_STATEMENT));
         builder.createIndex(config.get(JdbcSinkOptions.CREATE_INDEX));
diff --git 
a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/config/JdbcSinkOptions.java
 
b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/config/JdbcSinkOptions.java
index 22c9c4dfc4..6f752a3fc1 100644
--- 
a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/config/JdbcSinkOptions.java
+++ 
b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/config/JdbcSinkOptions.java
@@ -121,6 +121,14 @@ public class JdbcSinkOptions extends JdbcCommonOptions {
                     .defaultValue(false)
                     .withDescription("support upsert by insert only");
 
+    public static final Option<Boolean> UPSERT_BATCH_KEY_ORDERED =
+            Options.key("upsert_batch_key_ordered")
+                    .booleanType()
+                    .defaultValue(false)
+                    .withDescription(
+                            "sort standard upsert batches by primary key 
before flushing to reduce"
+                                    + " lock-order deadlocks; disabled by 
default and does not change custom query ordering");
+
     public static final Option<Boolean> USE_COPY_STATEMENT =
             Options.key("use_copy_statement")
                     .booleanType()
diff --git 
a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormat.java
 
b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormat.java
index e846e9b9a1..d78fb3991e 100644
--- 
a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormat.java
+++ 
b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormat.java
@@ -41,6 +41,7 @@ import java.util.IdentityHashMap;
 import java.util.List;
 import java.util.Locale;
 import java.util.Set;
+import java.util.concurrent.ThreadLocalRandom;
 import java.util.function.Supplier;
 
 import static 
org.apache.seatunnel.shade.com.google.common.base.Preconditions.checkNotNull;
@@ -252,6 +253,42 @@ public class JdbcOutputFormat<I, E extends 
JdbcBatchStatementExecutor<I>> implem
                             CommonErrorCodeDeprecated.FLUSH_DATA_FAILED, e);
                 }
 
+                boolean retryableTransactionConflict =
+                        isRetryableTransactionConflict(sqlExceptions);
+                boolean transactionConflict = false;
+                if (retryableTransactionConflict) {
+                    // An auto-commit connection keeps every statement in its 
own transaction, so
+                    // the failed attempt replayed nothing and the legacy 
generic retry below is
+                    // safe. Fail fast only when the flush does not own the 
transaction boundary
+                    // (checkpoint / XA) or the executor cannot retain its 
records for replay.
+                    boolean canRetry;
+                    try {
+                        canRetry = canRetryTransactionConflict();
+                        if (!canRetry && !isAutoCommitConnection()) {
+                            throw new JdbcConnectorException(
+                                    
CommonErrorCodeDeprecated.FLUSH_DATA_FAILED,
+                                    "JDBC transaction conflict cannot be 
retried inside the current"
+                                            + " transaction boundary.",
+                                    e);
+                        }
+                    } catch (SQLException transactionStateException) {
+                        throw new JdbcConnectorException(
+                                CommonErrorCodeDeprecated.FLUSH_DATA_FAILED,
+                                "Unable to inspect JDBC transaction state 
after a transaction conflict.",
+                                transactionStateException);
+                    }
+                    if (canRetry) {
+                        transactionConflict = true;
+                        try {
+                            rollbackAfterTransactionConflict();
+                        } catch (SQLException rollbackException) {
+                            throw new JdbcConnectorException(
+                                    
CommonErrorCodeDeprecated.FLUSH_DATA_FAILED,
+                                    "Unable to rollback JDBC transaction after 
a transaction conflict.",
+                                    rollbackException);
+                        }
+                    }
+                }
                 SQLException nonRetryableDataException =
                         findNonRetryableDataException(sqlExceptions);
                 if (nonRetryableDataException != null) {
@@ -301,7 +338,9 @@ public class JdbcOutputFormat<I, E extends 
JdbcBatchStatementExecutor<I>> implem
                             e);
                 }
                 try {
-                    if (shouldRefreshExecutor(sqlExceptions)) {
+                    // A transaction-conflict retry must keep the executor: 
its buffer still
+                    // holds the records the next attempt replays after the 
rollback.
+                    if (!transactionConflict && 
shouldRefreshExecutor(sqlExceptions)) {
                         updateExecutor(true);
                     }
                 } catch (Exception exception) {
@@ -314,7 +353,13 @@ public class JdbcOutputFormat<I, E extends 
JdbcBatchStatementExecutor<I>> implem
                             exception);
                 }
                 try {
-                    sleepBeforeFlushRetry((long) sleepMs * i);
+                    long retrySleepMs = (long) sleepMs * i;
+                    if (retryableTransactionConflict) {
+                        retrySleepMs =
+                                (long) sleepMs * (i + 1)
+                                        + 
ThreadLocalRandom.current().nextLong(sleepMs);
+                    }
+                    sleepBeforeFlushRetry(retrySleepMs);
                 } catch (InterruptedException ex) {
                     Thread.currentThread().interrupt();
                     throw new JdbcConnectorException(
@@ -605,6 +650,63 @@ public class JdbcOutputFormat<I, E extends 
JdbcBatchStatementExecutor<I>> implem
         return isOracleDataException(sqlException);
     }
 
+    /**
+     * Returns whether the current transaction is owned by this flush and can 
be replayed safely.
+     * Checkpoint and XA transactions span multiple flushes, so their 
conflicts must be propagated
+     * to the owner that can replay the complete transaction.
+     */
+    private boolean canRetryTransactionConflict() throws SQLException {
+        if (!commitOnFlush) {
+            return false;
+        }
+        if (jdbcStatementExecutor == null
+                || !jdbcStatementExecutor.supportsTransactionConflictRetry()) {
+            return false;
+        }
+        Connection connection = connectionProvider.getConnection();
+        return connection != null && !connection.getAutoCommit();
+    }
+
+    /** Returns whether the current connection keeps each JDBC statement in 
its own transaction. */
+    private boolean isAutoCommitConnection() throws SQLException {
+        Connection connection = connectionProvider.getConnection();
+        return connection != null && connection.getAutoCommit();
+    }
+
+    /**
+     * Rolls back the failed flush transaction and clears only the driver's 
partial batch. The
+     * executor retains its logical records so a following flush attempt can 
replay them.
+     */
+    private void rollbackAfterTransactionConflict() throws SQLException {
+        Connection connection = connectionProvider.getConnection();
+        if (connection != null && !connection.getAutoCommit()) {
+            connection.rollback();
+        }
+        // Clear the driver's partially submitted batch while retaining the 
logical records.
+        jdbcStatementExecutor.resetForTransactionConflictRetry();
+    }
+
+    /**
+     * Identifies database transaction conflicts using PostgreSQL SQLSTATEs 
40P01/40001 and Oracle
+     * vendor code 60 with the ORA-00060 message.
+     */
+    private boolean isRetryableTransactionConflict(List<SQLException> 
sqlExceptions) {
+        for (SQLException sqlException : sqlExceptions) {
+            String sqlState = sqlException.getSQLState();
+            int vendorCode = sqlException.getErrorCode();
+            if ("40P01".equals(sqlState) || "40001".equals(sqlState)) {
+                return true;
+            }
+            String message = sqlException.getMessage();
+            if (vendorCode == 60
+                    && message != null
+                    && message.toUpperCase(Locale.ROOT).contains("ORA-00060")) 
{
+                return true;
+            }
+        }
+        return false;
+    }
+
     private boolean isOracleDataException(SQLException sqlException) {
         String message = sqlException.getMessage();
         if (message == null) {
diff --git 
a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatBuilder.java
 
b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatBuilder.java
index 8203dbc900..6199100147 100644
--- 
a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatBuilder.java
+++ 
b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatBuilder.java
@@ -112,7 +112,8 @@ public class JdbcOutputFormatBuilder {
                                     primaryKeys.toArray(new String[0]),
                                     jdbcSinkConfig.isEnableUpsert(),
                                     jdbcSinkConfig.isPrimaryKeyUpdated(),
-                                    
jdbcSinkConfig.isSupportUpsertByInsertOnly());
+                                    
jdbcSinkConfig.isSupportUpsertByInsertOnly(),
+                                    jdbcSinkConfig.isUpsertBatchKeyOrdered());
         }
 
         return new JdbcOutputFormat(
@@ -155,7 +156,8 @@ public class JdbcOutputFormatBuilder {
             String[] pkNames,
             boolean enableUpsert,
             boolean isPrimaryKeyUpdated,
-            boolean supportUpsertByInsertOnly) {
+            boolean supportUpsertByInsertOnly,
+            boolean keyOrdered) {
         int[] pkFields =
                 Arrays.stream(pkNames)
                         .mapToInt(tableSchema.toPhysicalRowDataType()::indexOf)
@@ -188,7 +190,7 @@ public class JdbcOutputFormatBuilder {
                         isPrimaryKeyUpdated,
                         supportUpsertByInsertOnly);
         return new BufferReducedBatchStatementExecutor(
-                upsertExecutor, deleteExecutor, keyExtractor, 
Function.identity());
+                upsertExecutor, deleteExecutor, keyExtractor, 
Function.identity(), keyOrdered);
     }
 
     private static JdbcBatchStatementExecutor<SeaTunnelRow> 
createUpsertExecutor(
diff --git 
a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferReducedBatchStatementExecutor.java
 
b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferReducedBatchStatementExecutor.java
index 3f0bff4735..7fafde9e4b 100644
--- 
a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferReducedBatchStatementExecutor.java
+++ 
b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferReducedBatchStatementExecutor.java
@@ -25,22 +25,24 @@ import 
org.apache.seatunnel.common.exception.CommonErrorCodeDeprecated;
 import 
org.apache.seatunnel.connectors.seatunnel.jdbc.exception.JdbcConnectorException;
 
 import lombok.NonNull;
-import lombok.RequiredArgsConstructor;
 
 import java.sql.Connection;
 import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Collection;
 import java.util.HashMap;
 import java.util.LinkedHashMap;
+import java.util.List;
 import java.util.Map;
 import java.util.function.Function;
 
-@RequiredArgsConstructor
 public class BufferReducedBatchStatementExecutor
         implements JdbcBatchStatementExecutor<SeaTunnelRow> {
     @NonNull private final JdbcBatchStatementExecutor<SeaTunnelRow> 
upsertExecutor;
     @NonNull private final JdbcBatchStatementExecutor<SeaTunnelRow> 
deleteExecutor;
     @NonNull private final Function<SeaTunnelRow, SeaTunnelRow> keyExtractor;
     @NonNull private final Function<SeaTunnelRow, SeaTunnelRow> valueTransform;
+    private final boolean keyOrdered;
 
     /**
      * Buffered rows by key, so that only the last change of a key is written. 
The value holds the
@@ -57,6 +59,27 @@ public class BufferReducedBatchStatementExecutor
 
     private boolean flushFailed;
 
+    public BufferReducedBatchStatementExecutor(
+            @NonNull JdbcBatchStatementExecutor<SeaTunnelRow> upsertExecutor,
+            @NonNull JdbcBatchStatementExecutor<SeaTunnelRow> deleteExecutor,
+            @NonNull Function<SeaTunnelRow, SeaTunnelRow> keyExtractor,
+            @NonNull Function<SeaTunnelRow, SeaTunnelRow> valueTransform) {
+        this(upsertExecutor, deleteExecutor, keyExtractor, valueTransform, 
false);
+    }
+
+    public BufferReducedBatchStatementExecutor(
+            @NonNull JdbcBatchStatementExecutor<SeaTunnelRow> upsertExecutor,
+            @NonNull JdbcBatchStatementExecutor<SeaTunnelRow> deleteExecutor,
+            @NonNull Function<SeaTunnelRow, SeaTunnelRow> keyExtractor,
+            @NonNull Function<SeaTunnelRow, SeaTunnelRow> valueTransform,
+            boolean keyOrdered) {
+        this.upsertExecutor = upsertExecutor;
+        this.deleteExecutor = deleteExecutor;
+        this.keyExtractor = keyExtractor;
+        this.valueTransform = valueTransform;
+        this.keyOrdered = keyOrdered;
+    }
+
     @Override
     public void prepareStatements(Connection connection) throws SQLException {
         upsertExecutor.prepareStatements(connection);
@@ -95,10 +118,21 @@ public class BufferReducedBatchStatementExecutor
 
     @Override
     public void executeBatch() throws SQLException {
+        flushFailed = false;
         try {
             Boolean preChangeFlag = null;
-            for (Map.Entry<Object, Triple<Boolean, SeaTunnelRow, 
SeaTunnelRow>> entry :
-                    buffer.entrySet()) {
+            Collection<Map.Entry<Object, Triple<Boolean, SeaTunnelRow, 
SeaTunnelRow>>> entries =
+                    buffer.entrySet();
+            if (keyOrdered && buffer.size() > 1) {
+                List<Map.Entry<Object, Triple<Boolean, SeaTunnelRow, 
SeaTunnelRow>>> sorted =
+                        new ArrayList<>(buffer.entrySet());
+                sorted.sort(
+                        (left, right) ->
+                                compareKeys(
+                                        left.getValue().getMiddle(), 
right.getValue().getMiddle()));
+                entries = sorted;
+            }
+            for (Map.Entry<Object, Triple<Boolean, SeaTunnelRow, 
SeaTunnelRow>> entry : entries) {
                 Triple<Boolean, SeaTunnelRow, SeaTunnelRow> bufferedRow = 
entry.getValue();
                 Boolean currentChangeFlag = bufferedRow.getLeft();
                 if (currentChangeFlag) {
@@ -136,11 +170,74 @@ public class BufferReducedBatchStatementExecutor
         }
     }
 
+    /**
+     * Compares primary-key rows using a deterministic lexicographic order. 
The type name is part of
+     * the comparison when two fields have different Java types, which keeps 
the comparator
+     * transitive even when malformed input mixes numeric and textual values.
+     */
+    static int compareKeys(SeaTunnelRow left, SeaTunnelRow right) {
+        int arity = Math.min(left.getArity(), right.getArity());
+        for (int i = 0; i < arity; i++) {
+            Object a = left.getField(i);
+            Object b = right.getField(i);
+            int comparison = compareFields(a, b);
+            if (comparison != 0) {
+                return comparison;
+            }
+        }
+        return Integer.compare(left.getArity(), right.getArity());
+    }
+
+    private static int compareFields(Object left, Object right) {
+        if (left == right) {
+            return 0;
+        }
+        if (left == null) {
+            return 1;
+        }
+        if (right == null) {
+            return -1;
+        }
+        if (left instanceof byte[] && right instanceof byte[]) {
+            return compareBytes((byte[]) left, (byte[]) right);
+        }
+
+        int typeComparison = 
left.getClass().getName().compareTo(right.getClass().getName());
+        if (typeComparison != 0) {
+            return typeComparison;
+        }
+        if (left instanceof Comparable) {
+            @SuppressWarnings("unchecked")
+            Comparable<Object> comparable = (Comparable<Object>) left;
+            int valueComparison = comparable.compareTo(right);
+            if (valueComparison != 0) {
+                return valueComparison;
+            }
+        }
+        return 0;
+    }
+
+    private static int compareBytes(byte[] left, byte[] right) {
+        int length = Math.min(left.length, right.length);
+        for (int i = 0; i < length; i++) {
+            int comparison = Integer.compare(left[i] & 0xFF, right[i] & 0xFF);
+            if (comparison != 0) {
+                return comparison;
+            }
+        }
+        return Integer.compare(left.length, right.length);
+    }
+
     @Override
     public void closeStatements() throws SQLException {
         try {
             if (!buffer.isEmpty() && !flushFailed) {
                 executeBatch();
+            } else if (flushFailed) {
+                // A child executor may still contain a partially submitted 
JDBC batch. Never let
+                // its close method execute that batch after the transaction 
has failed.
+                upsertExecutor.clearBatch();
+                deleteExecutor.clearBatch();
             }
         } finally {
             upsertExecutor.closeStatements();
@@ -156,6 +253,17 @@ public class BufferReducedBatchStatementExecutor
         deleteExecutor.clearBatch();
     }
 
+    @Override
+    public boolean supportsTransactionConflictRetry() {
+        return true;
+    }
+
+    @Override
+    public void resetForTransactionConflictRetry() throws SQLException {
+        upsertExecutor.clearBatch();
+        deleteExecutor.clearBatch();
+    }
+
     private boolean changeFlag(RowKind rowKind) {
         switch (rowKind) {
             case INSERT:
diff --git 
a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferedBatchStatementExecutor.java
 
b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferedBatchStatementExecutor.java
index e00822df10..75181d4c08 100644
--- 
a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferedBatchStatementExecutor.java
+++ 
b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferedBatchStatementExecutor.java
@@ -53,6 +53,7 @@ public class BufferedBatchStatementExecutor implements 
JdbcBatchStatementExecuto
     @Override
     public void executeBatch() throws SQLException {
         if (!buffer.isEmpty()) {
+            flushFailed = false;
             try {
                 for (SeaTunnelRow row : buffer) {
                     statementExecutor.addToBatch(row);
@@ -73,11 +74,25 @@ public class BufferedBatchStatementExecutor implements 
JdbcBatchStatementExecuto
         statementExecutor.clearBatch();
     }
 
+    @Override
+    public boolean supportsTransactionConflictRetry() {
+        return true;
+    }
+
+    @Override
+    public void resetForTransactionConflictRetry() throws SQLException {
+        statementExecutor.clearBatch();
+    }
+
     @Override
     public void closeStatements() throws SQLException {
         try {
             if (!buffer.isEmpty() && !flushFailed) {
                 executeBatch();
+            } else if (flushFailed) {
+                // A child executor may still contain a partially submitted 
JDBC batch. Never let
+                // its close method execute that batch after the transaction 
has failed.
+                statementExecutor.clearBatch();
             }
         } finally {
             statementExecutor.closeStatements();
diff --git 
a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/JdbcBatchStatementExecutor.java
 
b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/JdbcBatchStatementExecutor.java
index 2647f42442..d966ab776a 100644
--- 
a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/JdbcBatchStatementExecutor.java
+++ 
b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/JdbcBatchStatementExecutor.java
@@ -39,6 +39,23 @@ public interface JdbcBatchStatementExecutor<T> {
         // no-op by default
     }
 
+    /**
+     * Returns whether this executor can retry the current transaction after a 
database conflict.
+     * Implementations must retain their logical input buffer while discarding 
only the JDBC
+     * driver's partially submitted batch.
+     */
+    default boolean supportsTransactionConflictRetry() {
+        return false;
+    }
+
+    /**
+     * Discards a partially submitted JDBC batch while retaining the logical 
records for replay.
+     * Implementations must keep the failed state until the next execute 
attempt starts.
+     */
+    default void resetForTransactionConflictRetry() throws SQLException {
+        throw new SQLException("Transaction conflict retry is not supported by 
this executor");
+    }
+
     /** Close JDBC related statements. */
     void closeStatements() throws SQLException;
 }
diff --git 
a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkFactory.java
 
b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkFactory.java
index 075f114995..3004743737 100644
--- 
a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkFactory.java
+++ 
b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkFactory.java
@@ -238,6 +238,7 @@ public class JdbcSinkFactory implements TableSinkFactory, 
SupportSinkDryRunValid
                         JdbcSinkOptions.PRIMARY_KEYS,
                         JdbcSinkOptions.IS_PRIMARY_KEY_UPDATED,
                         JdbcSinkOptions.SUPPORT_UPSERT_BY_INSERT_ONLY,
+                        JdbcSinkOptions.UPSERT_BATCH_KEY_ORDERED,
                         JdbcSinkOptions.USE_COPY_STATEMENT,
                         JdbcSinkOptions.COMPATIBLE_MODE,
                         JdbcSinkOptions.ENABLE_UPSERT,
diff --git 
a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatReconnectSafetyTest.java
 
b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatReconnectSafetyTest.java
index c1727286dc..408e952acb 100644
--- 
a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatReconnectSafetyTest.java
+++ 
b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatReconnectSafetyTest.java
@@ -21,6 +21,8 @@ import org.apache.seatunnel.api.table.type.SeaTunnelRow;
 import 
org.apache.seatunnel.connectors.seatunnel.jdbc.config.JdbcConnectionConfig;
 import 
org.apache.seatunnel.connectors.seatunnel.jdbc.exception.JdbcConnectorException;
 import 
org.apache.seatunnel.connectors.seatunnel.jdbc.internal.connection.JdbcConnectionProvider;
+import 
org.apache.seatunnel.connectors.seatunnel.jdbc.internal.executor.BufferReducedBatchStatementExecutor;
+import 
org.apache.seatunnel.connectors.seatunnel.jdbc.internal.executor.BufferedBatchStatementExecutor;
 import 
org.apache.seatunnel.connectors.seatunnel.jdbc.internal.executor.JdbcBatchStatementExecutor;
 
 import org.junit.jupiter.api.Assertions;
@@ -29,6 +31,7 @@ import org.mockito.Mockito;
 
 import java.sql.Connection;
 import java.sql.SQLException;
+import java.util.function.Function;
 
 class JdbcOutputFormatReconnectSafetyTest {
 
@@ -57,6 +60,129 @@ class JdbcOutputFormatReconnectSafetyTest {
         Mockito.verify(provider, Mockito.never()).reestablishConnection();
     }
 
+    @Test
+    void testDeadlockRetriesAfterRollbackAndBatchReset() throws Exception {
+        JdbcConnectionProvider provider = 
Mockito.mock(JdbcConnectionProvider.class);
+        Connection connection = Mockito.mock(Connection.class);
+        
Mockito.when(provider.getOrEstablishConnection()).thenReturn(connection);
+        Mockito.when(provider.getConnection()).thenReturn(connection);
+        Mockito.when(connection.getAutoCommit()).thenReturn(false);
+
+        TestDeadlockThenSuccessExecutor executor = new 
TestDeadlockThenSuccessExecutor();
+        NoSleepJdbcOutputFormat<SeaTunnelRow, TestDeadlockThenSuccessExecutor> 
outputFormat =
+                new NoSleepJdbcOutputFormat<>(
+                        provider, buildConnectionConfig(), () -> executor, 
true);
+        outputFormat.open();
+        outputFormat.writeRecord(new SeaTunnelRow(new Object[] {"AA"}));
+
+        Assertions.assertDoesNotThrow(outputFormat::flush);
+        outputFormat.close();
+        Mockito.verify(connection, Mockito.times(1)).rollback();
+        Assertions.assertEquals(1, executor.prepareStatementsCalls);
+        Assertions.assertEquals(2, executor.executeBatchCalls);
+        Assertions.assertEquals(1, executor.closeStatementsCalls);
+    }
+
+    @Test
+    void testAutoCommitDeadlockKeepsGenericRetryBehavior() throws Exception {
+        JdbcConnectionProvider provider = 
Mockito.mock(JdbcConnectionProvider.class);
+        Connection connection = Mockito.mock(Connection.class);
+        
Mockito.when(provider.getOrEstablishConnection()).thenReturn(connection);
+        Mockito.when(provider.getConnection()).thenReturn(connection);
+        Mockito.when(provider.isConnectionValid()).thenReturn(true);
+        Mockito.when(connection.getAutoCommit()).thenReturn(true);
+
+        TestDeadlockThenSuccessExecutor executor = new 
TestDeadlockThenSuccessExecutor();
+        NoSleepJdbcOutputFormat<SeaTunnelRow, TestDeadlockThenSuccessExecutor> 
outputFormat =
+                new NoSleepJdbcOutputFormat<>(
+                        provider, buildConnectionConfig(), () -> executor, 
true);
+        outputFormat.open();
+        outputFormat.writeRecord(new SeaTunnelRow(new Object[] {"AA"}));
+
+        Assertions.assertDoesNotThrow(outputFormat::flush);
+        Mockito.verify(connection, Mockito.never()).rollback();
+        Assertions.assertEquals(2, executor.executeBatchCalls);
+    }
+
+    @Test
+    void 
testDeadlockDoesNotReplayOnlyCurrentFlushInsideCheckpointTransaction() throws 
Exception {
+        JdbcConnectionProvider provider = 
Mockito.mock(JdbcConnectionProvider.class);
+        Connection connection = Mockito.mock(Connection.class);
+        
Mockito.when(provider.getOrEstablishConnection()).thenReturn(connection);
+        Mockito.when(provider.getConnection()).thenReturn(connection);
+        Mockito.when(connection.getAutoCommit()).thenReturn(false);
+
+        TestDeadlockThenSuccessExecutor executor = new 
TestDeadlockThenSuccessExecutor();
+        NoSleepJdbcOutputFormat<SeaTunnelRow, TestDeadlockThenSuccessExecutor> 
outputFormat =
+                new NoSleepJdbcOutputFormat<>(provider, 
buildConnectionConfig(), () -> executor);
+        outputFormat.open();
+        outputFormat.writeRecord(new SeaTunnelRow(new Object[] {"AA"}));
+
+        Assertions.assertThrows(JdbcConnectorException.class, 
outputFormat::flush);
+        Assertions.assertEquals(1, executor.executeBatchCalls);
+        Mockito.verify(connection, Mockito.never()).rollback();
+    }
+
+    @Test
+    void testExhaustedDeadlockRetryDoesNotReplayBufferedBatchOnClose() throws 
Exception {
+        JdbcBatchStatementExecutor<SeaTunnelRow> child = 
deadlockThenSuccessExecutor();
+        assertExhaustedDeadlockRetryDoesNotReplayOnClose(
+                new BufferedBatchStatementExecutor(child, 
Function.identity()), child);
+    }
+
+    @Test
+    void testExhaustedDeadlockRetryDoesNotReplayReducedBatchOnClose() throws 
Exception {
+        JdbcBatchStatementExecutor<SeaTunnelRow> upsert = 
deadlockThenSuccessExecutor();
+        JdbcBatchStatementExecutor<SeaTunnelRow> delete =
+                Mockito.mock(JdbcBatchStatementExecutor.class);
+        assertExhaustedDeadlockRetryDoesNotReplayOnClose(
+                new BufferReducedBatchStatementExecutor(
+                        upsert, delete, Function.identity(), 
Function.identity()),
+                upsert);
+    }
+
+    private static JdbcBatchStatementExecutor<SeaTunnelRow> 
deadlockThenSuccessExecutor()
+            throws SQLException {
+        JdbcBatchStatementExecutor<SeaTunnelRow> executor =
+                Mockito.mock(JdbcBatchStatementExecutor.class);
+        Mockito.doThrow(new SQLException("deadlock detected", "40P01"))
+                .doNothing()
+                .when(executor)
+                .executeBatch();
+        return executor;
+    }
+
+    private static void assertExhaustedDeadlockRetryDoesNotReplayOnClose(
+            JdbcBatchStatementExecutor<SeaTunnelRow> executor,
+            JdbcBatchStatementExecutor<SeaTunnelRow> child)
+            throws Exception {
+        JdbcConnectionProvider provider = 
Mockito.mock(JdbcConnectionProvider.class);
+        Connection connection = Mockito.mock(Connection.class);
+        
Mockito.when(provider.getOrEstablishConnection()).thenReturn(connection);
+        Mockito.when(provider.getConnection()).thenReturn(connection);
+        Mockito.when(connection.getAutoCommit()).thenReturn(false);
+
+        JdbcConnectionConfig config =
+                JdbcConnectionConfig.builder()
+                        .url("jdbc:test")
+                        .batchSize(100)
+                        .batchIntervalMs(0)
+                        .maxRetries(0)
+                        .build();
+        NoSleepJdbcOutputFormat<SeaTunnelRow, 
JdbcBatchStatementExecutor<SeaTunnelRow>>
+                outputFormat =
+                        new NoSleepJdbcOutputFormat<>(provider, config, () -> 
executor, true);
+        outputFormat.open();
+        outputFormat.writeRecord(new SeaTunnelRow(new Object[] {"AA"}));
+
+        Assertions.assertThrows(JdbcConnectorException.class, 
outputFormat::flush);
+        Assertions.assertThrows(JdbcConnectorException.class, 
outputFormat::close);
+
+        Mockito.verify(connection).rollback();
+        Mockito.verify(child, Mockito.times(1)).executeBatch();
+        Mockito.verify(child, Mockito.times(2)).clearBatch();
+    }
+
     @Test
     void testFlushRetryShouldFailFastWhenOracleValueTooLarge() throws 
Exception {
         JdbcConnectionProvider provider = 
Mockito.mock(JdbcConnectionProvider.class);
@@ -150,6 +276,18 @@ class JdbcOutputFormatReconnectSafetyTest {
             super(connectionProvider, jdbcConnectionConfig, 
statementExecutorFactory);
         }
 
+        private NoSleepJdbcOutputFormat(
+                JdbcConnectionProvider connectionProvider,
+                JdbcConnectionConfig jdbcConnectionConfig,
+                StatementExecutorFactory<E> statementExecutorFactory,
+                boolean commitOnFlush) {
+            super(
+                    connectionProvider,
+                    jdbcConnectionConfig,
+                    statementExecutorFactory,
+                    commitOnFlush);
+        }
+
         @Override
         protected void sleepBeforeFlushRetry(long sleepMs) throws 
InterruptedException {}
     }
@@ -184,4 +322,40 @@ class JdbcOutputFormatReconnectSafetyTest {
             closeStatementsCalls++;
         }
     }
+
+    private static class TestDeadlockThenSuccessExecutor
+            implements JdbcBatchStatementExecutor<SeaTunnelRow> {
+        private int prepareStatementsCalls;
+        private int executeBatchCalls;
+        private int closeStatementsCalls;
+
+        @Override
+        public void prepareStatements(Connection connection) {
+            prepareStatementsCalls++;
+        }
+
+        @Override
+        public void addToBatch(SeaTunnelRow record) {}
+
+        @Override
+        public void executeBatch() throws SQLException {
+            executeBatchCalls++;
+            if (executeBatchCalls == 1) {
+                throw new SQLException("deadlock detected", "40P01");
+            }
+        }
+
+        @Override
+        public boolean supportsTransactionConflictRetry() {
+            return true;
+        }
+
+        @Override
+        public void resetForTransactionConflictRetry() {}
+
+        @Override
+        public void closeStatements() {
+            closeStatementsCalls++;
+        }
+    }
 }
diff --git 
a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatReconnectTest.java
 
b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatReconnectTest.java
index 196890cbfd..461fb6232f 100644
--- 
a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatReconnectTest.java
+++ 
b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatReconnectTest.java
@@ -372,20 +372,51 @@ public class JdbcOutputFormatReconnectTest {
     }
 
     @Test
-    public void testFlushShouldRetryRolledBackBatchWhenNothingIsPending() 
throws Exception {
+    public void testCheckpointOwnedConflictFailsFastEvenWhenNothingIsPending() 
throws Exception {
         JdbcConnectionProvider provider = manualCommitProvider();
         Mockito.when(provider.isConnectionValid()).thenReturn(true);
+        Connection connection = provider.getConnection();
         TrackingJdbcBatchExecutor executor =
                 new TrackingJdbcBatchExecutor(new SQLException("deadlock 
detected", "40001"), 1);
         JdbcOutputFormat<SeaTunnelRow, TrackingJdbcBatchExecutor> outputFormat 
=
                 new JdbcOutputFormat<>(provider, buildConnectionConfig(), () 
-> executor);
         outputFormat.open();
 
-        // Nothing was flushed into the transaction yet, so the deadlock 
discarded only this batch
-        // and re-sending it is safe.
+        // Nothing was flushed into the transaction yet, but this flush does 
not own its commit
+        // boundary (checkpoint-owned) and the executor cannot replay its 
records, so the local
+        // retry is rejected: re-running executeBatch() would continue inside 
an already aborted
+        // transaction. The conflict fails fast for checkpoint recovery 
instead.
+        outputFormat.writeRecord(new SeaTunnelRow(new Object[] {"AA"}));
+        Assertions.assertThrows(JdbcConnectorException.class, 
outputFormat::flush);
+
+        Assertions.assertEquals(1, executor.executeBatchCalls);
+        Mockito.verify(connection, Mockito.never()).rollback();
+        // The failed batch was never recorded as flushed, so no shared 
uncommitted work is lost.
+        Assertions.assertDoesNotThrow(
+                () -> 
outputFormat.checkUncommittedBatchesOn(provider.getConnection()));
+    }
+
+    @Test
+    public void testFlushOwnedConflictReplaysBatchWithReplayCapableExecutor() 
throws Exception {
+        JdbcConnectionProvider provider = manualCommitProvider();
+        Mockito.when(provider.isConnectionValid()).thenReturn(true);
+        Connection connection = provider.getConnection();
+        TrackingJdbcBatchExecutor executor =
+                new TrackingJdbcBatchExecutor(
+                        new SQLException("deadlock detected", "40001"), 1, 
true);
+        NoSleepJdbcOutputFormat<SeaTunnelRow, TrackingJdbcBatchExecutor> 
outputFormat =
+                new NoSleepJdbcOutputFormat<>(
+                        provider, buildConnectionConfig(), () -> executor, 
true);
+        outputFormat.open();
+
+        // This flush owns its commit boundary and the executor retains its 
logical records while
+        // clearing only the driver batch, so the conflict is rolled back and 
the whole flush is
+        // replayed on the same executor.
         outputFormat.writeRecord(new SeaTunnelRow(new Object[] {"AA"}));
         outputFormat.flush();
 
+        Mockito.verify(connection, Mockito.times(1)).rollback();
+        Assertions.assertEquals(1, executor.resetCalls);
         Assertions.assertEquals(2, executor.executeBatchCalls);
         Assertions.assertDoesNotThrow(
                 () -> 
outputFormat.checkUncommittedBatchesOn(provider.getConnection()));
@@ -542,18 +573,26 @@ public class JdbcOutputFormatReconnectTest {
             implements JdbcBatchStatementExecutor<SeaTunnelRow> {
         private final SQLException firstFailure;
         private final int failOnCall;
+        private final boolean replayCapable;
         private boolean failedOnce;
         private int prepareStatementsCalls;
         private int executeBatchCalls;
         private int closeStatementsCalls;
+        private int resetCalls;
 
         private TrackingJdbcBatchExecutor(SQLException firstFailure) {
             this(firstFailure, 1);
         }
 
         private TrackingJdbcBatchExecutor(SQLException firstFailure, int 
failOnCall) {
+            this(firstFailure, failOnCall, false);
+        }
+
+        private TrackingJdbcBatchExecutor(
+                SQLException firstFailure, int failOnCall, boolean 
replayCapable) {
             this.firstFailure = firstFailure;
             this.failOnCall = failOnCall;
+            this.replayCapable = replayCapable;
         }
 
         @Override
@@ -573,9 +612,38 @@ public class JdbcOutputFormatReconnectTest {
             }
         }
 
+        @Override
+        public boolean supportsTransactionConflictRetry() {
+            return replayCapable;
+        }
+
+        @Override
+        public void resetForTransactionConflictRetry() {
+            resetCalls++;
+        }
+
         @Override
         public void closeStatements() {
             closeStatementsCalls++;
         }
     }
+
+    /** A format without retry backoff sleep, so conflict-retry tests stay 
fast. */
+    private static class NoSleepJdbcOutputFormat<I, E extends 
JdbcBatchStatementExecutor<I>>
+            extends JdbcOutputFormat<I, E> {
+        private NoSleepJdbcOutputFormat(
+                JdbcConnectionProvider connectionProvider,
+                JdbcConnectionConfig jdbcConnectionConfig,
+                StatementExecutorFactory<E> statementExecutorFactory,
+                boolean commitOnFlush) {
+            super(
+                    connectionProvider,
+                    jdbcConnectionConfig,
+                    statementExecutorFactory,
+                    commitOnFlush);
+        }
+
+        @Override
+        protected void sleepBeforeFlushRetry(long sleepMs) throws 
InterruptedException {}
+    }
 }
diff --git 
a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferReducedBatchStatementExecutorTest.java
 
b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferReducedBatchStatementExecutorTest.java
index 0a23505dee..8ccfd014ba 100644
--- 
a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferReducedBatchStatementExecutorTest.java
+++ 
b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferReducedBatchStatementExecutorTest.java
@@ -164,6 +164,60 @@ public class BufferReducedBatchStatementExecutorTest 
extends BufferExecutorTest
         Assertions.assertEquals(1, deletes.get(0).getArity());
     }
 
+    @Test
+    void testCompareKeysIsTransitiveAcrossDifferentTypes() {
+        SeaTunnelRow integerTwo = new SeaTunnelRow(new Object[] {2});
+        SeaTunnelRow integerTen = new SeaTunnelRow(new Object[] {10});
+        SeaTunnelRow stringEleven = new SeaTunnelRow(new Object[] {"11"});
+
+        int twoToTen = 
BufferReducedBatchStatementExecutor.compareKeys(integerTwo, integerTen);
+        int tenToString = 
BufferReducedBatchStatementExecutor.compareKeys(integerTen, stringEleven);
+        int twoToString = 
BufferReducedBatchStatementExecutor.compareKeys(integerTwo, stringEleven);
+
+        Assertions.assertTrue(twoToTen < 0);
+        Assertions.assertTrue(tenToString < 0);
+        Assertions.assertTrue(twoToString < 0);
+    }
+
+    @Test
+    void testExecuteBatchReplaysKeysInDeterministicOrder() throws SQLException 
{
+        List<String> recorder = new ArrayList<>();
+        BufferReducedBatchStatementExecutor executor =
+                new BufferReducedBatchStatementExecutor(
+                        new TaggedRecordingExecutor(recorder, "U"),
+                        new TaggedRecordingExecutor(recorder, "D"),
+                        row -> new SeaTunnelRow(new Object[] 
{row.getField(0)}),
+                        Function.identity(),
+                        true);
+
+        executor.addToBatch(row(10, "ten"));
+        executor.addToBatch(row(2, "two"));
+        executor.addToBatch(row(11, "eleven"));
+        executor.executeBatch();
+
+        Assertions.assertEquals(Arrays.asList("U:2", "U:10", "U:11", 
"U:flush"), recorder);
+    }
+
+    @Test
+    void testTransactionConflictResetRetainsLogicalBuffer() throws 
SQLException {
+        List<String> recorder = new ArrayList<>();
+        RetryRecordingExecutor upsert = new RetryRecordingExecutor(recorder, 
"U");
+        BufferReducedBatchStatementExecutor executor =
+                new BufferReducedBatchStatementExecutor(
+                        upsert,
+                        new TaggedRecordingExecutor(recorder, "D"),
+                        Function.identity(),
+                        Function.identity());
+
+        executor.addToBatch(row(1, "one"));
+        Assertions.assertThrows(SQLException.class, executor::executeBatch);
+        executor.resetForTransactionConflictRetry();
+        executor.executeBatch();
+
+        Assertions.assertEquals(Arrays.asList("U:1", "U:1", "U:flush"), 
recorder);
+        Assertions.assertEquals(1, upsert.clearBatchCalls);
+    }
+
     @Test
     void testCompositeKeyWithNullComponentIsNotReduced() throws SQLException {
         List<SeaTunnelRow> upserts = new ArrayList<>();
@@ -206,6 +260,10 @@ public class BufferReducedBatchStatementExecutorTest 
extends BufferExecutorTest
         return row;
     }
 
+    private static SeaTunnelRow row(Object key, String value) {
+        return new SeaTunnelRow(new Object[] {key, value});
+    }
+
     private static class RecordingExecutor implements 
JdbcBatchStatementExecutor<SeaTunnelRow> {
         private final List<SeaTunnelRow> recorder;
 
@@ -227,4 +285,54 @@ public class BufferReducedBatchStatementExecutorTest 
extends BufferExecutorTest
         @Override
         public void closeStatements() {}
     }
+
+    private static class TaggedRecordingExecutor
+            implements JdbcBatchStatementExecutor<SeaTunnelRow> {
+        protected final List<String> recorder;
+        protected final String tag;
+
+        private TaggedRecordingExecutor(List<String> recorder, String tag) {
+            this.recorder = recorder;
+            this.tag = tag;
+        }
+
+        @Override
+        public void prepareStatements(Connection connection) {}
+
+        @Override
+        public void addToBatch(SeaTunnelRow record) {
+            recorder.add(tag + ":" + record.getField(0));
+        }
+
+        @Override
+        public void executeBatch() throws SQLException {
+            recorder.add(tag + ":flush");
+        }
+
+        @Override
+        public void closeStatements() {}
+    }
+
+    private static final class RetryRecordingExecutor extends 
TaggedRecordingExecutor {
+        private int executeBatchCalls;
+        private int clearBatchCalls;
+
+        private RetryRecordingExecutor(List<String> recorder, String tag) {
+            super(recorder, tag);
+        }
+
+        @Override
+        public void executeBatch() throws SQLException {
+            executeBatchCalls++;
+            if (executeBatchCalls == 1) {
+                throw new SQLException("deadlock", "40P01");
+            }
+            super.executeBatch();
+        }
+
+        @Override
+        public void clearBatch() {
+            clearBatchCalls++;
+        }
+    }
 }
diff --git 
a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-jdbc-e2e/connector-jdbc-e2e-part-3/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/JdbcPostgresIT.java
 
b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-jdbc-e2e/connector-jdbc-e2e-part-3/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/JdbcPostgresIT.java
index b8e8545a72..dde0cc210f 100644
--- 
a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-jdbc-e2e/connector-jdbc-e2e-part-3/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/JdbcPostgresIT.java
+++ 
b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-jdbc-e2e/connector-jdbc-e2e-part-3/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/JdbcPostgresIT.java
@@ -24,15 +24,27 @@ import org.apache.seatunnel.api.table.catalog.Catalog;
 import org.apache.seatunnel.api.table.catalog.CatalogTable;
 import org.apache.seatunnel.api.table.catalog.Column;
 import org.apache.seatunnel.api.table.catalog.ConstraintKey;
+import org.apache.seatunnel.api.table.catalog.PhysicalColumn;
 import org.apache.seatunnel.api.table.catalog.PrimaryKey;
 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.converter.BasicTypeDefine;
+import org.apache.seatunnel.api.table.type.BasicType;
+import org.apache.seatunnel.api.table.type.RowKind;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
 import org.apache.seatunnel.common.utils.JdbcUrlUtil;
 import 
org.apache.seatunnel.connectors.seatunnel.jdbc.catalog.psql.PostgresCatalog;
+import 
org.apache.seatunnel.connectors.seatunnel.jdbc.config.JdbcConnectionConfig;
+import org.apache.seatunnel.connectors.seatunnel.jdbc.config.JdbcSinkConfig;
+import 
org.apache.seatunnel.connectors.seatunnel.jdbc.internal.JdbcOutputFormat;
+import 
org.apache.seatunnel.connectors.seatunnel.jdbc.internal.JdbcOutputFormatBuilder;
+import 
org.apache.seatunnel.connectors.seatunnel.jdbc.internal.connection.JdbcConnectionProvider;
+import 
org.apache.seatunnel.connectors.seatunnel.jdbc.internal.connection.SimpleJdbcConnectionProvider;
 import 
org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.DatabaseIdentifier;
 import 
org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.duckdb.DuckDBTypeConverter;
+import 
org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.psql.PostgresDialect;
+import 
org.apache.seatunnel.connectors.seatunnel.jdbc.internal.executor.JdbcBatchStatementExecutor;
 import org.apache.seatunnel.e2e.common.TestResource;
 import org.apache.seatunnel.e2e.common.TestSuiteBase;
 import org.apache.seatunnel.e2e.common.container.ContainerExtendedFactory;
@@ -57,6 +69,8 @@ import org.testcontainers.utility.DockerLoggerFactory;
 import lombok.extern.slf4j.Slf4j;
 
 import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Proxy;
 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.PreparedStatement;
@@ -66,7 +80,12 @@ import java.sql.Statement;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
+import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
 
@@ -74,6 +93,7 @@ import static org.awaitility.Awaitility.given;
 
 @Slf4j
 public class JdbcPostgresIT extends TestSuiteBase implements TestResource {
+
     private static final String PG_IMAGE = "postgis/postgis";
 
     /**
@@ -368,6 +388,480 @@ public class JdbcPostgresIT extends TestSuiteBase 
implements TestResource {
         postgresCatalog.close();
     }
 
+    @Test
+    public void 
testDeadlockIsRolledBackAndRetriedForIndependentFlushTransactions()
+            throws Exception {
+        executeSQL(
+                "CREATE TABLE IF NOT EXISTS jdbc_deadlock_retry_test ("
+                        + "id INTEGER PRIMARY KEY, value INTEGER NOT NULL)");
+        executeSQL(
+                "INSERT INTO jdbc_deadlock_retry_test (id, value) VALUES (1, 
0), (2, 0) "
+                        + "ON CONFLICT (id) DO UPDATE SET value = 0");
+
+        CyclicBarrier firstRowBarrier = new CyclicBarrier(2);
+        AtomicInteger retryCount = new AtomicInteger();
+        JdbcConnectionConfig connectionConfig =
+                JdbcConnectionConfig.builder()
+                        .url(POSTGRESQL_CONTAINER.getJdbcUrl())
+                        .driverName(POSTGRESQL_CONTAINER.getDriverClassName())
+                        .username(POSTGRESQL_CONTAINER.getUsername())
+                        .password(POSTGRESQL_CONTAINER.getPassword())
+                        .autoCommit(false)
+                        .batchSize(100)
+                        .maxRetries(2)
+                        .build();
+
+        DeadlockExecutor firstExecutor =
+                new DeadlockExecutor(firstRowBarrier, retryCount, new int[] 
{1, 2});
+        DeadlockExecutor secondExecutor =
+                new DeadlockExecutor(firstRowBarrier, retryCount, new int[] 
{2, 1});
+        JdbcOutputFormat<SeaTunnelRow, DeadlockExecutor> firstOutput =
+                createDeadlockOutput(connectionConfig, firstExecutor);
+        JdbcOutputFormat<SeaTunnelRow, DeadlockExecutor> secondOutput =
+                createDeadlockOutput(connectionConfig, secondExecutor);
+        ExecutorService executorService = Executors.newFixedThreadPool(2);
+        try {
+            firstOutput.open();
+            secondOutput.open();
+            firstOutput.writeRecord(new SeaTunnelRow(new Object[] {1}));
+            firstOutput.writeRecord(new SeaTunnelRow(new Object[] {2}));
+            secondOutput.writeRecord(new SeaTunnelRow(new Object[] {2}));
+            secondOutput.writeRecord(new SeaTunnelRow(new Object[] {1}));
+
+            Future<?> firstFlush =
+                    executorService.submit(
+                            () -> {
+                                firstOutput.flush();
+                                return null;
+                            });
+            Future<?> secondFlush =
+                    executorService.submit(
+                            () -> {
+                                secondOutput.flush();
+                                return null;
+                            });
+            firstFlush.get(60, TimeUnit.SECONDS);
+            secondFlush.get(60, TimeUnit.SECONDS);
+            Assertions.assertTrue(retryCount.get() >= 1, "the database should 
report a deadlock");
+            List<List<Object>> values =
+                    querySql("SELECT id, value FROM jdbc_deadlock_retry_test 
ORDER BY id");
+            Assertions.assertEquals(
+                    Arrays.asList(Arrays.asList(1, 2), Arrays.asList(2, 2)), 
values);
+        } finally {
+            executorService.shutdownNow();
+            closeQuietly(firstOutput, "first output");
+            closeQuietly(secondOutput, "second output");
+            try {
+                executeSQL("DROP TABLE IF EXISTS jdbc_deadlock_retry_test");
+            } catch (Exception cleanupFailure) {
+                log.warn("Failed to drop the deadlock retry test table", 
cleanupFailure);
+            }
+        }
+    }
+
+    private JdbcOutputFormat<SeaTunnelRow, DeadlockExecutor> 
createDeadlockOutput(
+            JdbcConnectionConfig config, DeadlockExecutor executor) {
+        SimpleJdbcConnectionProvider provider = new 
SimpleJdbcConnectionProvider(config);
+        return new JdbcOutputFormat<>(provider, config, () -> executor, true);
+    }
+
+    /** Closes an output format without letting one cleanup failure skip the 
remaining steps. */
+    private void closeQuietly(JdbcOutputFormat<?, ?> output, String name) {
+        try {
+            output.close();
+        } catch (Exception cleanupFailure) {
+            log.warn("Failed to close the {}", name, cleanupFailure);
+        }
+    }
+
+    private static final class DeadlockExecutor
+            implements JdbcBatchStatementExecutor<SeaTunnelRow> {
+        private final CyclicBarrier firstRowBarrier;
+        private final AtomicInteger retryCount;
+        private final int[] rowOrder;
+        private boolean firstAttempt = true;
+        private PreparedStatement statement;
+
+        private DeadlockExecutor(
+                CyclicBarrier firstRowBarrier, AtomicInteger retryCount, int[] 
rowOrder) {
+            this.firstRowBarrier = firstRowBarrier;
+            this.retryCount = retryCount;
+            this.rowOrder = rowOrder;
+        }
+
+        @Override
+        public void prepareStatements(Connection connection) throws 
SQLException {
+            this.statement =
+                    connection.prepareStatement(
+                            "UPDATE jdbc_deadlock_retry_test SET value = value 
+ 1 WHERE id = ?");
+        }
+
+        @Override
+        public void addToBatch(SeaTunnelRow record) {}
+
+        @Override
+        public void executeBatch() throws SQLException {
+            boolean coordinateDeadlock = firstAttempt;
+            firstAttempt = false;
+            if (!coordinateDeadlock) {
+                retryCount.incrementAndGet();
+            }
+            for (int i = 0; i < rowOrder.length; i++) {
+                statement.setInt(1, rowOrder[i]);
+                statement.executeUpdate();
+                if (coordinateDeadlock && i == 0) {
+                    try {
+                        firstRowBarrier.await(30, TimeUnit.SECONDS);
+                    } catch (Exception e) {
+                        throw new SQLException("Unable to coordinate deadlock 
test", e);
+                    }
+                }
+            }
+        }
+
+        @Override
+        public boolean supportsTransactionConflictRetry() {
+            return true;
+        }
+
+        @Override
+        public void resetForTransactionConflictRetry() {}
+
+        @Override
+        public void closeStatements() throws SQLException {
+            if (statement != null) {
+                statement.close();
+            }
+        }
+    }
+
+    @Test
+    public void testDeadlockRetryWithRealUpsertExecutor() throws Exception {
+        // Two writers flush the same keys in opposite primary-key order 
through the production
+        // upsert wiring (JdbcOutputFormatBuilder -> 
BufferReducedBatchStatementExecutor), so
+        // PostgreSQL reports 40P01 for one flush and the sink must roll back 
and replay the
+        // whole flush transaction. Writers released from the same barrier 
normally interleave;
+        // the scenario is retried in the rare case their batches do not 
overlap.
+        boolean deadlockObserved = false;
+        for (int attempt = 0; attempt < 3 && !deadlockObserved; attempt++) {
+            deadlockObserved = runConcurrentUpsertDeadlockAttempt();
+        }
+        Assertions.assertTrue(
+                deadlockObserved, "PostgreSQL should report a deadlock between 
the two writers");
+    }
+
+    private boolean runConcurrentUpsertDeadlockAttempt() throws Exception {
+        String table = "public.jdbc_deadlock_real_upsert_test";
+        String auditTable = "public.jdbc_deadlock_real_upsert_audit";
+        // A large batch keeps both writers executing server-side long enough 
that the opposite
+        // traversal orders reliably interleave row locks.
+        int rowCount = 200;
+        executeSQL("DROP TABLE IF EXISTS " + auditTable);
+        executeSQL("DROP TABLE IF EXISTS " + table);
+        executeSQL("DROP FUNCTION IF EXISTS 
jdbc_deadlock_real_upsert_audit_fn()");
+        executeSQL("CREATE TABLE " + table + " (id INTEGER PRIMARY KEY, value 
INTEGER NOT NULL)");
+        executeSQL("INSERT INTO " + table + " (id, value) VALUES " + 
seedValues(rowCount, 0));
+        executeSQL("CREATE TABLE " + auditTable + " (seq BIGSERIAL, value 
INT)");
+        executeSQL(
+                "CREATE FUNCTION jdbc_deadlock_real_upsert_audit_fn() RETURNS 
trigger AS $$ "
+                        + "BEGIN INSERT INTO "
+                        + auditTable
+                        + " (value) VALUES (NEW.value); RETURN NULL; END $$ 
LANGUAGE plpgsql");
+        // Created after the seed INSERT, so the audit table records exactly 
the sink writes.
+        executeSQL(
+                "CREATE TRIGGER jdbc_deadlock_real_upsert_audit AFTER INSERT 
OR UPDATE ON "
+                        + table
+                        + " FOR EACH ROW EXECUTE FUNCTION 
jdbc_deadlock_real_upsert_audit_fn()");
+
+        JdbcConnectionConfig connectionConfig =
+                JdbcConnectionConfig.builder()
+                        .url(POSTGRESQL_CONTAINER.getJdbcUrl())
+                        .driverName(POSTGRESQL_CONTAINER.getDriverClassName())
+                        .username(POSTGRESQL_CONTAINER.getUsername())
+                        .password(POSTGRESQL_CONTAINER.getPassword())
+                        .autoCommit(false)
+                        .batchSize(rowCount + 1)
+                        .maxRetries(2)
+                        .build();
+        RollbackCountingProvider ascendingProvider =
+                new RollbackCountingProvider(new 
SimpleJdbcConnectionProvider(connectionConfig));
+        RollbackCountingProvider descendingProvider =
+                new RollbackCountingProvider(new 
SimpleJdbcConnectionProvider(connectionConfig));
+        JdbcOutputFormat<SeaTunnelRow, 
JdbcBatchStatementExecutor<SeaTunnelRow>> ascending =
+                createUpsertOutput(connectionConfig, table, false, 
ascendingProvider);
+        JdbcOutputFormat<SeaTunnelRow, 
JdbcBatchStatementExecutor<SeaTunnelRow>> descending =
+                createUpsertOutput(connectionConfig, table, false, 
descendingProvider);
+        CyclicBarrier startBarrier = new CyclicBarrier(2);
+        ExecutorService executorService = Executors.newFixedThreadPool(2);
+        try {
+            ascending.open();
+            descending.open();
+            for (int i = 1; i <= rowCount; i++) {
+                ascending.writeRecord(new SeaTunnelRow(new Object[] {i, 1}));
+            }
+            for (int i = rowCount; i >= 1; i--) {
+                descending.writeRecord(new SeaTunnelRow(new Object[] {i, 2}));
+            }
+            Future<?> firstFlush =
+                    executorService.submit(
+                            () -> {
+                                startBarrier.await(30, TimeUnit.SECONDS);
+                                ascending.flush();
+                                return null;
+                            });
+            Future<?> secondFlush =
+                    executorService.submit(
+                            () -> {
+                                startBarrier.await(30, TimeUnit.SECONDS);
+                                descending.flush();
+                                return null;
+                            });
+            firstFlush.get(120, TimeUnit.SECONDS);
+            secondFlush.get(120, TimeUnit.SECONDS);
+
+            // rollback() on these connections is only called by the 
transaction-conflict retry
+            // path, so a rollback proves the database reported a real 40P01 
without relying on
+            // the asynchronously published pg_stat_database counters.
+            int rollbacks = ascendingProvider.rollbackCount() + 
descendingProvider.rollbackCount();
+            if (rollbacks == 0) {
+                return false;
+            }
+
+            // Both flushes write every row: the winner's rowCount audit 
entries plus the
+            // victim's replayed rowCount entries. A replay that lost the 
buffered rows (the
+            // regression this test guards against) would leave only rowCount 
entries.
+            List<List<Object>> auditCounts =
+                    querySql(
+                            "SELECT value, count(*) FROM "
+                                    + auditTable
+                                    + " GROUP BY value ORDER BY value");
+            Assertions.assertEquals(
+                    Arrays.asList(
+                            Arrays.asList(1, (long) rowCount), 
Arrays.asList(2, (long) rowCount)),
+                    auditCounts,
+                    "the rolled-back flush must replay every buffered row");
+
+            List<List<Object>> rows = querySql("SELECT id, value FROM " + 
table + " ORDER BY id");
+            Assertions.assertEquals(rowCount, rows.size());
+            return true;
+        } finally {
+            executorService.shutdownNow();
+            closeQuietly(ascending, "ascending output");
+            closeQuietly(descending, "descending output");
+            try {
+                executeSQL("DROP TABLE IF EXISTS " + table);
+                executeSQL("DROP TABLE IF EXISTS " + auditTable);
+                executeSQL("DROP FUNCTION IF EXISTS 
jdbc_deadlock_real_upsert_audit_fn()");
+            } catch (Exception cleanupFailure) {
+                log.warn(
+                        "Failed to clean up the real-upsert deadlock test 
resources",
+                        cleanupFailure);
+            }
+        }
+    }
+
+    @Test
+    public void testUpsertBatchKeyOrderedMixedUpsertAndDelete() throws 
Exception {
+        // The key-ordered option must reach the production executor through 
the builder wiring.
+        // AFTER UPDATE/DELETE triggers record the execution order, so a batch 
written in
+        // unsorted order must land in primary-key order with one child batch 
per change-flag
+        // transition: U1, D2, U3, D4, U5.
+        String table = "public.jdbc_key_ordered_mixed_test";
+        String auditTable = "public.jdbc_key_ordered_mixed_audit";
+        executeSQL("DROP TABLE IF EXISTS " + table);
+        executeSQL("DROP TABLE IF EXISTS " + auditTable);
+        executeSQL("DROP FUNCTION IF EXISTS jdbc_key_ordered_audit_fn()");
+        executeSQL("CREATE TABLE " + table + " (id INTEGER PRIMARY KEY, value 
INTEGER NOT NULL)");
+        executeSQL("CREATE TABLE " + auditTable + " (seq BIGSERIAL, op 
CHAR(1), id INT)");
+        executeSQL(
+                "CREATE FUNCTION jdbc_key_ordered_audit_fn() RETURNS trigger 
AS $$ "
+                        + "BEGIN IF TG_OP = 'DELETE' THEN INSERT INTO "
+                        + auditTable
+                        + " (op, id) VALUES ('D', OLD.id); "
+                        + "ELSE INSERT INTO "
+                        + auditTable
+                        + " (op, id) VALUES ('U', NEW.id); "
+                        + "END IF; RETURN NULL; END $$ LANGUAGE plpgsql");
+        executeSQL(
+                "CREATE TRIGGER jdbc_key_ordered_audit_update AFTER UPDATE ON "
+                        + table
+                        + " FOR EACH ROW EXECUTE FUNCTION 
jdbc_key_ordered_audit_fn()");
+        executeSQL(
+                "CREATE TRIGGER jdbc_key_ordered_audit_delete AFTER DELETE ON "
+                        + table
+                        + " FOR EACH ROW EXECUTE FUNCTION 
jdbc_key_ordered_audit_fn()");
+        executeSQL("INSERT INTO " + table + " (id, value) VALUES " + 
seedValues(5, 0));
+
+        JdbcConnectionConfig connectionConfig =
+                JdbcConnectionConfig.builder()
+                        .url(POSTGRESQL_CONTAINER.getJdbcUrl())
+                        .driverName(POSTGRESQL_CONTAINER.getDriverClassName())
+                        .username(POSTGRESQL_CONTAINER.getUsername())
+                        .password(POSTGRESQL_CONTAINER.getPassword())
+                        .autoCommit(false)
+                        .batchSize(100)
+                        .maxRetries(0)
+                        .build();
+        JdbcOutputFormat<SeaTunnelRow, 
JdbcBatchStatementExecutor<SeaTunnelRow>> output =
+                createUpsertOutput(
+                        connectionConfig,
+                        table,
+                        true,
+                        new SimpleJdbcConnectionProvider(connectionConfig));
+        try {
+            output.open();
+            output.writeRecord(keyOrderedRow(RowKind.INSERT, 5, 51));
+            output.writeRecord(keyOrderedRow(RowKind.DELETE, 2, 0));
+            output.writeRecord(keyOrderedRow(RowKind.INSERT, 1, 11));
+            output.writeRecord(keyOrderedRow(RowKind.DELETE, 4, 0));
+            output.writeRecord(keyOrderedRow(RowKind.INSERT, 3, 33));
+            output.flush();
+
+            Assertions.assertEquals(
+                    Arrays.asList(
+                            Arrays.asList("U", 1),
+                            Arrays.asList("D", 2),
+                            Arrays.asList("U", 3),
+                            Arrays.asList("D", 4),
+                            Arrays.asList("U", 5)),
+                    querySql("SELECT op, id FROM " + auditTable + " ORDER BY 
seq"));
+            Assertions.assertEquals(
+                    Arrays.asList(Arrays.asList(1, 11), Arrays.asList(3, 33), 
Arrays.asList(5, 51)),
+                    querySql("SELECT id, value FROM " + table + " ORDER BY 
id"));
+        } finally {
+            output.close();
+            executeSQL("DROP TABLE IF EXISTS " + table);
+            executeSQL("DROP TABLE IF EXISTS " + auditTable);
+            executeSQL("DROP FUNCTION IF EXISTS jdbc_key_ordered_audit_fn()");
+        }
+    }
+
+    private JdbcOutputFormat<SeaTunnelRow, 
JdbcBatchStatementExecutor<SeaTunnelRow>>
+            createUpsertOutput(
+                    JdbcConnectionConfig connectionConfig,
+                    String table,
+                    boolean keyOrdered,
+                    JdbcConnectionProvider connectionProvider) {
+        // The schema-qualified table keeps the generated upsert/delete SQL 
and the test DDL in
+        // the same schema, independent of the connection's search_path.
+        String schema = table.substring(0, table.indexOf('.'));
+        String tableName = table.substring(table.indexOf('.') + 1);
+        JdbcSinkConfig sinkConfig =
+                JdbcSinkConfig.builder()
+                        .jdbcConnectionConfig(connectionConfig)
+                        .database(schema)
+                        .table(tableName)
+                        .primaryKeys(Collections.singletonList("id"))
+                        .enableUpsert(true)
+                        .upsertBatchKeyOrdered(keyOrdered)
+                        .build();
+        TableSchema tableSchema =
+                TableSchema.builder()
+                        .columns(
+                                Arrays.asList(
+                                        PhysicalColumn.of(
+                                                "id",
+                                                BasicType.INT_TYPE,
+                                                (Long) null,
+                                                false,
+                                                null,
+                                                null),
+                                        PhysicalColumn.of(
+                                                "value",
+                                                BasicType.INT_TYPE,
+                                                (Long) null,
+                                                false,
+                                                null,
+                                                null)))
+                        .build();
+        return new JdbcOutputFormatBuilder(
+                        new PostgresDialect(), connectionProvider, sinkConfig, 
tableSchema, null)
+                .commitOnFlush(true)
+                .build();
+    }
+
+    private static String seedValues(int count, int value) {
+        StringBuilder values = new StringBuilder();
+        for (int i = 1; i <= count; i++) {
+            values.append(i > 1 ? ", " : "")
+                    .append("(")
+                    .append(i)
+                    .append(", ")
+                    .append(value)
+                    .append(")");
+        }
+        return values.toString();
+    }
+
+    private static SeaTunnelRow keyOrderedRow(RowKind rowKind, int id, int 
value) {
+        SeaTunnelRow row = new SeaTunnelRow(new Object[] {id, value});
+        row.setRowKind(rowKind);
+        return row;
+    }
+
+    /**
+     * Counts {@link Connection#rollback()} calls made through the returned 
connections. The sink
+     * only rolls back after a detected transaction conflict, so this is a 
deterministic deadlock
+     * signal, unlike the asynchronously published pg_stat_database counters.
+     */
+    private static final class RollbackCountingProvider implements 
JdbcConnectionProvider {
+        private final JdbcConnectionProvider delegate;
+        private final AtomicInteger rollbackCount = new AtomicInteger();
+
+        private RollbackCountingProvider(JdbcConnectionProvider delegate) {
+            this.delegate = delegate;
+        }
+
+        private int rollbackCount() {
+            return rollbackCount.get();
+        }
+
+        private Connection countRollbacks(Connection real) {
+            if (real == null) {
+                return null;
+            }
+            return (Connection)
+                    Proxy.newProxyInstance(
+                            Connection.class.getClassLoader(),
+                            new Class<?>[] {Connection.class},
+                            (proxy, method, args) -> {
+                                if ("rollback".equals(method.getName())) {
+                                    rollbackCount.incrementAndGet();
+                                }
+                                try {
+                                    return method.invoke(real, args);
+                                } catch (InvocationTargetException e) {
+                                    throw e.getCause();
+                                }
+                            });
+        }
+
+        @Override
+        public Connection getConnection() {
+            return countRollbacks(delegate.getConnection());
+        }
+
+        @Override
+        public boolean isConnectionValid() throws SQLException {
+            return delegate.isConnectionValid();
+        }
+
+        @Override
+        public Connection getOrEstablishConnection() throws SQLException, 
ClassNotFoundException {
+            return countRollbacks(delegate.getOrEstablishConnection());
+        }
+
+        @Override
+        public void closeConnection() {
+            delegate.closeConnection();
+        }
+
+        @Override
+        public Connection reestablishConnection() throws SQLException, 
ClassNotFoundException {
+            return countRollbacks(delegate.reestablishConnection());
+        }
+    }
+
     @Test
     public void testDuckDbUnboundedStringAutoDdl() throws Exception {
         String label = String.join("", Collections.nCopies(400, "m"));

Reply via email to