You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by gi...@apache.org on 2026/09/10 15:43:35 UTC

(seatunnel) 01/01: [Fix][API] Fix negative queue index when primary key hash is Integer.MIN_VALUE (#11721)

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

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

commit 3ab7dcde597d8224f6150dcb873643a2b32e7659
Author: Sepuri Sai Krishna <sa...@gmail.com>
AuthorDate: Thu Sep 10 15:37:28 2026 +0000

    [Fix][API] Fix negative queue index when primary key hash is Integer.MIN_VALUE (#11721)
    
    Co-authored-by: David Zollo <da...@gmail.com>
---
 docs/en/architecture/features/multi-table.md       | 25 +++---
 docs/zh/architecture/features/multi-table.md       | 16 ++--
 .../sink/multitablesink/MultiTableSinkWriter.java  |  9 ++-
 .../multitablesink/MultiTableSinkWriterTest.java   | 94 ++++++++++++++++++++++
 4 files changed, 120 insertions(+), 24 deletions(-)

diff --git a/docs/en/architecture/features/multi-table.md b/docs/en/architecture/features/multi-table.md
index 339b54b933..a87d2e9851 100644
--- a/docs/en/architecture/features/multi-table.md
+++ b/docs/en/architecture/features/multi-table.md
@@ -306,10 +306,9 @@ public class MultiTableSinkWriter
             Object object = element.getField(primaryKey.get());
             int index = 0;
             if (object != null) {
-                // Known issue: Math.abs(Integer.MIN_VALUE) returns Integer.MIN_VALUE
-                // unchanged (still negative), so a key hashing to it yields a negative
-                // queue index. See section 5.3.
-                index = Math.abs(object.hashCode()) % blockingQueues.size();
+                // Clear the sign bit rather than using Math.abs: Math.abs(Integer.MIN_VALUE)
+                // returns Integer.MIN_VALUE unchanged, which would yield a negative index.
+                index = (object.hashCode() & Integer.MAX_VALUE) % blockingQueues.size();
             }
             offerRowElement(index, element);
         }
@@ -403,17 +402,17 @@ Both strategies select a queue index in `[0, blockingQueues.size())`. See
 which is what preserves ordering for that key:
 
 ```java
-int index = Math.abs(object.hashCode()) % blockingQueues.size();
+int index = (object.hashCode() & Integer.MAX_VALUE) % blockingQueues.size();
 ```
 
-:::caution Known issue
+:::note
 
-`Math.abs(Integer.MIN_VALUE)` returns `Integer.MIN_VALUE`, which is still negative, so a
-key whose hash is exactly `Integer.MIN_VALUE` produces a negative index whenever the queue
-count is not a power of two, and the subsequent `blockingQueues.get(index)` throws
-`IndexOutOfBoundsException`. This page documents the behaviour currently on `dev`; the
-defect is tracked in [#11720](https://github.com/apache/seatunnel/issues/11720), and this
-section should be updated when a fix lands.
+The sign bit is cleared with `& Integer.MAX_VALUE` rather than with `Math.abs`, because
+`Math.abs(Integer.MIN_VALUE)` returns `Integer.MIN_VALUE` unchanged — still negative. A key
+whose hash is exactly `Integer.MIN_VALUE` would otherwise produce a negative index whenever
+the queue count is not a power of two, and the subsequent `blockingQueues.get(index)` would
+throw `IndexOutOfBoundsException`. Masking is branch-free and correct for every input.
+Tracked as [#11720](https://github.com/apache/seatunnel/issues/11720).
 
 :::
 
@@ -425,7 +424,7 @@ int index = random.nextInt(blockingQueues.size());
 
 `random.nextInt(bound)` is used rather than a time-derived expression such as
 `System.nanoTime() % n`. `System.nanoTime()` is documented as possibly negative, so that
-expression can produce a negative index for exactly the same reason `Math.abs` can above.
+expression can produce a negative index for the same reason the hash is masked above.
 
 ## 6. Schema Management in Multi-Table
 
diff --git a/docs/zh/architecture/features/multi-table.md b/docs/zh/architecture/features/multi-table.md
index 71067d5a80..30bdce1313 100644
--- a/docs/zh/architecture/features/multi-table.md
+++ b/docs/zh/architecture/features/multi-table.md
@@ -195,15 +195,15 @@ sink {
 
 要点:
 - 以主键(或业务唯一键)做哈希,将同一键稳定映射到同一副本
-- 当前实现: $replica = \mathrm{Math.abs}(hash(pk)) \bmod replicaNum$
+- 当前实现: $replica = (hash(pk) \mathbin{\&} \mathrm{Integer.MAX\_VALUE}) \bmod replicaNum$
 
-:::caution 已知问题
+:::note
 
-`Math.abs(Integer.MIN_VALUE)` 仍返回 `Integer.MIN_VALUE`(负数),因此当主键哈希恰好为
-`Integer.MIN_VALUE` 且副本数不是 2 的幂时会得到负的下标,随后的
-`blockingQueues.get(index)` 会抛出 `IndexOutOfBoundsException`。本页描述的是 `dev`
-分支当前的实际行为;该缺陷记录在
-[#11720](https://github.com/apache/seatunnel/issues/11720),修复合入后需同步更新本节。
+这里用 `& Integer.MAX_VALUE` 清除符号位,而不是用 `Math.abs`:`Math.abs(Integer.MIN_VALUE)`
+仍返回 `Integer.MIN_VALUE`(负数)。否则当主键哈希恰好为 `Integer.MIN_VALUE` 且副本数不是
+2 的幂时会得到负的下标,随后的 `blockingQueues.get(index)` 会抛出
+`IndexOutOfBoundsException`。掩码写法无分支,且对任意输入都成立。相关记录见
+[#11720](https://github.com/apache/seatunnel/issues/11720)。
 
 :::
 
@@ -212,7 +212,7 @@ sink {
 要点:
 - 当记录缺少主键字段信息时,无法提供稳定落点
 - 使用 `Random.nextInt(blockingQueues.size())` 在副本间扩散压力,但不保证同一键的顺序性
-- 不使用 `System.nanoTime() % replicaNum` 之类的写法:`nanoTime()` 可能为负,同样会产生负下标
+- 不使用 `System.nanoTime() % replicaNum` 之类的写法:`nanoTime()` 可能为负,会产生负下标,原因与上面哈希需要掩码相同
 
 ## 6. 多表中的模式管理
 
diff --git a/seatunnel-api/src/main/java/org/apache/seatunnel/api/sink/multitablesink/MultiTableSinkWriter.java b/seatunnel-api/src/main/java/org/apache/seatunnel/api/sink/multitablesink/MultiTableSinkWriter.java
index 453effddfe..e17eca1503 100644
--- a/seatunnel-api/src/main/java/org/apache/seatunnel/api/sink/multitablesink/MultiTableSinkWriter.java
+++ b/seatunnel-api/src/main/java/org/apache/seatunnel/api/sink/multitablesink/MultiTableSinkWriter.java
@@ -563,8 +563,8 @@ public class MultiTableSinkWriter
      *
      * <ul>
      *   <li>If the table's primary key information is present and the primary key field value is
-     *       non-null, the row is routed by {@code Math.abs(primaryKeyValue.hashCode()) %
-     *       queueSize}, guaranteeing that rows with the same primary key always go to the same
+     *       non-null, the row is routed by {@code (primaryKeyValue.hashCode() & Integer.MAX_VALUE)
+     *       % queueSize}, guaranteeing that rows with the same primary key always go to the same
      *       queue for ordered delivery.
      *   <li>If the table's primary key information is present but the actual field value is {@code
      *       null}, the row is routed to queue 0.
@@ -616,7 +616,10 @@ public class MultiTableSinkWriter
             Object object = element.getField(primaryKey.get());
             int index = 0;
             if (object != null) {
-                index = Math.abs(object.hashCode()) % blockingQueues.size();
+                // Clear the sign bit rather than using Math.abs: Math.abs(Integer.MIN_VALUE) is
+                // still Integer.MIN_VALUE, which would yield a negative queue index whenever the
+                // queue count is not a power of two.
+                index = (object.hashCode() & Integer.MAX_VALUE) % blockingQueues.size();
             }
             offerRowElement(index, element);
         }
diff --git a/seatunnel-api/src/test/java/org/apache/seatunnel/api/sink/multitablesink/MultiTableSinkWriterTest.java b/seatunnel-api/src/test/java/org/apache/seatunnel/api/sink/multitablesink/MultiTableSinkWriterTest.java
index 10e2b19a8b..9d9bcfed41 100644
--- a/seatunnel-api/src/test/java/org/apache/seatunnel/api/sink/multitablesink/MultiTableSinkWriterTest.java
+++ b/seatunnel-api/src/test/java/org/apache/seatunnel/api/sink/multitablesink/MultiTableSinkWriterTest.java
@@ -927,6 +927,100 @@ public class MultiTableSinkWriterTest {
         Assertions.assertTrue(restored.getFailedTables().isEmpty());
     }
 
+    /**
+     * A primary key whose {@code hashCode()} is {@link Integer#MIN_VALUE} must still route to a
+     * valid queue. {@code Math.abs(Integer.MIN_VALUE)} is itself negative, so the old routing
+     * produced a negative index and the write failed with {@link IndexOutOfBoundsException}
+     * whenever the replica count was not a power of two.
+     */
+    @Test
+    public void testMinValuePrimaryKeyHashRoutesToValidQueue() throws IOException {
+        // 3 is not a power of two, so Integer.MIN_VALUE % 3 == -2 under the old routing
+        int replicaNum = 3;
+        // Under the fix both rows route to (Integer.MIN_VALUE & Integer.MAX_VALUE) % 3 == 0.
+        int expectedIndex = (Integer.MIN_VALUE & Integer.MAX_VALUE) % replicaNum;
+        Assertions.assertEquals(0, expectedIndex);
+
+        Map<SinkIdentifier, SinkWriter<SeaTunnelRow, ?, ?>> sinkWriters = new HashMap<>();
+        Map<SinkIdentifier, SinkWriter.Context> sinkWritersContext = new HashMap<>();
+        RecordingSinkWriter[] writersByIndex = new RecordingSinkWriter[replicaNum];
+        for (int i = 0; i < replicaNum; i++) {
+            SinkIdentifier identifier = SinkIdentifier.of("test.table", i);
+            RecordingSinkWriter writer = new RecordingSinkWriter(false);
+            writersByIndex[i] = writer;
+            sinkWriters.put(identifier, writer);
+            sinkWritersContext.put(identifier, new TestSinkWriterContext());
+        }
+
+        MultiTableSinkWriter multiTableSinkWriter =
+                new MultiTableSinkWriter(sinkWriters, replicaNum, sinkWritersContext);
+
+        // Integer.valueOf(Integer.MIN_VALUE).hashCode() and Long.valueOf(Long.MIN_VALUE)
+        // .hashCode() are both Integer.MIN_VALUE
+        SeaTunnelRow longKeyRow = new SeaTunnelRow(new Object[] {Long.MIN_VALUE});
+        longKeyRow.setTableId("test.table");
+
+        Assertions.assertDoesNotThrow(
+                () -> multiTableSinkWriter.write(buildRow("test.table", Integer.MIN_VALUE)));
+        Assertions.assertDoesNotThrow(() -> multiTableSinkWriter.write(longKeyRow));
+
+        Optional<MultiTableCommitInfo> commitInfo = multiTableSinkWriter.prepareCommit(1L);
+        Assertions.assertTrue(commitInfo.isPresent());
+
+        int totalWrites =
+                sinkWriters.values().stream()
+                        .mapToInt(writer -> ((RecordingSinkWriter) writer).getWriteCount())
+                        .sum();
+        Assertions.assertEquals(2, totalWrites);
+
+        // Pin the target queue exactly rather than only asserting no-throw: both rows must land
+        // in queue 0 and nowhere else, so this fails if the routing regresses, not merely if it
+        // throws.
+        Assertions.assertEquals(2, writersByIndex[expectedIndex].getWriteCount());
+        for (int i = 0; i < replicaNum; i++) {
+            if (i != expectedIndex) {
+                Assertions.assertEquals(0, writersByIndex[i].getWriteCount());
+            }
+        }
+    }
+
+    @Test
+    public void testOrdinaryNegativeHashRoutesToMaskedIndex() throws IOException {
+        // The fix is a general bitmask, not a special case for Integer.MIN_VALUE: it changes the
+        // index for every negative hash, since Math.abs(h) is -h while h & Integer.MAX_VALUE is
+        // h + 2^31. An INT primary key hashes to its own value, so this key's hash is -5, and:
+        //   old routing: Math.abs(-5) % 3               == 2
+        //   new routing: (-5 & Integer.MAX_VALUE) % 3   == 0
+        // The resulting index is asserted exactly, not merely checked for being in range.
+        int replicaNum = 3;
+        int primaryKey = -5;
+        int expectedIndex = (primaryKey & Integer.MAX_VALUE) % replicaNum;
+        Assertions.assertEquals(0, expectedIndex);
+
+        Map<SinkIdentifier, SinkWriter<SeaTunnelRow, ?, ?>> sinkWriters = new HashMap<>();
+        Map<SinkIdentifier, SinkWriter.Context> sinkWritersContext = new HashMap<>();
+        RecordingSinkWriter[] writersByIndex = new RecordingSinkWriter[replicaNum];
+        for (int i = 0; i < replicaNum; i++) {
+            SinkIdentifier identifier = SinkIdentifier.of("test.table", i);
+            RecordingSinkWriter writer = new RecordingSinkWriter(false);
+            writersByIndex[i] = writer;
+            sinkWriters.put(identifier, writer);
+            sinkWritersContext.put(identifier, new TestSinkWriterContext());
+        }
+
+        MultiTableSinkWriter multiTableSinkWriter =
+                new MultiTableSinkWriter(sinkWriters, replicaNum, sinkWritersContext);
+
+        multiTableSinkWriter.write(buildRow("test.table", primaryKey));
+
+        Optional<MultiTableCommitInfo> commitInfo = multiTableSinkWriter.prepareCommit(1L);
+        Assertions.assertTrue(commitInfo.isPresent());
+
+        Assertions.assertEquals(1, writersByIndex[expectedIndex].getWriteCount());
+        // Index 2 is where the old Math.abs routing would have sent this row.
+        Assertions.assertEquals(0, writersByIndex[2].getWriteCount());
+    }
+
     private SeaTunnelRow buildRow(String tableId, int value) {
         SeaTunnelRow row = new SeaTunnelRow(new Object[] {value});
         row.setTableId(tableId);