Skip to content

[Improve][API] Use HashUtils.bucketIndex in MultiTableSinkWriter routing - #12290

Merged
nzw921rx merged 4 commits into
apache:devfrom
SEPURI-SAI-KRISHNA:migrate-multitablesink-bucketindex
Oct 2, 2026
Merged

nzw921rx merged 4 commits into
apache:devfrom
SEPURI-SAI-KRISHNA:migrate-multitablesink-bucketindex

Conversation

@SEPURI-SAI-KRISHNA

@SEPURI-SAI-KRISHNA SEPURI-SAI-KRISHNA commented Sep 13, 2026 •

Copy link
Copy Markdown
Collaborator

Purpose of this pull request

Close #11976

#11721 fixed the negative queue index in MultiTableSinkWriter by clearing the sign bit inline. That was deliberate rather than preferred: HashUtils.bucketIndex did not exist at that branch point. It landed on dev through #11987 on 2026-09-01, a week after #11721's last dev merge, so adopting it there would have meant a fresh merge and a re-review of an already approved diff. #11976 was opened to track the migration and held open until #11721 merged, which it did on 2026-09-10.

This is that migration:

- index = (object.hashCode() & Integer.MAX_VALUE) % blockingQueues.size();
+ index = HashUtils.bucketIndex(object.hashCode(), blockingQueues.size());

The two are the same function for every input. HashUtils.bucketIndex(int, int) is exactly (hash & Integer.MAX_VALUE) % bucketCount, so routing is unchanged for every key, including Integer.MIN_VALUE. This removes the last remaining copy of the idiom and moves the reasoning into one documented place rather than a comment at the call site. #11987 migrated the other call sites when it introduced the helper, and #12049 did the AzureCosmosDB enumerator.

The javadoc on write(SeaTunnelRow) is updated to point at the helper instead of restating the expression.

One deliberate behavioral difference: bucketIndex rejects a non-positive bucketCount with IllegalArgumentException, where the inline form would have thrown ArithmeticException on division by zero. That path is unreachable here, since an empty queue list would already fail earlier in the random-routing branch on Random.nextInt(0), and the explicit message is the better outcome if it ever became reachable.

Note also that object.hashCode() is an int, so this binds to the int overload. HashUtils documents that the int and long overloads are distinct mappings rather than a widening, and a call site must not be switched between them. This one is not.

Does this PR introduce any user-facing change?

No. Same routing for every input, no config or API surface touched.

How was this patch tested?

The existing routing tests in MultiTableSinkWriterTest are unchanged and still pass, including the one that pins the exact target queue for a primary key whose hashCode() is Integer.MIN_VALUE. That test is what makes this a safe swap: it asserts the concrete index, not merely that the index is non-negative, so a change in mapping would fail it.

./mvnw -pl seatunnel-api -Dskip.spotless=true test
Tests run: 398, Failures: 0, Errors: 0, Skipped: 0

./mvnw -pl seatunnel-api spotless:check passes.

apache#11721 fixed the negative queue index by masking the sign bit inline, because
the shared helper did not exist at that point. HashUtils.bucketIndex landed
separately in apache#11987, a week after apache#11721's branch point, so the two could not
be combined at the time.

Both spellings are the same function: bucketIndex is exactly
(hash & Integer.MAX_VALUE) % bucketCount. This replaces the inline expression
with the call, which removes the last copy of the idiom in the codebase and
puts the Integer.MIN_VALUE reasoning in one documented place instead of a
comment at the call site.

The helper rejects a non-positive bucketCount with IllegalArgumentException
where the inline form would divide by zero. That path is unreachable here,
since an empty queue list would already fail in the random-routing branch on
Random.nextInt(0), and an explicit message is the better outcome either way.

The existing routing tests are unchanged and still pin the exact target queue
for an Integer.MIN_VALUE primary key hash.

Closes apache#11976
@github-actions github-actions Bot added the api label Sep 13, 2026

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What Problem Does This PR Solve?

This is a pure internal refactor, not a bug fix. MultiTableSinkWriter.write(SeaTunnelRow) routes a row to a queue by (primaryKeyValue.hashCode() & Integer.MAX_VALUE) % blockingQueues.size(). That exact expression, and the reasoning behind it (why masking the sign bit and not Math.abs, because Math.abs(Integer.MIN_VALUE) is still negative), was written inline as part of #11721's fix for the Integer.MIN_VALUE routing bug. Since then, HashUtils.bucketIndex(int, int) was added in #11987 as the shared home for exactly this idiom, used by many split enumerators. This PR swaps the inline expression for the shared helper, closing the tracking issue #11976 that was left open for this migration until #11721 landed.

Before/after example: for blockingQueues.size() == 3 and a primary key whose hashCode() is Integer.MIN_VALUE:

  • Before: index = (Integer.MIN_VALUE & Integer.MAX_VALUE) % 3 computed inline -> 0.
  • After: index = HashUtils.bucketIndex(Integer.MIN_VALUE, 3) -> (Integer.MIN_VALUE & Integer.MAX_VALUE) % 3 -> 0.

Same result for every input; nothing a job author or operator observes changes.

1. Code Change Review

1.1 Core Logic Analysis

Change is confined to seatunnel-api/.../MultiTableSinkWriter.java, write(SeaTunnelRow) (line ~617-621 in the PR head):

- index = (object.hashCode() & Integer.MAX_VALUE) % blockingQueues.size();
+ index = HashUtils.bucketIndex(object.hashCode(), blockingQueues.size());

I read HashUtils.bucketIndex(int, int) at head (seatunnel-common/.../utils/HashUtils.java):

public static int bucketIndex(int hash, int bucketCount) {
    checkBucketCount(bucketCount);
    return (hash & Integer.MAX_VALUE) % bucketCount;
}

This is byte-for-byte the same computation as the inline expression it replaces, just with an added bucketCount <= 0 guard in front. So the routing function is provably identical for every int input, including Integer.MIN_VALUE — no need to take the PR description's word for it.

Runtime flow: write() is on the normal per-row hot path (not a boundary/recovery path) for any multi-table sink with a primary key present and non-null on the row — this is the common case for CDC/ordered-delivery sinks, so this is squarely a mainline-path change, which is exactly why it deserves the scrutiny it's getting.

The javadoc on write(SeaTunnelRow) is updated to point at HashUtils#bucketIndex instead of re-deriving the masking rationale at the call site — good, it keeps one source of truth instead of two copies of the same reasoning drifting apart.

One correctness nuance the PR calls out and I verified independently: object.hashCode() returns int, so this resolves to the bucketIndex(int, int) overload, not bucketIndex(long, int). The two overloads are documented as distinct mappings (not a widening), so this is the right overload and there's no accidental semantic change from an overload mismatch.

1.2 Compatibility Impact

Fully compatible. No config, API, protocol, or serialization surface is touched. Routing output is identical for every hash/queue-count combination, so:

  • No redistribution of in-flight or replayed rows across writer queues on upgrade.
  • No checkpoint/state compatibility concern — this method doesn't participate in checkpoint state, it only routes a row to a queue at write time.

The one behavioral delta, and it's a genuine (not overlooked) one: if blockingQueues.size() were ever 0, the old code would throw ArithmeticException (% 0 on int), the new code throws IllegalArgumentException from checkBucketCount. I checked whether this path is actually reachable: blockingQueues is populated once in the constructor from queueSize, and the same write() method's random-routing branch (line ~604, unchanged) already calls random.nextInt(blockingQueues.size()), which itself throws for a non-positive bound. So a queueSize == 0 writer is already broken well before this change; this PR doesn't introduce a new failure mode, it just changes the exception type at one of several call sites that would already fail. Not user-facing today, since queueSize is always derived from the number of physical sinks/parallelism (never zero in the constructor call sites I checked).

1.3 Performance / Side-Effect Analysis

None. HashUtils.bucketIndex is a two-operation static call (a comparison + branch on bucketCount, then the same mask-and-modulo). No allocation, no locking, no I/O. Negligible/no measurable overhead versus the inline expression, called once per row on the hot path.

1.4 Error Handling and Logging

No behavior change in the reachable path (see 1.2). No new logging, no swallowed exceptions.

2. Code Quality Assessment

2.1 Coding Standards

New import (HashUtils) is used, no dead import left behind. No new public method or field is introduced by this PR, so there's nothing new here requiring its own Javadoc; the existing write(SeaTunnelRow) doc is correctly updated instead of just deleted. Diff is minimal and matches the stated intent — nothing extraneous is touched in this class-heavy file.

2.2 Test Coverage and Test Stability

The diff does not touch MultiTableSinkWriterTest.java (0 test files changed), which is fine here because the pre-existing tests from #11721 already pin the exact routing outcome rather than merely asserting "does not throw":

  • testMinValuePrimaryKeyHashRoutesToValidQueue computes expectedIndex = (Integer.MIN_VALUE & Integer.MAX_VALUE) % replicaNum and asserts writes landed in that exact queue and nowhere else.
  • testOrdinaryNegativeHashRoutesToMaskedIndex does the same for an ordinary negative hash (-5), explicitly asserting the masked index differs from where Math.abs routing would have sent it.

Since both asserted expectedIndex values are computed with the identical (hash & Integer.MAX_VALUE) % bucketCount formula that HashUtils.bucketIndex implements, these tests exercise the new call path and would fail on any routing regression, not just a crash. This is a case where "no test changes" is the correct outcome, not a coverage gap — I verified this by reading the test file at the PR head rather than taking the PR description's claim at face value.

No UT/E2E code is touched by this diff, so the mandatory flaky-test analysis doesn't apply; nothing here introduces timing, ordering, or environment dependence. Stability rating: Stable.

2.3 Documentation Updates

N/A — no user-facing config, CLI, or connector doc references this internal routing expression. docs/en / docs/zh don't need changes.

3. Architectural Soundness

3.1 Elegance of the Solution

This is the precise fix, not a workaround: it removes the last inline copy of an idiom that already has a shared, documented, tested home, without changing behavior. Matches the pattern already applied to ~15 other call sites (Kafka, ClickHouse, JDBC, Fluss, HBase, MongoDB, Iceberg, Paimon, Pulsar, RocketMQ, Bigtable, AzureCosmosDB, etc. — confirmed via HashUtils.bucketIndex usage search at head).

3.2 Maintainability

Improves it: one place (HashUtils) now carries the "why masking, not Math.abs" reasoning and the "don't confuse the int/long overloads" warning, instead of a comment that could drift from the shared helper's own doc over time.

3.3 Extensibility

No impact — this is a leaf call site, not an abstraction boundary.

3.4 Historical-Version Compatibility

No concern: routing is byte-for-byte identical for every input (proven above from the helper's actual implementation, not inferred from the PR description), so upgrading a running job across this change redistributes nothing.

4. Issue Summary

# Issue Location Severity
1 PR description misattributes part of the "other call sites" migration history to #11937, which is actually an unrelated Zeta SQL ROUND/CEIL numeric-type fix ("Handle TINYINT and SMALLINT in Zeta SQL numeric functions"). All other call-site migrations I could find (Kafka, ClickHouse, JDBC, Fluss, HBase, MongoDB, Iceberg, Paimon, Pulsar, RocketMQ, Bigtable) were introduced by #11987 itself, and AzureCosmosDB by #12049 — I could not find any HashUtils-related change in #11937. This doesn't affect the code, only the PR's narrative/traceability. PR description Low

No other issues found — the diff is a byte-for-byte behavior-preserving refactor and I independently verified the equivalence from the actual HashUtils source rather than accepting the PR's claim.

5. Merge Recommendation

Conclusion: Ready to merge

  1. Blockers — none.
  2. Recommended fixes — non-blocking:
    • Correct or drop the #11937 reference in the PR description (issue #1 above) before merge, purely for accurate history; it has no effect on the code itself.

Overall assessment: This is exactly the kind of change that should be simple to review and is: single file, single expression swapped for an equivalent library call, existing tests already pin the exact numeric outcome so a routing regression would fail loudly, and the routing function was verified equivalent by reading the actual HashUtils implementation rather than trusting the PR's own equivalence claim. blockingQueues/queue-count reachability for the one behavioral delta (exception type on an already-unreachable bucketCount == 0) was traced through the constructor and the adjacent random-routing branch, not assumed.

CI: As of this review, the apache-side "Build" check and the fork's own Build workflow run are both still in progress/queued (fork run 34740599956 on SEPURI-SAI-KRISHNA/seatunnel, branch migrate-multitablesink-bucketindex, was still queued/no conclusion at review time) — no result to diagnose yet. Given the scope of this change (one file, no new dependencies, seatunnel-api already depends on seatunnel-common for other utils), I'd expect a clean pass; please let it finish and it should be squash-mergeable once green.

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Collaborator Author

Thanks for the review, and for catching the history error.

You are right and I have corrected the description. #11937 is "[Fix][Transform-V2] Handle TINYINT and SMALLINT in Zeta SQL numeric functions" and has nothing to do with HashUtils; it touches NumericFunction and the SQL function docs. I checked its file list to confirm rather than just taking the correction. #11987 migrated the other call sites itself when it introduced the helper, and #12049 did the AzureCosmosDB enumerator, so those are the two the description should have named.

On your reachability trace for bucketCount == 0: that matches what I found. The random-routing branch calls random.nextInt(blockingQueues.size()) first, so a writer with an empty queue list is already broken before this line is reached, and the change only alters which exception a path that cannot be entered would throw.

On CI: the fork run is still going, and I would rather let it finish than rerun into what looks like a bad window. The failures so far are not specific to this change. They overlap almost exactly with the ones on my other open PR #12182, which is a test-only change in seatunnel-transforms-v2 and shares no code with this one: all-connectors-it-6, all-connectors-it-7 and paimon-connector-it all failed on both, on both JDK legs.

Where I have read the logs, the causes are environmental rather than assertions. paimon-connector-it failed before any test ran, with Could not transfer artifact org.apache.commons:commons-lang3:jar:3.5 from/to central and The build could not read 2 projects. all-connectors-it-7 failed on ContainerFetchException: Can't get Docker image: minio/minio:RELEASE.2024-06-13T22-53-53Z. This run also lost Run / Dead links, which only checks URLs. A one line swap to a helper in seatunnel-api cannot reach any of those.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks for tightening up the description and for double-checking the reachability trace independently rather than just taking my word for it — appreciated.

One thing worth correcting before you spend more reruns waiting on it: the minio/minio failure on all-connectors-it-7 isn't a bad window, it's minio/minio having been permanently removed from Docker Hub (the 404 repository does not exist is the signature; a rate limit would be a 429). It's already fixed on dev via #12287 (switches MinIOContainer usage to the quay.io/minio/minio mirror). Waiting it out won't help there — a sync with the latest dev would. The paimon-connector-it Maven dependency-resolution failure and the lost Dead links job are separate and a sync may or may not touch those, but the MinIO one specifically has a known available fix.

Doesn't change my approval on this one — still a clean, self-contained one-line swap in seatunnel-api with no path to any of these failures.

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Collaborator Author

Agreed, and that matches what I found independently before reading this. Syncing now.

Two refinements from the attempt 2 logs.

paimon-connector-it is no longer the Maven resolution failure. That was the signature on attempt 1. On attempt 2 it is PaimonWithS3IT.startUp:151 » ContainerFetch, the same MinIO pull, so the sync should clear it along with the rest. Dead links also came back green on this attempt. On this run every failed leg was MinIO and nothing else: IcebergSourceIT.startUp:161, DatabendIT.startUp:249, DatabendCDCSinkIT.startUp:221, S3FileWithFilterIT.startUp:76 and PaimonWithS3IT.startUp:151.

On the registry state, what is observable from outside is that anonymous pulls are denied, rather than that the repository is definitely gone. An anonymous manifest request for minio/minio returns 401 UNAUTHORIZED, the same request for library/alpine returns 200, and the Hub API reports the minio/minio repository as not found. The daemon collapses that into 404 ... repository does not exist or may require 'docker login'. The distinction only matters in that a Hub credential would be the alternative fix, and the quay mirror is clearly the better one, so nothing here argues against #12287. The comment #12287 adds at the call sites reads the same way, that Docker Hub "no longer serves anonymous/unauthenticated pulls".

One thing to expect after the sync: all-connectors-it-7 will likely still fail, on a different MinIO reference. S3FileConnectDryRunIT was added by #12242 at 10:31Z on 09-13, after #12287 was written, and still points at Docker Hub on dev. It sits in connector-file-s3-e2e, the same module as S3FileWithFilterIT, so that leg stays red until #12302 lands.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What Problem Does This PR Solve?

Sorry for missing this in the last review — that's on me. I re-reviewed the latest head and want to flag that this is actually a non-event from a code perspective: the only new commit since my prior approval is a merge from upstream/dev (b319d412) to pick up unrelated dev fixes for the CI environment issues we discussed on this thread (notably the minio/minio Docker Hub removal fix, #12287). It carries no new business-logic change.

This PR itself replaces the inline (primaryKeyValue.hashCode() & Integer.MAX_VALUE) % blockingQueues.size() expression in MultiTableSinkWriter.write(SeaTunnelRow) with the equivalent shared helper HashUtils.bucketIndex(int, int), closing out the migration tracked by #11976 now that #11721 (which introduced the inline form before the helper existed) has landed on dev.

1. Code Change Review

1.1 Core Logic Analysis

I diffed the current PR head against origin/dev with git diff origin/dev...HEAD --stat and confirmed the merge commit did not change the reviewable surface at all:

.../api/sink/multitablesink/MultiTableSinkWriter.java | 12 +++++-------
1 file changed, 5 insertions(+), 7 deletions(-)

This is byte-identical in scope to what I approved before the sync. The change itself, re-verified against the current head:

- index = (object.hashCode() & Integer.MAX_VALUE) % blockingQueues.size();
+ index = HashUtils.bucketIndex(object.hashCode(), blockingQueues.size());

I re-read HashUtils.bucketIndex(int, int) at the current head (seatunnel-common/.../utils/HashUtils.java:47-50):

public static int bucketIndex(int hash, int bucketCount) {
    checkBucketCount(bucketCount);
    return (hash & Integer.MAX_VALUE) % bucketCount;
}

Same conclusion as last time, re-verified rather than assumed: this is byte-for-byte the same computation as the inline expression, so routing is unchanged for every int input including Integer.MIN_VALUE. write() sits on the normal per-row hot path for any multi-table sink with a non-null primary key value — a mainline-path change, not a boundary path, which is why it earned this level of scrutiny both times.

Key findings on re-review:

  • The diff content is unchanged from my prior approval; only a merge-from-dev commit was added.
  • HashUtils.bucketIndex(int, int) implementation is unchanged at the current head — the equivalence proof still holds.
  • No new call sites, no new tests, no new files were introduced by the sync commit that touch this PR's subject matter.
  • The thread discussion (SEPURI-SAI-KRISHNA and I) correctly diagnosed the prior CI failures (minio/minio 404 from Docker Hub, a stale Maven artifact resolution blip, and S3FileConnectDryRunIT from #12242 still pointing at Docker Hub) as environmental/upstream, not caused by this one-line seatunnel-api change — the sync is the correct remedy for the ones already fixed on dev (#12287).

1.2 Compatibility Impact

Fully compatible — unchanged from my prior review. No config, API, protocol, or serialized/state format is touched. Routing output is identical for every hash/queue-count combination, so there is no restore-compatibility risk: a job upgraded across this change routes every primary key to the exact same physical writer queue it would have before, so in-flight/replayed rows after a checkpoint restore are not redistributed. The one behavioral delta (an unreachable bucketCount == 0 path now throws IllegalArgumentException instead of ArithmeticException) remains unreachable in practice, since the adjacent random-routing branch already calls random.nextInt(blockingQueues.size()) first and would fail before this line for an empty queue list.

1.3 Performance / Side-Effect Analysis

None, unchanged from prior review. HashUtils.bucketIndex is a guard check plus the same mask-and-modulo, no allocation, no locking, no I/O, called once per row.

1.4 Error Handling and Logging

No behavior change on the reachable path. No new logging, nothing swallowed.

2. Code Quality Assessment

2.1 Coding Standards

Unchanged from prior review: clean single-purpose diff, javadoc correctly updated to reference the helper instead of re-deriving the masking rationale at the call site, no dead imports.

2.2 Test Coverage and Test Stability

Unchanged from prior review, re-verified at the current head: MultiTableSinkWriterTest still pins the exact expected queue index for an Integer.MIN_VALUE-hashing primary key and for an ordinary negative hash, using the identical (hash & Integer.MAX_VALUE) % bucketCount formula the helper implements. These assert the concrete index, not just "no exception," so a routing regression introduced by this swap would fail them. No test files are touched by this PR (correctly — nothing about the test needs to change), and the sync commit did not modify or weaken any test. Stability rating: Stable.

2.3 Documentation Updates

N/A, unchanged — no user-facing docs reference this internal routing expression.

3. Architectural Soundness

3.1 Elegance of the Solution (Precise fix)

Unchanged assessment: this is the precise, minimal fix — removing the last inline copy of an idiom that already has a shared, tested, documented home, with proven behavior equivalence.

3.2 Maintainability

Improves it — one documented place now carries the masking rationale and the int/long-overload warning.

3.3 Extensibility

No impact — leaf call site.

3.4 Historical-Version Compatibility

No concern — proven byte-for-byte identical routing output, so no restore-compatibility break across the upgrade boundary. This was the specific angle I was asked to scrutinize hardest on re-review, and the merge-from-dev commit does not change that conclusion.

4. Issue Summary

# Issue Location Severity
1 (Already resolved) PR description previously misattributed part of the call-site migration history to #11937; this was corrected in the description after my first review. No remaining action. PR description Low

No new issues found on this re-review. No blockers.

5. Merge Recommendation

Conclusion: Ready to merge

  1. Blockers — none.
  2. Recommended fixes — none outstanding; the one non-blocking documentation nit from my first pass was already fixed by the author.

Overall assessment: Re-reviewed the entire current diff against origin/dev, not just the incremental commit, per the process for a NEED_REREVIEW pass. The only change since my prior approval is a merge from dev to absorb the minio/minio mirror fix for CI, and it introduces zero business-logic delta — the routing change remains a byte-for-byte equivalent swap to a shared helper, fully restore-compatible, with tests that pin the exact numeric outcome. Thanks again to SEPURI-SAI-KRISHNA for the careful, evidence-based back-and-forth on the CI triage in this thread — that made this re-check fast and confident rather than a guess.

CI: At review time, the fork's Build run for the new head (b319d412, run 34799734299) is still queued/in progress following the just-completed sync — no result to diagnose yet. Given the change is unchanged from my already-approved diff and the sync specifically targets the previously-diagnosed environmental failures, I'd expect a clean pass once it completes; no need to hold this up further on my end.

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Collaborator Author

CI is down to one job after the sync, and it is not reachable from this diff.

The sync cleared the MinIO family for good, as expected once #12302 landed. Failed legs went from seven before the sync, to four, to two legs of a single job now: engine-v2-it.

That job failed a different test each time. Attempt 1 was BackpressureSlowSinkIT.testCheckpointsKeepCompletingUnderSustainedBackpressure:247, attempt 2 was SplitClusterFaultToleranceIT.testStreamJobCancelResolvesWhenWorkerCrashesBeforeCancelAck:449, both Awaitility ConditionTimeout, both read from the JDK 8 leg. A different timeout each run points at runner load rather than one broken test, so I have stopped rerunning it.

It is also not specific to this PR. #12403 has engine-v2-it red on both legs too, and that change adds AES SQL functions in seatunnel-transforms-v2 plus docs, touching nothing under seatunnel-engine.

For completeness on the diff itself: (object.hashCode() & Integer.MAX_VALUE) % blockingQueues.size() becomes HashUtils.bucketIndex(object.hashCode(), blockingQueues.size()), and that method's body is return (hash & Integer.MAX_VALUE) % bucketCount;. Routing is identical for any queue count above zero, and the only difference is which exception an unreachable zero-queue path would throw.

@nzw921rx this has had @DanielLeens's approval since 09-14 and is green everywhere except that one job, if you are happy to take it.

@nzw921rx nzw921rx left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 LGTM

@nzw921rx

Copy link
Copy Markdown
Member

CI is down to one job after the sync, and it is not reachable from this diff.

The sync cleared the MinIO family for good, as expected once #12302 landed. Failed legs went from seven before the sync, to four, to two legs of a single job now: engine-v2-it.

That job failed a different test each time. Attempt 1 was BackpressureSlowSinkIT.testCheckpointsKeepCompletingUnderSustainedBackpressure:247, attempt 2 was SplitClusterFaultToleranceIT.testStreamJobCancelResolvesWhenWorkerCrashesBeforeCancelAck:449, both Awaitility ConditionTimeout, both read from the JDK 8 leg. A different timeout each run points at runner load rather than one broken test, so I have stopped rerunning it.

It is also not specific to this PR. #12403 has engine-v2-it red on both legs too, and that change adds AES SQL functions in seatunnel-transforms-v2 plus docs, touching nothing under seatunnel-engine.

For completeness on the diff itself: (object.hashCode() & Integer.MAX_VALUE) % blockingQueues.size() becomes HashUtils.bucketIndex(object.hashCode(), blockingQueues.size()), and that method's body is return (hash & Integer.MAX_VALUE) % bucketCount;. Routing is identical for any queue count above zero, and the only difference is which exception an unreachable zero-queue path would throw.

@nzw921rx this has had @DanielLeens's approval since 09-14 and is green everywhere except that one job, if you are happy to take it.

Please wait dev fixed, then rebase?

@nzw921rx

nzw921rx commented Sep 21, 2026 •

Copy link
Copy Markdown
Member

If you're willing, could you help fix it?💌

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Collaborator Author

Thanks for the approval.

Happy to rebase whenever you want, though it would be a no-op for this job today. #12290 is exactly 3 commits behind dev and all three are mine: #12349 and #12392 (RocketMQ) and #12410 (MQTT). None touch seatunnel-engine, so a sync cannot move engine-v2-it either way.

I also need to correct something I wrote above. I said the differing failures looked like runner load. That was wrong, and I found it by pulling the two job logs in full instead of reading the summaries again. Both legs are real, and both are already filed.

JDK 8, SplitClusterFaultToleranceIT.testStreamJobCancelResolvesWhenWorkerCrashesBeforeCancelAck

expected: <CANCELED> but was: <FAILED>
  at CoordinatorService.lambda$makeTasksFailed$25(CoordinatorService.java:2144)
  at CoordinatorService.makeTasksFailed(CoordinatorService.java:2129)
  at CoordinatorService.failedTaskOnMemberRemoved(CoordinatorService.java:2112)
  at CoordinatorService.memberRemoved(CoordinatorService.java:2155)

Not a timeout. FAILED is terminal, so the Awaitility condition could never have become true afterwards. This is #12353, which @tomatotomata reproduced on unmodified dev.

What the log does establish is the path: the member-removed handler assigned FAILED to the SplitEnumerator vertex, and SubPlan then logged Task ... Failed ... Begin to cancel other tasks in this pipeline. Two sibling vertices were already in terminal CANCELED at that instant and a third was still in the CheckTaskGroupIsExecutingOperation retry, so the cancel was well underway.

What it does not establish is the state of that vertex at the moment the member was removed, because vertex transitions are not logged at this level. That matters for #12311, which redirects a vertex only when it was already CANCELING; traced through SubPlan.addPhysicalVertexCallBack, that case does end as CANCELED, since the callback then takes the CANCELED branch and never sets the pipeline to FAILING. I also have a concern about whether #12377's approach survives that same callback, but that belongs on its own PR rather than here, so I will raise it there.

JDK 11, BackpressureSlowSinkIT.testCheckpointsKeepCompletingUnderSustainedBackpressure

Fails at line 193, the first-checkpoint gate, not the sustained-window assertion. The JobStatus.RUNNING check on the line above passed, so the job was healthy and simply never completed a checkpoint in 2 minutes against a 15s checkpoint.interval.

Dev matches the starvation preconditions #12313 describes: the conf sets row.num = 10000000 with split.num = 1, one split far above FakeSourceReader.MAX_ROWS_PER_POLL = 4096, which keeps splitInProgress true, skips the Thread.sleep(1000L) at FakeSourceReader.java:173, and lets pollNext re-enter synchronized (output.getCheckpointLock()) back to back. #12313 addresses that by sizing splits under the cap, #12316 in the engine.

So both failures have open fixes already and I am not going to add another PR in the same area.

On helping, what I have that those PRs do not is an independent reproduction of both from a change that touches one line of seatunnel-api. I am glad to attach that to whichever threads are useful and to review any of the four properly. If you would rather I pick something up directly, tell me which.

For this PR in the meantime, the diff is (object.hashCode() & Integer.MAX_VALUE) % blockingQueues.size() becoming HashUtils.bucketIndex(object.hashCode(), blockingQueues.size()), and neither failing test reaches MultiTableSinkWriter.

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Collaborator Author

Following up on the #12377 note above: I read that thread properly and @SEZ9 already raised exactly that point in a changes-requested review on 09-18, including the SubPlan.java:219 transition out of CANCELING and the regression test bypassing it. There is nothing for me to add there.

That also sharpens the answer to your question. Both engine failures already have fixes written. #12311 covers the cancellation one, and the #12353 thread has settled on it as the implementation rather than a separate PR. #12313 or #12316 covers the backpressure one. None of them is waiting on analysis. #12311 and #12313 have no approvals, and #12377 has had blocking review comments unanswered since 09-18. Review attention is what would move them, so that is where I would put any help you want from me.

@SEZ9

SEZ9 commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator

Thanks for digging into the full logs and for the correction — that is a much clearer picture than the runner-load theory, and I agree the two engine-v2-it failures are not something this diff can influence.

On your point about review attention: understood, that is where I can actually help. I will look at #12311 for the cancellation path first, since you say #12353 has settled on it as the implementation. One clarification I need from you: you wrote "#12313 or #12316 covers the backpressure one" — which of the two is the one to review? If both exist, tell me which is the intended fix so I do not split attention across them.

For this PR itself: since the 3 commits behind dev are yours and none touch seatunnel-engine, I agree a rebase today changes nothing. Let's leave #12290 as is until the engine fixes are merged, then rebase once and rerun engine-v2-it. My approval stands; I just want a green run on that job before merging.

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Collaborator Author

Thanks, and to answer directly: #12316 is the one to review for the backpressure failure. #12313 is worth reading first as context, but it is not the fix.

They are not two competing implementations, they are the same defect at two levels, both by @DanielLeens.

#12316 is the engine-side root cause. FakeSourceReader#pollNext emits rows while holding the checkpoint lock that SourceFlowLifeCycle#triggerBarrier needs. When a split exceeds MAX_ROWS_PER_POLL the reader sets splitInProgress and skips its own Thread.sleep(1000L) at FakeSourceReader.java:173, so it re-acquires the lock back to back with no deterministic release point and barrier injection starves. #12316 adds SourceCheckpointLockHandoff and replaces the Thread.sleep(0L) between polls with awaitInjectors(), so the reader yields when an injector is pending. That is in SourceFlowLifeCycle, so it applies to every source, not just FakeSource.

#12313 changes only the test: the config on dev is row.num = 10000000 with split.num = 1, one split far above the 4096 per-poll cap, and #12313 resizes it to row.num = 2000000 / split.num = 500 so every split is 4000 rows and the reader takes its real sleep between splits. Its Java diff is entirely javadoc, zero code lines. It makes this one test deterministic without touching the starvation itself, so if #12316 lands, #12313 becomes a test tweak rather than the fix.

One correction to my own earlier framing while I am here. I described the BackpressureSlowSinkIT failure as hitting the sustained-window assertion. It does not. In the run I read it failed at the first-checkpoint gate, completed >= 1 never becoming true inside 2 minutes while the job was healthy and RUNNING, which is the starvation above rather than a slow window.

A small note if you review #12313 as well: the comment it adds says the reader's sleep gives barrier injection a contention-free window "once per second". With 4000 rows per split and the sink at write_delay_ms = 2, so 500 rows per second, a split takes 8 seconds, so the window is once per 8 seconds. The conclusion still holds against a 15 second checkpoint.interval, but the stated margin is 8x larger than the real one, and that margin is the whole justification for the chosen numbers.

On this PR: agreed, leave it parked and rebase once the engine fixes land, then rerun engine-v2-it. Thanks for taking the cancellation path on #12311.

@DanielLeens

DanielLeens commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Thanks both for chasing this down so thoroughly — that's a lot more useful than another CI rerun would have been.

Confirming from my side: the head is still the same commit I approved on 09-14 (678c754a7bd6), so there's nothing new to re-review on the diff itself. It remains the one-line swap in MultiTableSinkWriter.write(SeaTunnelRow), and HashUtils.bucketIndex(int, int) really is just (hash & Integer.MAX_VALUE) % bucketCount, so routing is unchanged for any non-zero queue count as described.

On engine-v2-it: agreed that neither failure is reachable from this change — BackpressureSlowSinkIT and SplitClusterFaultToleranceIT are both under seatunnel-engine, and this PR only touches seatunnel-api. The distinction between #12313 (test-only, resizes the split so the reader's sleep is actually hit) and #12316 (the real engine-side fix, replacing the Thread.sleep(0L) gap with awaitInjectors() in SourceFlowLifeCycle) matches what I'd expect from the code each PR touches, and treating #12316 as the fix to review is the right call.

My approval stands. Agreed with the plan to leave this parked, rebase once #12311 and #12316 land, and get one clean engine-v2-it run before merging — no action needed from me until then.

@SEZ9

SEZ9 commented Sep 23, 2026

Copy link
Copy Markdown
Collaborator

Thanks @SEPURI-SAI-KRISHNA, that clears it up. Agreed that there is nothing further to add on the SubPlan.java:219 / CANCELING point since it was already raised in the changes-requested review, and that review attention rather than more analysis is what moves #12311, #12313 and #12377.

On the backpressure side, the split you laid out is the one I'll go with: #12316 is the fix to review (the awaitInjectors() handoff in SourceFlowLifeCycle applies to every source, not just FakeSource), and #12313 is a test-only resize from row.num = 10000000 / split.num = 1 to row.num = 2000000 / split.num = 500. Your correction that BackpressureSlowSinkIT fails at the first-checkpoint gate rather than the sustained window also matches the starvation reading. Good catch on the "once per second" comment in #12313 too — with 4000 rows per split at write_delay_ms = 2 it is once per 8 seconds, and since that margin is the justification for the numbers, it would be worth leaving that as a comment on #12313 so the javadoc gets fixed before it lands.

For this PR: the head is still 678c754a7bd6, so nothing on the diff changes and it stays parked. Concrete remaining asks:

  1. Rebase onto dev once [Fix][Zeta] Resolve a CANCELING vertex to CANCELED, not FAILED, when its worker is lost #12311 and [Fix][Zeta] Hand the source checkpoint lock to barrier injectors instead of racing them #12316 have merged.
  2. Rerun engine-v2-it and post the link to one clean run here.
  3. If either engine fix stalls, ping me on this thread and we can decide whether to merge on a targeted rerun instead of waiting.

I'll pick up the review of #12316 from here.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks @SEZ9 — that's a clean summary and matches what I read as well. Head here is still 678c754a7bd6, so there's nothing new on the diff side for me to re-check, and my approval from 09-14 still stands.

Agreed on the plan: leave this parked until #12311 and #12316 land, then rebase once and get one clean engine-v2-it run before merging. No action needed from me in the meantime — glad you're picking up the review on #12316.

@SEZ9

SEZ9 commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator

Thanks @SEPURI-SAI-KRISHNA — one thing I didn't pick up in my earlier replies: the "once per second" wording in the javadoc on the test-only resize is my mistake. With 4000 rows per split and the sink at 500 rows per second, the contention-free window is once per 8 seconds, not once per second. The conclusion against the 15 second checkpoint interval still holds, but the stated margin is wrong, so I'll correct that javadoc on my PR myself rather than leave it as is.

Nothing else changes here: this PR stays parked at 678c754a7bd6 until the engine fixes land, then one rebase and a clean engine-v2-it run before merging.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks for flagging the javadoc correction on your side.

Confirming from my end: head here is still 678c754a7bd6, unchanged since my 09-14 approval, so there's nothing new on this PR's own diff to re-review. The routing swap is still (object.hashCode() & Integer.MAX_VALUE) % blockingQueues.size() becoming HashUtils.bucketIndex(object.hashCode(), blockingQueues.size()), and bucketIndex's body is exactly that same expression, so bucket assignment is byte-for-byte identical for every hash and queue count on this diff — no redistribution risk for existing multi-table jobs across the upgrade, and nothing in the engine-v2-it failures traces back to MultiTableSinkWriter.

The "once per second" vs "once per 8 seconds" margin correction is scoped to #12313's javadoc, not to anything in this PR, so it doesn't change my assessment here.

My approval stands. Plan unchanged: leave #12290 parked at 678c754a7bd6 until #12311 and #12316 land, then one rebase and a clean engine-v2-it run before merging.

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Collaborator Author

Refreshed this branch onto current dev. The head was 54 commits behind and its CI evidence dated from September 21, so the red badge here was stale as well as, on the evidence below, unrelated to this change.

The diff is untouched by the refresh: one file, MultiTableSinkWriter.java, +5/-7. No commit landed on dev touching that file since the merge base ea3df166, so the merge was conflict free and what you approved is what is here.

Both failures on the old run are pre-existing, and both already have open issues.

leg failing test tracked by
engine-v2-it (8, ubuntu-latest) SplitClusterFaultToleranceIT.testStreamJobCancelResolvesWhenWorkerCrashesBeforeCancelAck #12311, #12353
engine-v2-it (11, ubuntu-latest) BackpressureSlowSinkIT.testCheckpointsKeepCompletingUnderSustainedBackpressure #12313

Neither is a whole-suite failure. JDK 8 finished Tests run: 204, Failures: 0, Errors: 1, Skipped: 7; JDK 11 finished Tests run: 196, Failures: 0, Errors: 1, Skipped: 8. Zero assertion failures on either leg, one Awaitility ConditionTimeoutException each.

Where the backpressure test died matters. Its trace is ConditionTimeoutException ... expected: <true> but was: <false> within 2 minutes at BackpressureSlowSinkIT.java:184, caused by an AssertionFailedError at line 193. Line 193 is Assertions.assertTrue(getLong(counts, "completed") >= 1L), inside the atMost(2, TimeUnit.MINUTES) block whose comment reads "Wait for the first checkpoint so the sampling loop below always starts from a well-defined baseline instead of racing the job's own startup". So the job never completed its first checkpoint, and the test died at its startup baseline before the backpressure loop ran at all. That is checkpoint-barrier startup, which is what #12313 is about, and it is upstream of anything a sink writer routes.

Neither test can reach the changed code. BackpressureSlowSinkIT runs stream_fast_fakesource_to_slow_inmemory_backpressure.conf: parallelism = 1, one FakeSource, one InMemory sink, no table list. There is no multi-table routing to exercise and no second bucket to route to; the only "bucket" in that test is bucket_ms, a metrics window unrelated to HashUtils.bucketIndex. SplitClusterFaultToleranceIT is a Zeta cancellation test and does not touch seatunnel-api sink routing.

Both fail on unmodified dev. @SEZ9 measured this on #12353: SplitClusterFaultToleranceIT failed 13 of 17 real executions across three code bases with no branch correlation, including a plain dev run, and every completed dev Build run since the test landed has had a red engine-v2-it leg. That comment also records the pair trading places, BackpressureSlowSinkIT failing on reruns where SplitClusterFaultToleranceIT passed. That is the pattern this PR's old run shows.

Since #12311 and #12313 are both open, a rerun here will likely land on one of them again rather than come back green, so I would rather not keep rerunning. @nzw921rx @davidzollo if you agree the reds are unrelated, this is ready from my side. If you would rather wait for #12311 and #12313 to land first, say so and I will park it.

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Collaborator Author

Correcting my previous comment. The rerun on 4d64a4d8 has finished and it is red again, but with three different failures, none of them the two I named earlier. engine-v2-it passed this time on both JDK legs, so #12311 and #12313 are not what is holding this PR now.

leg failure status
transform-v2-it-part-1 (11) TestFilterRowKindIT.testFilterRowKindMultiTable #12116
iceberg-connector-it (8) DependencyResolutionException, no test ran infrastructure
jdbc-connectors-it-part-7 (11) MetalakeIT.testMetalake, fails in startUp not currently tracked

Run 36725638109: 80 jobs successful, 3 failed, 11 skipped. engine-v2-it is green on both JDK 8 and JDK 11, which is what rules out the two I named before.

transform-v2-it-part-1 is the one that deserves scrutiny here, because the failing test has "MultiTable" in the name and this PR touches multi-table sink routing. It is not this PR, and the reason is that the change cannot alter routing at all:

- index = (object.hashCode() & Integer.MAX_VALUE) % blockingQueues.size();
+ index = HashUtils.bucketIndex(object.hashCode(), blockingQueues.size());

HashUtils.bucketIndex(int, int) is checkBucketCount(bucketCount); return (hash & Integer.MAX_VALUE) % bucketCount;. For any bucket count of 1 or more the two expressions are the same arithmetic, so every row routes to the same queue before and after. The only behavioural addition is the guard rejecting a bucket count of zero or less, which a running job cannot reach.

The failure itself is expected: <0> but was: <1> at TestFilterRowKindIT.java:53, an exit-code assertion on a non-Zeta container leg. #12116 records that exact signature for that exact test, and attributes it to AssertSinkWriter using static JVM-wide counters evaluated per subtask close(), on Flink legs only. Suite totals were 219 tests, 1 failure, 0 errors.

iceberg-connector-it never reached a test. Maven failed dependency resolution, so there is nothing in it to attribute.

MetalakeIT fails during fixture setup rather than in the test body:

org.awaitility.core.ConditionTimeoutException: ... expected: <0> but was: <7> within 3 minutes
    at MetalakeIT.startUp(MetalakeIT.java:158)

I could not find an open issue for it. I am deliberately not filing one on a single observation, since one occurrence is an anecdote; if it shows up again I will sample the nightly runs properly and file it with evidence.

So the position is unchanged in substance: this PR's diff is one file, +5/-7, provably routing-neutral, and nothing red on it is attributable to it. What has changed is which flakes happened to land, which is itself the point. Three reruns have now produced three different sets of unrelated failures.

@nzw921rx @davidzollo I would rather not keep rerunning and burning CI on this. If you are satisfied the above is unrelated, this is ready from my side; if you would prefer to wait for #12116 and the rest to clear, say so and I will park it until then.

@SEZ9

SEZ9 commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the rebase and for the follow-up correction, @SEPURI-SAI-KRISHNA.

On the diff side nothing changes for me: the refresh onto dev from merge base ea3df166 left MultiTableSinkWriter.java as the single touched file, and your reading of HashUtils.bucketIndex is right — (hash & Integer.MAX_VALUE) % bucketCount is the same arithmetic as the old inline expression for any positive bucket count, so routing is unchanged and the only new behaviour is the guard on a non-positive count. That is what was approved and it is still what is here.

On run 36725638109 for 4d64a4d8, I agree with the triage as you've laid it out:

Two concrete asks before I merge:

  1. Please re-trigger the failed legs on 4d64a4d8 (no new commit needed). I'd like to see iceberg-connector-it (8) actually resolve its dependencies, and to learn whether MetalakeIT recurs or was a one-off.
  2. If MetalakeIT.startUp fails again on the rerun, drop the trace here so there is a second data point to file against; if it passes, note that too and I'll consider the CI picture settled.

Nothing else outstanding from my side.

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Collaborator Author

Rerun done, @SEZ9, and it is green. No new commit, same head 4d64a4d8, failed-jobs-only rerun of run 36725638109.

Attempt 2: 83 jobs successful, 11 skipped, 0 failed. The upstream Build check is now passing.

The three legs you asked about:

leg attempt 1 attempt 2
iceberg-connector-it (8) DependencyResolutionException, no test ran pass, dependencies resolved
jdbc-connectors-it-part-7 (11) MetalakeIT error in startUp pass
transform-v2-it-part-1 (11) TestFilterRowKindIT, tracked by #12116 pass

On MetalakeIT specifically, since that was the one worth a second data point. It did not recur, and the timing says why:

attempt 1:  Tests run: 2, Failures: 0, Errors: 1, Time elapsed: 1,853.228 s
            testMetalake  Time elapsed: 1,219.394 s  <<< ERROR!
            ConditionTimeoutException ... expected: <0> but was: <7> within 3 minutes
            at MetalakeIT.startUp(MetalakeIT.java:158)

attempt 2:  Tests run: 2, Failures: 0, Errors: 0, Time elapsed: 94.562 s

94 seconds against 1,853. The failure was the fixture never coming up inside its three-minute window on a slow runner, not anything in the test or in this change. One occurrence with no recurrence, so I am not filing it, as agreed. If it shows up again I will sample the nightlies and open it with a proper sample rather than two anecdotes.

Nothing else outstanding from my side.

@nzw921rx
nzw921rx added this pull request to the merge queue Oct 2, 2026
@nzw921rx

nzw921rx commented Oct 2, 2026

Copy link
Copy Markdown
Member

Thank you for your effort, he has indeed gone through a long CI cycle!

Merged via the queue into apache:dev with commit 6d9667a Oct 2, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature][API] Add a shared non-negative modulo helper for hash-based routing

4 participants