Skip to content

[Fix][Connector-V2][Kafka] Isolate transactional IDs by sink writer - #13060

Open
zephyr45 wants to merge 17 commits into
apache:devfrom
zephyr45:fix/kafka-transaction-ids-13044
Open

zephyr45 wants to merge 17 commits into
apache:devfrom
zephyr45:fix/kafka-transaction-ids-13044

Conversation

@zephyr45

@zephyr45 zephyr45 commented Oct 29, 2026 •

Copy link
Copy Markdown

Purpose of this pull request

Yes, I am contributing to Apache SeaTunnel. Fixes #13044. Thanks to @nzw921rx for the reproduction and root-cause investigation.

Parallel Kafka sink writers using EXACTLY_ONCE and one configured transaction_prefix previously generated the same <prefix>-<checkpoint> IDs and fenced one another. This PR gives each active writer a disjoint transactional namespace with a contiguous sequence:

<transaction_prefix>-<opaque-writer-namespace>-<sequence>

Current dev already flushes and propagates asynchronous Kafka send failures. This PR removes the transaction-ID collision that triggered fencing. The silent lossy FINISHED comparison was reproduced separately on released SeaTunnel 2.3.13.

Current status

The head is 32fb52215ab395d604f1e9120f85afe40246ada8: 117dc411 plus a docs-only change that limits recovery and rescaling to Zeta and Flink in the EN/ZH incompatible-change notes, as zhangshenghang asked. Fork Build 45184080151 is fully green on 32fb5221 (88 passed, 9 skipped; six jobs passed on re-run). The branch was last synced with dev on 2026-11-18 (89f91a89), which includes the IRIS (#13285) and SFTP (#13203) fixture fixes. Fork Build 44311890713 is fully green on 117dc411, including kafka-connector-it and all unit tests on JDK 11/17 (connector-file-local-it (17) passed on re-run after an earlier 2-hour timeout that also affects dev). Since 7c272c5a, this PR's only own code change is cf52689e, which removes the unused multi-table stable-index override and its test. DanielLeens approved 117dc411 on 2026-11-20. Pending: committer approval of the PR signal run (the Build check appears after it), re-reviews from SEZ9 and nzw921rx, and committer approval of the PR.

Review findings status (SEZ9, F1–F7) at 32fb5221

Finding Status Commit Coverage
F1: Flink contiguous scale-down restore Fixed: modulo owner check removed; every assigned state is fenced 585f69b7 KafkaSinkWriterTest#shouldFenceContiguouslyAssignedFlinkNamespacesAfterScaleDown, #shouldFenceEveryAssignedWriterNamespaceAfterScaleDown
F2: scale-down with transaction_prefix unset Fixed: each state is parsed with its own saved prefix 585f69b7 #shouldRestoreMixedGeneratedPrefixesAfterScaleDown
F3: stateless writer starts at sequence 1 Fixed: sequence 1 is fenced before the first send; a later abandoned sequence is bounded by transaction.timeout.ms (documented) d8143b58, b9ed7c12 #shouldReuseGeneratedPrefixWhenStatelessWriterRetries, #shouldNotWalkStatelessWriterTransactionHistory; EN/ZH Kafka.md Semantics
F4: Spark task retry identity Fixed: Kafka uses getStableSubtaskIndex() (Spark partition ID), so a retry fences the same namespace 9e4aad72 KafkaIT#shouldFenceAbandonedAttemptWithStableIndex, SparkSinkTest/SparkDataWriterFactoryTest#shouldSeparateTaskIdentityFromStablePartitionAcrossRetriesAndEpochs
F5/F6: legacy shared-namespace probing Left as is: legacy migration cost, repeated on each retried restore — Deferred to #13298 (agreed by SEZ9; behaviour noted there)
F7: docs Fixed: option row shows <prefix>-<writer>-<sequence>; rescaling scoped to Zeta/Flink, also in the incompatible-change notes 7887e909, 9e4aad72, 32fb5221 EN/ZH Kafka.md and incompatible-changes.md

Namespace and recovery contract

  • KafkaSink creates the job prefix and generation token once and serializes them with the execution graph. Fresh writers use g<generation>w<index>.
  • A writer-specific restore advances its assigned lineage to <base>_r<revision>w<current-index>. The revision is checkpointed in the transaction ID and is independent of engine-local checkpoint counters. Retrying one recovery point derives the same output namespace; a later recovery advances the saved revision.
  • Every assigned old namespace is cleaned from its saved sequence plus one, preserving the pending transaction captured by the restored checkpoint. Stateful recovery also cleans the deterministic output namespace before new work begins.
  • Each state is parsed relative to its own saved job prefix, preserving mixed historical generated prefixes. The connector consumes engine-assigned state and assumes neither Zeta modulo ownership nor Flink contiguous ownership.
  • Spark 2.4 and 3.3 retain their historical task-attempt index through getIndexOfSubtask(). The new default getStableSubtaskIndex() delegates to the existing index; Spark overrides it with partitionId, which Kafka uses for retry-stable namespaces. Other sinks, including Doris and SelectDB, retain their historical identifiers.

Documented limitations and follow-up

F3 — no retained state: A fresh writer opens and fences sequence one without scanning namespace history. A later abandoned transaction absent from retained checkpoint state cannot be identified through a checkpoint counter and may block read_committed consumers until Kafka's transaction.timeout.ms expires. This boundary is documented next to the recovery semantics in EN and ZH. Timeout configuration must account for this possible consumer delay as well as the job's normal transaction/checkpoint duration.

F5/F6 — legacy migration cost: abortRestoredTransactions deduplicates prefixes within each writer only. This head adds neither cross-writer ownership of a legacy shared prefix nor a new hard probe-chain bound. Concurrent restoring writers can bump producer epochs and extend one another's scans, amplifying first-upgrade startup work roughly quadratically. This remains a legacy migration cost, repeated on each retried restore, and a separate optimization follow-up. Safe coordination requires per-prefix ownership, owner failover and mixed-prefix handling; choosing subtask zero alone would be incorrect.

For Spark exactly-once Kafka sinks, keep spark.speculation=false (the Spark default), because concurrent attempts for one partition share a writer identity. The stable partition index is not a unique streaming-batch identifier.

Compatibility and migration

Configuration keys/defaults, existing API/SPI methods and KafkaSinkState serialization are preserved. The context API adds a default method. There is no new runtime dependency; Spark tests use a test-scoped dependency on the existing Doris connector.

Transactional-ID shape changes, and the new sink-level generation fields make an execution graph serialized by an older version incompatible. For an upgrade:

  1. Stop the old job attempt.
  2. Build a new execution graph from the configuration with the upgraded SeaTunnel version.
  3. Restore retained checkpoint or savepoint state.
  4. Update transactional-ID ACLs/monitoring for the new shape and retain legacy-ID access during recovery.
  5. Keep a distinct configured prefix for every concurrent job.

Earlier validation on 7c272c5

The November 15–16 Java 11 validation passed 583 JUnit tests, with zero failures, errors or skips:

Suite Passed
API 411
Kafka connector unit tests 152
Spark 2.4 / 3.3 adapter suites 5
Flink writer adapter regressions 4
Kafka broker regressions 3
Packaged Kafka engine E2E 8

Coverage includes contiguous state assignment, mixed prefixes, repeated 3 -> 4 -> 3 -> 4 -> 3 recovery regression, bounded fresh initialization, restored transaction fencing, and Spark retries with different task IDs sharing a stable partition index. Engine E2E covers parallel batch jobs on Flink 1.13/1.15/1.18/1.20, Spark 2.4/3.3 and Zeta, plus Zeta streaming restore from parallelism 3 to 2. Output checks use read_committed, exact expected sets and exact counts.

Separate real Spark 2.4.6 and 3.3.0 Structured Streaming runs into Doris with 2PC committed two consecutive batches and verified the exact stored rows through SQL. The original b9ed7c1297d9 factories, loaded as controls against the same clean server, failed on batch two with Label Already Exists; the current factories passed. Loaded class locations and control hashes were recorded.

The affected reactor and dependencies passed install -DskipTests across 75 modules, including formatting/package checks; git diff --check passed. The fork Build for 7c272c5 completed with 85 successful jobs, 11 skipped and no failures/cancellations; only the two failed jobs from attempt 1 were rerun.

Runtime images were the repository-pinned confluentinc/cp-kafka:7.0.9 and apache/doris:doris-all-in-one-2.1.0 (reporting doris-2.1.0-rc11-91efb6a43d). These results do not certify every server version. Real Flink savepoint/rescale execution and SelectDB runtime remain untested; Flink recovery has model/adapter coverage. See the current-head validation report in the discussion and original Spark regression correction.

Check list

  • Documentation and both incompatible-change pages are updated.
  • Kafka E2E coverage is updated.
  • No new runtime JAR dependency or connector registration is introduced; new-runtime-JAR notices, plugin mapping, distribution, CI-label and plugin-config additions are not applicable.

@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.

Thanks for addressing parallel Kafka writer fencing! I read the full ten-file diff and traced state/commit flow through the Zeta and Flink adapters. Writer-specific IDs fix the normal shared-prefix collision. One recovery ownership boundary still needs a fix or an explicit rejection before this can safely claim the same exactly-once behavior after state redistribution.

What Problem Does This PR Solve?

User pain point: Parallel exactly-once sink writers configured with the same transaction prefix create the same checkpoint transaction ID and fence each other.

Fix approach: Append the writer subtask index to the transaction namespace, preserve the checkpointed job prefix, and fence legacy shared IDs when migrating old state.

One-sentence summary: Writers 0 and 1 now use orders-0-5 and orders-1-5 instead of both using orders-5. But if old writer 2 disappears after rescaling, its uncommitted orders-2-5 is not fenced by either surviving writer.

Review report time: 2026-10-29T12:58:12.646015-04:00. Current head 322a6c75ca4b595659fb7c4d59813b36f1114f73; base dev at 5598ed7f3a88602032a18b617cb21c688aacf965. Checks: No current-head check reported. Check references: none. Compare: ahead, ahead 1, behind 0; merge state blocked / BLOCKED.

1. Code Change Review

1.1 Core Logic Analysis

KafkaSinkWriter.java:76-103 derives writerTransactionPrefix after restoring the common job prefix. snapshotState starts the next transaction with that writer prefix; KafkaTransactionSender separates the saved prefix from its cleanup prefix. Same-index restore fences the current writer's future IDs; a legacy shared ID is detected by stripping the last checkpoint suffix and fenced before migration. KafkaSinkState and serializers are unchanged. prepareCommit/flush/asynchronous error and KafkaSinkCommitter contracts remain unchanged. Crucially, the restore constructor reads only kafkaStates.get(0), and for a new-format state whose saved writer differs it neither fences that saved namespace nor validates ownership. FlinkSink.createWriter:84-90 passes a potentially redistributed list of operator states; SinkFlowLifeCycle.restoreState:380-409 also flattens assigned states before restoreWriter. The new test shouldNotFenceAnotherWriterWhenRestoringItsState explicitly accepts state from writer 1 on writer 2 while leaving namespace 1 untouched, which exposes the ownership gap rather than proving safe redistribution.

Before:

generateTransactionId(transactionPrefix, checkpointId);
// parallel writers with configured prefix collide

After:

writerTransactionPrefix = transactionPrefix + "-" + subtaskIndex;
generateTransactionId(writerTransactionPrefix, checkpointId);
// restore: fence legacy prefix if detected, then only the current writer prefix
// restored new-format namespaces from other indices are not covered

Key Findings

  • Normal parallel writers receive distinct IDs for every checkpoint, fixing the reported producer-fencing bug.
  • Same-index restart and legacy namespace migration are covered by real writer/sender unit paths.
  • State serialization is unchanged, but transaction-ID identity/ACL behavior intentionally changes.
  • State reassignment or scale-down can leave old writer namespaces with unfinished transactions.
  • The new batch IT has two nonempty source partitions and exact set/count checks, while the changed restore IT still has only one source partition.

Complete runtime path

SinkFactory -> KafkaSink.createWriter -> KafkaSinkWriter(context subtask index)
 -> writer prefix -> KafkaTransactionSender.beginTransaction -> Kafka producer sends
Checkpoint prepare -> flush + async failure check -> KafkaCommitInfo(actual transaction ID/PID/epoch)
 -> snapshot KafkaSinkState(common prefix, actual ID, checkpoint) -> next writer-specific ID
 -> KafkaSinkCommitter resumes and commits the captured transaction
Recovery -> engine/adaptor assigns state list -> KafkaSink.restoreWriter -> constructor
 -> get(0) common prefix/checkpoint -> legacy-prefix cleanup when applicable
 -> cleanup CURRENT index only -> begin current next transaction
Scale-down/reassignment -> saved namespace of a retired/different writer is skipped
 -> old broker transaction can remain open and is not fenced before replay

The effects depend on the entry and preconditions above. Recovery, batching and connector lifecycle retain their existing contracts unless explicitly described here; source inspection is not runtime proof.

1.2 Compatibility Impact

Partially incompatible. API signatures and state serialization remain compatible, including legacy shared IDs. Kafka transactional IDs change shape, affecting ACLs and monitoring; en/zh migration entries describe retaining access to saved legacy IDs and stopping the old attempt. Existing configuration keys/defaults are unchanged. State redistribution is not safely handled by current cleanup (Issue 1); stopping the old attempt does not itself abort every broker-side unfinished transaction.

1.3 Performance / Side-Effect Analysis

Distinct namespaces avoid cross-writer fencing on normal checkpoints. Cleanup still creates/closes temporary producers and probes until an unused ID, now once per writer plus legacy migration. No new per-row object, lock or executor is introduced. Broker transaction/network cleanup remains failure-sensitive. A retired unfenced namespace can hold read_committed progress until transaction timeout; an old producer is also not fenced by the new attempt. The fix must coordinate cleanup ownership, rather than have live writers blindly fence each other.

1.4 Error Handling and Logging

Existing async send failures and non-started transactions still fail prepareCommit; causes and transaction IDs remain available without logging credentials. The new constructor accepts mismatched/multiple restored writer states without an error, although it cannot establish their cleanup ownership. No fallback should silently claim exactly-once for that case.

Issue 1: Resolve restored namespace ownership before starting redistributed writers

  • Location: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:90-103
  • Problem description: Only kafkaStates.get(0) is examined, and a saved new-format prefix different from the current subtask prefix is deliberately skipped. Flink can redistribute sink operator state on rescaling; for example, after 3->2 parallelism an assigned list can include old writer 2, while the surviving writers only clean prefixes 0 and 1. Its unfinished checkpoint+1 transaction remains open. The new mismatched-index unit test confirms this behavior but does not model the broker transaction or retired writer.
  • Potential risk: Recovery can leave read_committed consumers blocked behind old uncommitted records until broker timeout, and the previous producer namespace is not fenced before replay. This breaks the cleanup assumption required for exactly-once failover under the supported stateful adapter path.
  • Best improvement / root-cause and location assessment: Define cleanup ownership for every restored writer namespace and complete that fencing before any new attempt can open overlapping IDs; cover multi-state/scale-down and reassigned-index cases with actual unfinished broker transactions. Do not simply fence every sibling ID concurrently, which can fence a new live writer. The smallest safe alternative is to fail fast on unsupported multiple/mismatched new-format states, document the rescaling restriction in both languages and require a supported migration path, instead of silently accepting them. Preserve the valid same-index and legacy migration cases.
  • Severity: High; blocking.
  • Raised by another reviewer: No.

Issue 2: Document the two distinct transaction-prefix lifetimes

  • Location: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaTransactionSender.java:53-54
  • Problem description: The new transactionIdPrefix field and package-private three-argument constructor establish a protocol distinction from transactionPrefix, but do not explain saved common-prefix versus writer-cleanup-prefix ownership. KafkaSinkWriter.writerTransactionPrefix likewise has only a construction-site comment.
  • Potential risk: A later maintainer can accidentally persist the expanded prefix or use the common prefix for cleanup, reintroducing fencing/namespace drift. These are nontrivial protocol fields and require the project's core-field documentation.
  • Best improvement / root-cause and location assessment: Add concise field/constructor Javadocs explaining which prefix is checkpointed, which identifies the current writer, legacy compatibility and the state-ownership constraints from Issue 1. No public API or extra abstraction is needed.
  • Severity: Medium; non-blocking.
  • Raised by another reviewer: No.

2. Code Quality Assessment

2.1 Coding Standards

The complete changed-file set, imports and removed lines were inspected. Existing formatting/imports/ASF headers and connector boundaries are preserved. New protocol-prefix documentation needs the focused non-blocking Issue 2. The new writer test class is justified by exercising the writer constructor/state lifecycle separately from the existing sender tests.

2.2 Test Coverage and Test Stability

Stability rating: Stable. KafkaSinkWriterTest.java:40-232 executes the real writer/sender with only external producer construction mocked, closes mock scope/writers and uses fixed state/IDs with synchronous assertions. The new KafkaIT.java:2291-2331 preloads two partitions with distinct values, waits for producer acknowledgements and job completion, then checks read_committed set and count; topics are uniquely named and registered for cleanup. No new hard sleep or fixed host port is added. Existing streaming restore now sets parallelism=2, but its source topic still has one partition, so only one writer carries source data. Neither fixture covers reassigned/multiple state ownership or scale-down; Issue 1 requests that regression. The production recovery counterexample is independent of test stability.

Local verification results: exact-head git fetch and isolated review branch seatunnel-review-13060 created; full git diff 5598ed7f3a88602032a18b617cb21c688aacf965...322a6c75ca4b595659fb7c4d59813b36f1114f73 read (10 files); git diff --check passed; git show, rg and line-numbered source/caller/config/test reads used for the trace above. GitHub changed filenames are reconciled with this local diff before publication. No local compile, Maven verify, unit/IT/E2E, Docker, service or UI execution occurred, as required for this review task. No build/deployment artifact was reused; engine-ui was not built.

2.3 Documentation Updates

Both Kafka guides and incompatible-changes entries consistently explain the ID shape, unique per-job configured prefix, legacy ACL access and stopped old attempt. Add the supported redistribution/rescaling contract after resolving Issue 1; do not claim unchanged state serialization is sufficient evidence of safe runtime recovery.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix.

3.2 Maintainability

Best change-location assessment: The writer identity belongs in the Kafka transaction namespace, and the normal-path change is appropriately local. Recovery ownership must also be explicit at the state-assignment boundary. A coordinated cleanup barrier is the broad robust solution; a clear rejection of currently unsupported state shapes is the smaller safe option.

3.3 Extensibility

Keep existing connector identities and contracts. Reuse the current boundary and regression fixtures; no shared-framework redesign or unrelated dependency is needed for the behavior reviewed here.

3.4 Historical-Version Compatibility

API signatures and state serialization remain compatible, including legacy shared IDs. Kafka transactional IDs change shape, affecting ACLs and monitoring; en/zh migration entries describe retaining access to saved legacy IDs and stopping the old attempt. Existing configuration keys/defaults are unchanged. State redistribution is not safely handled by current cleanup (Issue 1); stopping the old attempt does not itself abort every broker-side unfinished transaction. This review does not claim an executed upgrade/recovery validation.

4. Issue Summary

Number Issue Location Severity
1 Resolve restored namespace ownership before starting redistributed writers seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:90-103 High, blocking
2 Document the two distinct transaction-prefix lifetimes seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaTransactionSender.java:53-54 Medium, non-blocking

Completeness check: full diff and affected entry/call chain, failure/resource paths, compatibility, tests and stability, bilingual docs, configuration/registration and current CI/merge gates were inspected before enumerating these findings. No additional finding is reserved for a later round on this version.

Community review reconciliation: No earlier reviewer or discussion finding was present in the collected metadata. This is the first complete review on this head; no issue is duplicated from another reviewer.

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers — must be fixed: Issue 1: Resolve restored namespace ownership before starting redistributed writers; Required current-head CI and effective maintainer review/merge gates must be satisfied.
  2. Recommended fixes — non-blocking: Issue 2: Document the two distinct transaction-prefix lifetimes

Overall assessment: The writer identity belongs in the Kafka transaction namespace, and the normal-path change is appropriately local. Recovery ownership must also be explicit at the state-assignment boundary. A coordinated cleanup barrier is the broad robust solution; a clear rejection of currently unsupported state shapes is the smaller safe option. Current head 322a6c75ca4b595659fb7c4d59813b36f1114f73; base dev at 5598ed7f3a88602032a18b617cb21c688aacf965. Checks: No current-head check reported. Check references: none. Compare: ahead, ahead 1, behind 0; merge state blocked / BLOCKED. Behind/diverged status alone is synchronization metadata and does not justify a sync-and-rerun instruction. Daniel has READ permission: this COMMENT is a technical conclusion, not an effective APPROVED event or dismissal of historical requested changes. A write-capable maintainer owns final approval/dismissal where required. No current-head aggregate runtime Build was attached at collection. That does not establish disabled fork Actions or a failed test. Source inspection found Issue 1 independently of CI; neither green unrelated checks nor a generic upstream sync would resolve that ownership gap. Thanks again; happy to help with the focused next revision.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks again. The CI fact cited previously has changed: this exact head now has a successful Build, replacing the missing-runtime-check snapshot in my source review. That clears the CI observation, but not Issue 1 about redistributed Kafka transaction-namespace ownership during recovery/rescale, or the documented prefix-lifetime follow-up. Those source requests still apply; green CI does not establish the omitted ownership invariant. No drift-only sync or unrelated CI patch is requested.

Snapshot 2026-10-30T03:23:54.080283+00:00: head 322a6c75ca4b595659fb7c4d59813b36f1114f73; Label PRs when reviewed = SUCCESS; Signal pull request update = SUCCESS; Build = SUCCESS.

Base dev; comparison diverged, ahead 1, behind 3; merge state blocked. Behind/diverged alone is recorded metadata and does not add a sync request. This is an unchanged-head discussion/CI clarification, not a new complete source review, an effective approval or a dismissal of historical requested changes.

@zephyr45

Copy link
Copy Markdown
Author

Thanks @DanielLeens — both review points are addressed in 10e618cb.

  • Recovery now inspects every assigned KafkaSinkState, derives and deduplicates each saved transaction namespace, and fences all unfinished transactions before opening new work. For current-format state it validates the engine's modulo assignment (restoredWriterIndex % currentParallelism == currentWriterIndex) before any Kafka producer is initialized, so a live writer cannot fence a sibling. Legacy shared-prefix checkpoints remain supported.
  • The writer unit coverage now includes a 3-to-2 scale-down (old writers 0 and 2 assigned to new writer 0) and fail-fast rejection of an incorrectly assigned namespace. The streaming Zeta E2E now restores from parallelism 3 to 2, sends data through all three source partitions, retains a single-partition sink, and passed against Kafka 7.0.9.
  • Added focused Javadocs for the checkpointed job prefix and writer-owned transaction namespace.

Post-revision validation: all 139 Kafka connector unit tests passed; both affected real-broker E2Es passed; the 16-module affected dependency reactor packaged successfully; Spotless, git diff --check, and the English/Chinese documentation checks passed.

For @SEZ9's failure-status question, the PR description now records that current dev already propagates asynchronous Kafka send/fencing failures at the next write or prepareCommit, causing task/checkpoint failure rather than a silently successful lossy commit; engine retry policy determines final job status. That propagation predates this PR. The silent FINISHED behavior was reproduced on released 2.3.13.

@SEZ9 SEZ9 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for working on this. I reviewed the latest head 10e618cb3815.

What this PR fixes

  • User pain: With semantics = EXACTLY_ONCE and a shared transaction_prefix, parallel Kafka sink writers all open <prefix>-<checkpoint> and fence each other with ProducerFencedException (#13044), so any exactly-once Kafka sink with parallelism > 1 is unusable.
  • Fix approach: KafkaSinkWriter derives a per-writer namespace <prefix>-<subtask> (KafkaSinkWriter.java:84) and passes it alongside the persisted job prefix into a new two-prefix KafkaTransactionSender constructor (KafkaTransactionSender.java:81-86). On restore, abortRestoredTransactions parses each saved transaction ID back to its namespace, checks restoredWriterIndex % parallelism == currentWriterIndex, and fences every assigned namespace (including the legacy shared one) via abortTransaction(prefix, checkpointId) before beginning a new transaction.
  • One-line summary: The core collision fix is correct and well-tested on Zeta, but the restore path hard-codes Zeta's modulo redistribution (Flink's contiguous ListState split will throw at KafkaSinkWriter.java:259 on scale-down), and the new single-prefix guard in restoreState breaks scale-down for jobs that omit transaction_prefix (each writer draws its own random SeaTunnel%04d), so this is not mergeable as-is.

Runtime chain I rechecked

KafkaSink.restoreWriter(context, states) -> new KafkaSinkWriter(...)  KafkaSink.java:64-66
  KafkaSinkWriter.<init>  KafkaSinkWriter.java:67
    transactionPrefix = config TRANSACTION_PREFIX or random "SeaTunnel%04d"  KafkaSinkWriter.java:75-80
    restoreState(states)  KafkaSinkWriter.java:82 -> :177
      transactionPrefix = states[0].getTransactionIdPrefix(); lastCheckpointId = max(checkpointId); throws IllegalStateException on mixed prefixes  KafkaSinkWriter.java:177-190
    writerTransactionPrefix = transactionPrefix + "-" + context.getIndexOfSubtask()  KafkaSinkWriter.java:84
    new KafkaTransactionSender<>(transactionPrefix, writerTransactionPrefix, props)  KafkaSinkWriter.java:87-91 -> KafkaTransactionSender.java:81-86
    abortRestoredTransactions(sender, states)  KafkaSinkWriter.java:94 -> :197  (only when states non-empty)
      getRestoredTransactionIdPrefix(state)  KafkaSinkWriter.java:208  (strip "-<checkpoint>" from saved transactionId, require prefix match)
      validateRestoredStateOwner(restoredPrefix)  KafkaSinkWriter.java:239  (legacy shared prefix passes; else restoredWriterIndex % parallelism != currentWriterIndex -> IllegalStateException  :259)
      nextCheckpointByPrefix.forEach(sender::abortTransaction)  KafkaSinkWriter.java:205 -> KafkaTransactionSender.abortTransaction(prefix, checkpointId)  KafkaTransactionSender.java:193
        loop createTransactionProducer(generateTransactionId(prefix, i)) until producer.getEpoch()==0  KafkaTransactionSender.java:194-210
    kafkaProducerSender.beginTransaction(generateTransactionId(writerTransactionPrefix, lastCheckpointId+1))  KafkaSinkWriter.java:96-97 -> KafkaTransactionSender.java:119
  KafkaSinkWriter.snapshotState(cp)  KafkaSinkWriter.java:112
    KafkaTransactionSender.snapshotState -> new KafkaSinkState(transactionId, transactionPrefix /*job prefix, not writer prefix*/, cp, props)  KafkaTransactionSender.java:214-221
    beginTransaction(generateTransactionId(writerTransactionPrefix, cp+1))  KafkaSinkWriter.java:115-116

Findings

Issue 1: validateRestoredStateOwner hard-codes Zeta's modulo state redistribution; Flink's ListState repartitioning hands out contiguous chunks, so any Flink scale-down restore of an EXACTLY_ONCE Kafka sink now throws IllegalStateException and cannot recover

  • Location: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:259
  • Why it matters: - Root cause: KafkaSinkWriter.validateRestoredStateOwner (lines 255-265) rejects a restored state unless restoredWriterIndex % parallelism == currentWriterIndex. That rule mirrors Zeta's CheckpointCoordinator.restoreTaskState loop (for (int i = tuple.f1(); i < actionState.getParallelism(); i += currentParallelism)), which is an engine-internal detail. The Flink adapter (FlinkSink.createWriter -> sink.restoreWriter(stContext, restoredState)) receives whatever Flink's operator ListState repartitioner assigns, and that repartitioner distributes the union of old states as contiguous ranges, not a modulo stripe.
  • Failure scenario: a Flink job at parallelism 3 checkpoints <prefix>-0-N, <prefix>-1-N, <prefix>-2-N and is restored at parallelism 2. Subtask 0 receives <prefix>-0-N and <prefix>-1-N; 1 % 2 != 0, so line 259 throws before any fencing runs and the job cannot be restored at the new parallelism. A restore at the same parallelism still works, which is why this is easy to miss.
  • Why the check is unnecessary: the engine already guarantees each saved state is delivered to exactly one restoring subtask (the invariant abortRestoredTransactions and its Javadoc rely on). Fencing every namespace present in states is therefore safe without ownership validation; the check only adds a failure mode.
  • Test coverage: testRestoreKafkaToKafkaExactlyOnceOnStreaming in KafkaIT is @DisabledOnContainer(type = {SPARK, FLINK}), so the Flink restore path is not exercised by the e2e suite.
  • Suggested fix: keep the Integer.parseInt format check as the only hard failure, fence every namespace that arrives in states, and downgrade the ownership mismatch to a WARN log (or remove it).
  • Evidence: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:259 || restoredWriterIndex % parallelism != currentWriterIndex) {; seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:262 "Kafka transaction prefix [%s] was assigned to writer [%d] of [%d], "; docs/en/introduction/concepts/incompatible-changes.md:19 Stop the previous job attempt before restoring a checkpoint; recovery and rescaling fence every unfinished writer namespace assigned by the checkpoint, including IDs written before this change.
  • Suggested fix: This restoredWriterIndex % parallelism != currentWriterIndex rule encodes Zeta's CheckpointCoordinator.restoreTaskState loop (i = tuple.f1(); i += currentParallelism). The Flink adapter (FlinkSink.createWriter -> sink.restoreWriter(...)) gets its states from Flink's operator ListState repartitioner, which hands out contiguous ranges rather than a modulo stripe: on a 3->2 scale-down subtask 0 receives <prefix>-0-* and <prefix>-1-*, and this throws before any fencing runs, so the Flink job cannot be restored at the new parallelism. The engine already guarantees each state lands on exactly one subtask (the invariant abortRestoredTransactions relies on), so the check only adds a failure mode. Please fence whatever arrives in states and downgrade this to a WARN log (keep the Integer.parseInt format check as the only hard failure). Note that testRestoreKafkaToKafkaExactlyOnceOnStreaming is @DisabledOnContainer(FLINK, SPARK), so this path has no e2e coverage.
  • Severity: High

Issue 2: Scale-down restore now hard-fails whenever transaction_prefix is not configured, because each writer generates its own random prefix and the new restoreState() rejects mixed prefixes

  • Location: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:183
  • Why it matters: - Root cause: when transaction_prefix is absent (the default), lines 78-79 still give every writer instance its own random SeaTunnel%04d prefix, and KafkaTransactionSender.snapshotState (KafkaTransactionSender.java:219-221) persists that per-writer value into KafkaSinkState.transactionIdPrefix. On a Zeta scale-down, CheckpointCoordinator.restoreTaskState hands subtask k the states of original subtasks k, k+P, k+2P, ..., so the restored list legitimately contains two or more different random prefixes. The new loop in restoreState (lines 182-187) throws IllegalStateException("Cannot restore Kafka sink states with different transaction prefixes") as soon as the second prefix differs from states.get(0).
  • Failure scenario: parallelism 3 -> 2 with no transaction_prefix. Writer 0 receives SeaTunnel0001-0-4 (from original subtask 0) and SeaTunnel0002-2-4 (from original subtask 2). restoreState throws at line 184 and the job never starts. Even if that guard were relaxed, getRestoredTransactionIdPrefix (lines 229-234) would reject the second state as "does not belong to prefix" because it compares against the single this.transactionPrefix.
  • Regression: before this PR, the extra states were effectively ignored (their transactions were left unfenced, but the job restored). The PR turns a silent gap into a hard crash for the default configuration.
  • Suggested fix: resolve each state's namespace relative to its own state.getTransactionIdPrefix() instead of a single writer-wide prefix, and fence all of them. Add a KafkaSinkWriterTest case that restores writer 0 at parallelism 2 from SeaTunnel0001-0-4 + SeaTunnel0002-2-4.
  • Evidence: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:184-185 throw new IllegalStateException("Cannot restore Kafka sink states with different transaction prefixes");; seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:229-230 if (!restoredPrefix.equals(this.transactionPrefix) && !restoredPrefix.startsWith(this.transactionPrefix + "-")) {; seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:185 "Cannot restore Kafka sink states with different transaction prefixes");
  • Suggested fix: This check breaks the default configuration on scale-down. When transaction_prefix is not set, lines 78-79 give every writer its own random SeaTunnel%04d prefix, and that per-writer value is what KafkaTransactionSender.snapshotState stores in KafkaSinkState.transactionIdPrefix. Zeta's restoreTaskState assigns subtask k the states of original subtasks k, k+P, ..., so after a 3->2 restore writer 0 legitimately receives two states with different random prefixes and this loop throws; getRestoredTransactionIdPrefix would then also reject the second one as "does not belong to prefix". Previously those extra states were ignored (unfenced, but no crash). Please resolve each state's namespace relative to its own getTransactionIdPrefix() and fence all of them instead of requiring a single prefix, and add a KafkaSinkWriterTest case restoring writer 0 at parallelism 2 from SeaTunnel0001-0-4 + SeaTunnel0002-2-4.
  • Severity: High

Issue 3: A writer that restores with no state (scale-up) starts its transaction sequence at 1 regardless of the job's checkpoint id, so its namespace is never fenced and a failed first attempt leaves an unfenced open transaction until the next checkpoint

  • Location: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:93 if (!kafkaStates.isEmpty()) {
  • Why it matters: - Root cause: abortRestoredTransactions only runs when !kafkaStates.isEmpty() (line 93), and lastCheckpointId stays 0 for a writer that received no state. After a scale-up (e.g. 2 -> 3 restoring from checkpoint 8) writer 2 begins <prefix>-2-1 (line 97) while its siblings begin <prefix>-0-9 / <prefix>-1-9. On snapshotState(9) writer 2 then jumps to <prefix>-2-10, so the id sequence in that namespace is 1, 10, 11, ....
  • Failure scenario: the first attempt at parallelism 3 fails after snapshotState(9) is called on writer 2 but before checkpoint 9 completes. On the next restore writer 2 again receives no state (checkpoint 8 only has two states), skips fencing, and opens <prefix>-2-1 again, which does fence the previous -2-1. But the previous attempt's <prefix>-2-10 (begun at line 115-116) is never probed: nothing starts the getEpoch()==0 scan in this namespace, so that transaction stays open until transaction.timeout.ms, blocking read_committed consumers on the affected partitions.
  • Suggested fix: seed lastCheckpointId for stateless writers from the job-wide restored checkpoint (e.g. via a committer-side or shared max), or always run abortTransaction(writerTransactionPrefix, lastCheckpointId + 1) for the writer's own namespace on restore even when kafkaStates is empty, so the scan from 1 can discover and fence any later ids left by a previous attempt.
  • Evidence: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:94 abortRestoredTransactions(transactionSender, kafkaStates);; seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:97 generateTransactionId(this.writerTransactionPrefix, this.lastCheckpointId + 1));
  • Severity: Medium

Issue 4: On Spark the subtask index is the Spark taskId, so every task retry gets a brand-new transactional namespace and the previous attempt's open transaction is never fenced

  • Location: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:84
  • Why it matters: - Root cause: writerTransactionPrefix is built from context.getIndexOfSubtask() (line 84). On Spark, SeaTunnelSparkDataWriterFactory.createWriter(partitionId, taskId) constructs new DefaultSinkWriterContext(jobId, (int) taskId, parallelism) (spark-3.3 line 69; the spark-2.4 SparkDataWriterFactory does the same at line 68), and DefaultSinkWriterContext.getIndexOfSubtask() returns that value, i.e. Spark's monotonically increasing task ID rather than a stable [0, parallelism) slot.
  • Impact: each Spark task attempt opens <prefix>-<taskId>-1 (line 96-97). A retried attempt uses a different taskId, so it opens a fresh namespace, and because kafkaStates is empty on Spark the fence path at line 93-94 never runs. The previous attempt's <prefix>-<oldTaskId>-1 stays open until transaction.timeout.ms, blocking read_committed consumers on those partitions.
  • Note: this is partly pre-existing (Spark never had restore state), but the PR now makes the namespace depend on a value that is unstable on Spark, so the new per-writer design should account for it.
  • Suggested fix: make the Spark writer context expose partitionId as the subtask index, or guard here against idx >= getNumberOfParallelSubtasks() and document the Spark behaviour.
  • Evidence: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:96 this.kafkaProducerSender.beginTransaction(
  • Suggested fix: On Spark this index is not a stable slot: SeaTunnelSparkDataWriterFactory.createWriter(partitionId, taskId) builds new DefaultSinkWriterContext(jobId, (int) taskId, parallelism), so getIndexOfSubtask() is Spark's ever-increasing task id. A retried task therefore opens <prefix>-<newTaskId>-1 and nothing ever fences <prefix>-<oldTaskId>-1 (the fence path below only runs when kafkaStates is non-empty), leaving an open transaction that blocks read_committed consumers until transaction.timeout.ms. Could we either make the Spark context expose partitionId as the subtask index, or guard here against idx >= getNumberOfParallelSubtasks() and document the Spark behaviour?
  • Severity: Medium

Issue 5: Every restoring writer fences the same legacy shared namespace concurrently; sibling probes bump the epoch of IDs that would otherwise terminate the getEpoch()==0 loop, so the probe chain grows with parallelism and the same ID is fenced N times

  • Location: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:242
  • Why it matters: - Root cause: for legacy state every subtask's KafkaSinkState.transactionId is <prefix>-<cp>, so validateRestoredStateOwner returns early for all of them (lines 240-243) and each writer calls abortTransaction(transactionPrefix, cp+1) via line 205. The loop in KafkaTransactionSender.abortTransaction(String,long) (lines 193-210) stops only when producer.getEpoch() == 0, i.e. when the ID has never been registered with the coordinator; but a sibling writer's initTransactions() on <prefix>-<cp+k> registers that ID and bumps its epoch.
  • Effect: with N writers restoring at once, the first to probe <prefix>-<cp+1> sees epoch 0 and stops, but it has now registered the ID; the second sees epoch 1 and continues to <prefix>-<cp+2>, the third to <prefix>-<cp+3>, and so on. Startup performs up to roughly N(N+1)/2 temporary producer create/init/close round-trips across the job instead of one, and the same legacy ID is fenced N times. The work is wasted rather than incorrect, so this is a LOW.
  • Suggested fix: fence the legacy shared namespace only from subtask 0 (which always receives a state when any exist, under both Zeta's modulo and Flink's contiguous distribution), or fence once per distinct legacy prefix, and let other writers skip the merge at line 203 for the legacy prefix.
  • PR13060-F6 describes this same behaviour; a single fix covers both.
  • Evidence: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:242 return;; seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaTransactionSender.java:193 void abortTransaction(String transactionIdPrefix, long checkpointId) {; seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaTransactionSender.java:195 String transactionId = generateTransactionId(transactionIdPrefix, i);
  • Suggested fix: For legacy state every subtask holds <prefix>-<cp>, so this early return makes all N writers run abortTransaction(transactionPrefix, cp+1) on the same shared namespace at the same time. Because that loop stops only on getEpoch() == 0, a sibling's initTransactions() on <prefix>-<cp+k> registers the ID and pushes the next writer one probe further, so startup does up to O(N) redundant producer init/close round-trips per writer (roughly N(N+1)/2 across the job). Consider fencing the legacy namespace only from subtask 0 (it always receives a state when any exist under both Zeta and Flink distribution) and skipping the merge for other writers.
  • Severity: Low

Issue 6: Legacy shared-namespace fencing is repeated concurrently by every restored writer and each probe bumps the epoch siblings observe, so the scan grows with parallelism

  • Location: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:205
  • Why it matters: - Same issue as PR13060-F5, viewed from the nextCheckpointByPrefix.forEach(transactionSender::abortTransaction) call at line 205: legacy states from an old checkpoint all carry the same transaction id <prefix>-<ckpt>, so after a restore every one of the N writers calls abortTransaction(prefix, ckpt+1) on the same shared namespace (KafkaTransactionSender.java:193-210). Each initTransactions() on an id bumps its epoch, so once writer A has probed <prefix>-6 (epoch 0, stops), writer B sees epoch 1 on <prefix>-6 and must continue to <prefix>-7, writer C to <prefix>-8, and so on: roughly N(N+1)/2 producer creations on restore instead of one.
  • Resolution: addressed by the same change proposed in PR13060-F5 (fence the legacy shared namespace once, from subtask 0 or once per distinct legacy prefix). No separate action is needed; the line comment for this issue is posted at KafkaSinkWriter.java:242 under PR13060-F5.
  • Evidence: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaTransactionSender.java:195 String transactionId = generateTransactionId(transactionIdPrefix, i);; seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:205 nextCheckpointByPrefix.forEach(transactionSender::abortTransaction);
  • Suggested fix: For legacy state every restored writer holds the same <prefix>-<ckpt> id, so all N writers run abortTransaction(prefix, ckpt+1) concurrently against the same shared namespace. Because each initTransactions() bumps the epoch, the writer that probes <prefix>-6 second sees epoch 1 and keeps scanning to -7, the third to -8, etc. - roughly N(N+1)/2 producer creations on restore. Consider fencing the legacy shared namespace only from subtask 0 (or once per distinct legacy prefix) and letting the other writers skip it.
  • Severity: Low

Issue 7: New ID-shape documentation lives only in the Semantics paragraph; the transaction_prefix option row and the engine scope of the rescaling claim should be aligned

  • Location: docs/en/connectors/sink/Kafka.md:102
  • Why it matters: - The new paragraph in docs/en/connectors/sink/Kafka.md:102 (and the docs/zh counterpart) describes the <prefix>-<subtask>-<checkpoint> shape and the recovery/rescaling cleanup, but the transaction_prefix row in the Sink Options table still only says to use a different prefix for each job and does not mention that the ID is extended with the subtask index. Users scanning the option table (which is what most ACL authors read) will miss the change.
  • The sentence "During recovery or rescaling, each writer cleans every unfinished transaction namespace assigned to it by the restored checkpoint" currently holds only for Zeta's state redistribution, because of the modulo check in KafkaSinkWriter#validateRestoredStateOwner (see PR13060-F1). Once that check is made engine-neutral the sentence is accurate; otherwise it should be scoped to Zeta.
  • docs/en/introduction/concepts/incompatible-changes.md:19 correctly calls out the ACL/monitoring impact; linking the option row to that entry would help.
  • Evidence: docs/en/introduction/concepts/incompatible-changes.md:19 Update Kafka transactional-ID ACLs or monitoring rules that depend on the old ID shape. Stop the previous job attempt before restoring a checkpoint; recovery and rescaling fence every unfinished writer namespace assigned by the checkpoint, including IDs written before this change.
  • Suggested fix: Thanks for documenting the new ID shape here. Two small asks: (1) please also mention the <prefix>-<subtask>-<checkpoint> shape in the transaction_prefix row of the Sink Options table (EN and ZH), since that is where people configuring ACLs look first; (2) the "recovery or rescaling" sentence currently holds only for Zeta's state redistribution given the modulo check in KafkaSinkWriter#validateRestoredStateOwner -- once that is made engine-neutral this is fine, otherwise please scope it to Zeta.
  • Severity: Low

Review conclusion

Conclusion: can merge after the blocking items are fixed

1. Blocking items

  • Issue 1: validateRestoredStateOwner hard-codes Zeta's modulo state redistribution; Flink's ListState repartitioning hands out contiguous chunks, so any Flink scale-down restore of an EXACTLY_ONCE Kafka sink now throws IllegalStateException and cannot recover
  • Issue 2: Scale-down restore now hard-fails whenever transaction_prefix is not configured, because each writer generates its own random prefix and the new restoreState() rejects mixed prefixes

2. Remaining follow-ups

  • Issue 3: A writer that restores with no state (scale-up) starts its transaction sequence at 1 regardless of the job's checkpoint id, so its namespace is never fenced and a failed first attempt leaves an unfenced open transaction until the next checkpoint
  • Issue 4: On Spark the subtask index is the Spark taskId, so every task retry gets a brand-new transactional namespace and the previous attempt's open transaction is never fenced
  • Issue 5: Every restoring writer fences the same legacy shared namespace concurrently; sibling probes bump the epoch of IDs that would otherwise terminate the getEpoch()==0 loop, so the probe chain grows with parallelism and the same ID is fenced N times
  • Issue 6: Legacy shared-namespace fencing is repeated concurrently by every restored writer and each probe bumps the epoch siblings observe, so the scan grows with parallelism
  • Issue 7: New ID-shape documentation lives only in the Semantics paragraph; the transaction_prefix option row and the engine scope of the rescaling claim should be aligned

Thanks for the updates so far. Happy to discuss the remaining points.

@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.

Thanks for the recovery changes and validation details. I checked the new head and reconciled @SEZ9's findings below. The per-writer collision fix is appropriate, but recovery is not yet safe across the supported assignment and retry paths.

What Problem Does This PR Solve?

User pain point: Parallel exactly-once writers sharing a configured transaction prefix use the same Kafka transaction ID and fence one another.

Fix approach: Separate the checkpointed prefix from the current writer namespace, and fence saved namespaces before beginning new transactions.

One-sentence summary and example: Two writers now use job-0-7 and job-1-7 instead of both opening job-7; however, valid redistributed states can still be rejected during restore.

1. Code Change Review

1.1 Core Logic Analysis

KafkaSinkWriter derives the writer suffix after restoring state. KafkaTransactionSender persists the original prefix, while beginTransaction uses the writer namespace. Restore takes the maximum saved checkpoint and deduplicates namespace cleanup with the earliest unfinished sequence. The public two-argument sender constructor remains available. Zeta assigns old writer indices modulo new parallelism, but that is not a connector-wide contract.

Before:

generateTransactionId(transactionPrefix, checkpointId);
// Restore only the first saved namespace.

After:

generateTransactionId(writerTransactionPrefix, checkpointId);
// Inspect all saved namespaces, validate ownership, then fence each.

Key Findings

  • Normal parallel writers no longer share IDs when their subtask indices differ.
  • Saved state fields remain unchanged; transaction-ID ACL/monitoring assumptions do change.
  • The new prefix and ownership guards reject valid recovery cases.
  • A writer with no assigned saved state has no evidence from which to clean its later failed-attempt IDs.

Complete runtime path

KafkaSink.restoreWriter -> KafkaSinkWriter.restoreState
 -> writerTransactionPrefix -> KafkaTransactionSender
 -> abortRestoredTransactions -> validateRestoredStateOwner -> abortTransaction
 -> beginTransaction -> write/send -> prepareCommit -> snapshotState -> next transaction
Zeta CheckpointCoordinator.restoreTaskState / FlinkSink.restoreWriter -> assigned writer states
Spark SeaTunnelSparkDataWriterFactory -> createWriter with taskId -> empty-state writer

The base failure propagation from asynchronous sends is unchanged. The new normal-write namespace fixes collision, but restore and failed-attempt cleanup require the issues below. Flink's RoundRobinOperatorStateRepartitioner balances SPLIT_DISTRIBUTE state in chunks; it does not promise Zeta's modulo assignment.

1.2 Compatibility Impact

Partially incompatible. The serialized state fields and option names are unchanged, but Kafka transactional IDs acquire a writer suffix. Existing ACLs and monitoring must allow the new shape. Legacy states are parsed, but acceptance of a state format alone does not prove recovery compatibility.

1.3 Performance / Side-Effect Analysis

Cleanup creates and closes a temporary producer per probed transaction. Deduplication is local to one writer. Legacy shared prefixes may still be probed by several restoring writers, adding coordinator round trips; this is a non-blocking efficiency concern.

1.4 Error Handling and Logging

Malformed IDs and mismatched ownership fail before producer cleanup starts. Temporary cleanup producers close in finally. The current guards also treat valid engine assignments/default prefixes as errors, so they need correction rather than a broader catch-and-ignore.

Issue 1: Valid Flink redistributed state fails the modulo ownership check

  • Location: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:255
  • Problem description: With three old single-entry writer states redistributed to two Flink subtasks, a valid assignment gives new writer 0 old writers 0 and 1. The check rejects old writer 1 because 1 % 2 != 0. The Flink adapter forwards restored state unchanged.
  • Potential risk: A valid exactly-once scale-down checkpoint cannot restore.
  • Best improvement: Support actual engine assignments while preventing old-namespace cleanup from fencing newly active siblings. Prove the ordering/isolation invariant with a Flink assignment regression. Do not simply downgrade the guard to a warning: unique delivery of each OLD state does not guarantee exclusive ownership of the NEW writer namespace.
  • Severity: High; blocking.
  • Raised by another reviewer: Yes — SEZ9 Issue 1; independently verified

Issue 2: Generated per-writer prefixes are rejected on scale-down

  • Location: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:183
  • Problem description: Without transaction_prefix, each writer generates SeaTunnel%04d independently. A valid scale-down list can contain SeaTunnel0001 and SeaTunnel0002. restoreState rejects it, and getRestoredTransactionIdPrefix also compares every state against only the first prefix.
  • Potential risk: The default configuration can no longer restore valid combined writer states.
  • Best improvement: Interpret and fence every state relative to its own saved prefix, then choose the current writer namespace under a documented recovery invariant. Cover mixed generated prefixes and legacy states in the existing regression fixture.
  • Severity: High; blocking.
  • Raised by another reviewer: Yes — SEZ9 Issue 2; independently verified

Issue 3: Scale-up retries can leave later transactions in a stateless writer namespace unfenced

  • Location: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:93
  • Problem description: Restoring checkpoint 8 from parallelism 2 to 3 leaves new writer 2 with no state. It opens prefix-2-1, then snapshotState(9) opens prefix-2-10. If data is sent there and the attempt fails before checkpoint 9 completes, restore from checkpoint 8 again only reopens prefix-2-1. No saved state identifies prefix-2-10 for cleanup.
  • Potential risk: An abandoned transaction can hold back read_committed consumers until Kafka times it out.
  • Best improvement: Provide a recovery protocol that knows the restored checkpoint and cleans the new writer namespace across failed scale-up attempts, or uses an equivalent safe coordinated namespace strategy. Scanning from 1 alone is insufficient: the existing scan stops at the first unused ID, so the gap at 2 hides ID 10. Add a failure-before-checkpoint-completion regression.
  • Severity: High; blocking.
  • Raised by another reviewer: Yes — SEZ9 Issue 3; independently verified with a qualification to its proposed fix

Issue 4: Spark task attempts do not provide a stable writer namespace

  • Location: seatunnel-translation/seatunnel-translation-spark/seatunnel-translation-spark-3.3/src/main/java/org/apache/seatunnel/translation/spark/sink/write/SeaTunnelSparkDataWriterFactory.java:69
  • Problem description: The adapter supplies taskId, not partitionId, as indexOfSubtask and calls createWriter with no restored state. After an abrupt executor loss that cannot run abort(), a retry uses a different writer namespace and does not fence the prior attempt. Normal abortPrepare does abort a live transaction; this finding concerns loss of that cleanup path.
  • Potential risk: The prior attempt can leave a transaction open until timeout, delaying read_committed output.
  • Best improvement: Define and validate an attempt-safe Spark namespace/recovery contract, or explicitly restrict the affected exactly-once support until it is implemented. An index-range guard alone does not implement retry cleanup.
  • Severity: Medium; blocking.
  • Raised by another reviewer: Yes — SEZ9 Issue 4; narrowed to abrupt failure

Issue 5: Deduplicate legacy cleanup and align the option documentation

  • Location: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:205
  • Problem description: Multiple restored writers can probe the same legacy shared namespace; deduplication currently applies only within each writer. The option table also does not point directly to the newly documented ID shape.
  • Potential risk: Redundant producer initialization increases restore work, and ACL users can miss the shape change.
  • Best improvement: Where the recovery protocol permits, assign one cleanup owner per distinct legacy namespace. Do not blindly choose writer 0 when saved prefixes may differ. Cross-link the option description in both guides to the detailed transaction-ID behavior.
  • Severity: Low; non-blocking.
  • Raised by another reviewer: Yes — SEZ9 Issues 5 and 6 are duplicates; Issue 7 is documentation

2. Code Quality Assessment

2.1 Coding Standards

Prefix field and constructor Javadocs now explain the two lifetimes, resolving the earlier comment request. The ownership Javadoc must change with the corrected algorithm; it currently presents the modulo assumption as a general engine guarantee.

2.2 Test Coverage and Test Stability

Test stability: Risk present. The new deterministic unit case uses Zeta-style old writers 0 and 2 assigned to new writer 0. The real-broker 3-to-2 recovery test is disabled for Flink and Spark, so it cannot validate those adapters. The batch path checks read_committed output and exact row counts. Add recovery cases for mixed generated prefixes, Flink assignments, and failure after scale-up before a new checkpoint completes. These are recovery coverage gaps, not evidence that the existing test itself is timing-flaky. Author-reported local executions are not independently executed here.

Local analysis: fetched the head, created independent branch seatunnel-review-13060, read the complete 10-file diff and traced affected callers with git show/git grep. No local compilation, unit tests, integration tests, E2E, containers, or job execution was performed, as requested. These are source-analysis conclusions; execution evidence is the current-head CI below.

2.3 Documentation Updates

Both connector guides and incompatible-changes pages describe the ID shape and ACL impact. Scope the recovery claim to behavior actually supported after the fixes; link the transaction_prefix option row to the detailed semantics so ACL users can find it.

3. Architectural Soundness

3.1 Elegance of the Solution

Incomplete root-cause fix. The connector is the right layer for namespace generation. The best design separates failed-attempt cleanup ownership from current writer namespace ownership. The smallest safe revision must preserve recovery for actual engine assignments and generated prefixes; merely deleting the modulo guard can allow one recovering writer to fence a sibling that has already opened the overlapping new namespace.

3.2 Maintainability

Resolve each saved namespace against its own saved prefix, and document the cross-writer ordering or namespace isolation invariant. Do not infer that invariant solely from the index of the restoring task.

3.3 Extensibility

Engine-neutral state ownership is necessary for Zeta and Flink. Spark uses task attempt IDs in its adapter, so the connector cannot assume a stable partition slot on every backend.

3.4 Historical-Version Compatibility

Old shared-prefix and newer per-writer states require explicit recovery coverage. No state serializer changes are present, but generated-prefix and rescaling behavior is part of the compatibility contract.

4. Issue Summary

Number Issue Location Severity
1 Valid Flink redistributed state fails the modulo ownership check seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:255 High
2 Generated per-writer prefixes are rejected on scale-down seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:183 High
3 Scale-up retries can leave later transactions in a stateless writer namespace unfenced seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:93 High
4 Spark task attempts do not provide a stable writer namespace seatunnel-translation/seatunnel-translation-spark/seatunnel-translation-spark-3.3/src/main/java/org/apache/seatunnel/translation/spark/sink/write/SeaTunnelSparkDataWriterFactory.java:69 Medium
5 Deduplicate legacy cleanup and align the option documentation seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:205 Low

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers — must be fixed
    • Issue 1: Valid Flink redistributed state fails the modulo ownership check; Issue 2: Generated per-writer prefixes are rejected on scale-down; Issue 3: Scale-up retries can leave later transactions in a stateless writer namespace unfenced; Issue 4: Spark task attempts do not provide a stable writer namespace Issues 1–4 and a successful exact-head Build remain required.
  2. Recommended fixes — non-blocking
    • Issue 5: Deduplicate legacy cleanup and align the option documentation

Overall assessment: Normal parallel collision is addressed. The recovery protocol still has concrete compatibility and failed-attempt gaps, so the author's Zeta-only passing results do not establish support across the adapters.

Existing-review reconciliation: All seven SEZ9 findings were checked: 1–4 are consolidated above, 5/6 are one efficiency finding, and 7 is documentation. I disagree with removing the ownership check without a replacement ordering/isolation guarantee, and with scanning from 1 as a sufficient fix for a sequence gap. The author's prefix documentation improvement is accepted. Author replies have been incorporated into this single full review.

Head 10e618cb3815d613889e9ef9632fb54df7431926. Live base dev at 3ac2d1cec6aa7b3741c4dacdd23020f778e23c02; comparison diverged, ahead 2 / behind 7; merge state BLOCKED. Behind/diverged alone is recorded metadata, not a request to synchronize upstream. Checks: Signal pull request update = SUCCESS; Build = ACTION_REQUIRED

The Build check is ACTION_REQUIRED with “Workflow run detection failed”: no fork Build was detected for this head. This is a missing-run gate, not a failing executed Kafka test. Enable fork Actions if disabled and run Build for this branch, or link an existing exact-head run. Behind status does not establish that synchronization fixes this condition.

Daniel has READ repository permission. This COMMENT records the technical conclusion; it is not an effective maintainer approval or a dismissal of any historical requested-changes entry. A write-capable maintainer owns the final repository approval gate.

@zephyr45

Copy link
Copy Markdown
Author

Thanks @SEZ9 and @DanielLeens — I addressed the blocking findings in 585f69b7.

  • Removed the Zeta-specific modulo ownership rule. A restoring writer now adopts one non-legacy namespace from the old states actually assigned to it (preferring its exact index when present, otherwise deterministically choosing one). Since an old state/namespace is assigned to one restoring writer, siblings neither adopt nor clean the chosen current namespace. This covers Flink's contiguous 3-to-2 assignment as well as Zeta's modulo assignment without a cleanup/new-writer race.
  • Each restored state is parsed relative to its own saved base prefix, so scale-down works when transaction_prefix was omitted and the assigned states contain different generated prefixes.
  • Transaction IDs now use a contiguous per-writer sequence independent of checkpoint IDs. Every writer, including a stateless scale-up writer, scans and fences its current namespace from sequence 1 before opening work; there is no 1-to-10 gap hidden behind the first unused ID.
  • Spark 2.4 and 3.3 now use stable partitionId rather than retry-specific taskId as the sink-writer index. The Spark unit regression passes partitionId=2, taskId=99, and verifies index 2.
  • The English and Chinese option rows now link to and state the <prefix>-<writer>-<sequence> shape.

I deliberately did not invent a global owner for legacy shared-prefix cleanup: mixed historical prefixes provide no engine-neutral cross-writer coordinator. That low-severity path can do redundant fencing, but correctness is preserved.

Current-head validation:

  • Kafka connector unit suite: 143 passed; KafkaSinkWriterTest 11/11.
  • Spark 3.3 SparkSinkTest: 2/2.
  • Affected Kafka/Spark package reactor: 30/30 modules.
  • Documentation checks: no failures/errors.
  • Real Kafka E2E: Zeta parallel exactly-once + 3-to-2 restore, 2/2.
  • Real Kafka E2E: parallel exactly-once on Spark 2.4.6 and Spark 3.3.0, 2/2.
  • Spotless and git diff --check passed.

GitHub had disabled inherited workflows on the fork despite the API reporting Actions enabled. I re-enabled them and queued the exact-head Build: https://github.com/zephyr45/seatunnel/actions/runs/41174376848 (head 585f69b76ed066ec7c270f688fbb9d7e9753adc5).

@zephyr45

Copy link
Copy Markdown
Author

Thanks @SEZ9 and @DanielLeens — I found and fixed two residual correctness gaps in the previous update with d8143b58.

  • A fresh writer namespace no longer reuses the bare current subtask index. KafkaSink now creates a generation token once and serializes it with the sink graph. Task retries therefore reuse and fence the same namespace, while a later rescale/execution generation gives a stateless writer a namespace distinct from any old namespace adopted from restored state. This covers the repeated Flink 3 -> 2 -> 3 case where old namespace 2 can be adopted by writer 1 before writer 2 becomes stateless again.
  • When transaction_prefix is omitted, the generated job prefix is also chosen once in KafkaSink and serialized with the graph instead of being regenerated independently by each writer construction. A stateless retry can now identify and fence its previous attempt. Restore remains compatible with historical states whose writers saved different generated prefixes.
  • The parser accepts both the previous numeric writer namespaces and the new opaque generation-scoped namespaces; KafkaSinkState and its serialized fields are unchanged.
  • EN/ZH connector and incompatible-change docs now state that <writer> is opaque, stable across task retries, and not necessarily the current subtask index after rescaling.
  • Added regressions for repeated scale-down/scale-up namespace isolation, generated-prefix stateless retry through sink serialization, and legacy no-prefix migration.

Final local validation on Java 11:

  • Kafka connector unit suite: 146 passed; KafkaSinkWriterTest 14/14.
  • 16-module affected dependency reactor: package succeeded.
  • Documentation checks: 7 run, 0 failures/errors (3 skipped).
  • Repository-wide Spotless and full -DskipTests verify: passed.
  • git diff --check: passed.

The Docker daemon is unavailable in my local environment, so I did not claim a new local real-broker E2E result for this follow-up. The exact-head fork Build is running at https://github.com/zephyr45/seatunnel/actions/runs/41208442957 (head d8143b588329f87ef2a123936165fba87a2d22b8).

The previously noted duplicate legacy shared-prefix probing remains an engine-neutral efficiency limitation, not a correctness gap: historical shared states contain no globally unique cleanup owner, and selecting writer 0 would miss distinct historical generated prefixes assigned elsewhere. Cleanup is still deduplicated within each writer and remains safe across writers.

@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.

Thank you for the thorough rework, and for taking both rounds of feedback (mine and @SEZ9's) so seriously. I re-read the whole diff on the new head d8143b58 rather than only the increment. The blockers from my previous round on 10e618cb (Flink contiguous redistribution, mixed generated prefixes, scale-up retry gap, Spark attempt identity) are resolved at the source level in this head, and I have no remaining source blocker. I do have a few non-blocking points below, and the exact-head CI is still running, so this is a comment rather than an approval for now.

What Problem Does This PR Solve?

User pain point: With semantics = EXACTLY_ONCE and a shared transaction_prefix, parallel Kafka sink writers all open <prefix>-<checkpoint> and fence each other with ProducerFencedException (#13044).

Fix approach: Each writer gets its own transactional-ID namespace <prefix>-<writer>-<sequence>. The job prefix and a generation token are created once in KafkaSink and serialized with the sink. On restore, a writer adopts one namespace from the states assigned to it and fences every assigned namespace plus its own before opening new work. Spark now uses partitionId instead of taskId as the writer index.

One-sentence summary: Parallel writers no longer share transactional IDs, and recovery fences exactly the namespaces the engine hands to each restoring writer.

1. Code Change Review

1.1 Core Logic Analysis

KafkaSink.<init>  KafkaSink.java:55-58   prefix (config or random) + generation token chosen ONCE, serialized with the sink
 -> createWriter / restoreWriter  KafkaSink.java:62-84 -> new KafkaSinkWriter(..., prefix, token)
   -> newWriterNamespace = token + "w" + subtaskIndex            KafkaSinkWriter.java:97-98
   -> restoreState(states, ns, idx)                              KafkaSinkWriter.java:230-298
        parse each state relative to ITS OWN saved prefix        :322-367
        no states      -> fresh ns, sequence starts at 1
        non-legacy     -> adopt exact-match ns, else min(ns) among ASSIGNED states; next seq = max(seq)+1
        legacy only    -> keep saved prefix, fresh ns, sequence 1
   -> abortRestoredTransactions: per distinct ns, probe from (seq+1) until an unused ID   :306-320
   -> beginTransaction(<writerPrefix>-<seq>)                     :112-114
snapshotState(cp): sender.snapshotState -> KafkaSinkState(txId, job prefix, cp); seq++ ; begin next   :128-136

Re-verifying each earlier blocker against this head:

  • Flink contiguous redistribution (my Issue 1 / SEZ9 Issue 1): resolved. The modulo guard is gone. A writer fences only namespaces that came in its own assigned states, and it adopts one of them as its new namespace (:244-270). Because the engine delivers each old state to exactly one new writer, no sibling can adopt or clean the same namespace. A fresh namespace is token+w+index, which cannot equal a namespace adopted from an older generation. This also addresses my concern that simply downgrading the guard could let one writer fence a live sibling.
  • Mixed generated prefixes (Issue 2): resolved. Every state is parsed against its own getTransactionIdPrefix() (:344-366), and this.transactionPrefix follows the adopted state. The unit test shouldRestoreMixedGeneratedPrefixesAfterScaleDown covers it.
  • Scale-up retry gap (Issue 3): resolved. The sequence is now independent of checkpoint IDs and contiguous, so the "scan stops at the first unused ID" probe in KafkaTransactionSender.java:190-210 cannot be hidden behind a gap (the former 1, 10, 11 case). The generated prefix is also chosen once, so a stateless retry can find its previous attempt.
  • Spark attempt identity (Issue 4): resolved. partitionId is stable across attempts and the sink-level token is shared, so a retried attempt fences the previous one. Both SparkDataWriterFactory.java:68 and SeaTunnelSparkDataWriterFactory.java:69 are changed.
  • Prefix-lifetime Javadocs: resolved. Docs for the option row now cross-link to #semantics in both languages (anchors exist).

Other things I checked and found sound: the pending-commit transaction n of the restored checkpoint is never probed (scan starts at n+1), so the committer can still resume it; state serialization (KafkaSinkState) is unchanged; MultiTableSink creates one KafkaSink per table and gives each writer a unique subtask*replica+i index (MultiTableSink.java:149), so per-table tokens plus indices stay distinct.

1.2 Compatibility Impact

Partially incompatible (intentional and documented). Transactional IDs change shape from <prefix>-<checkpoint> to <prefix>-<writer>-<sequence>, so ACLs or monitoring keyed on the exact old shape need updating (prefixed ACLs keep matching). Old checkpoints restore through the legacy branch, which fences the saved <prefix>-<ckpt+1>... IDs. Option names, defaults, and the state DTO are unchanged. English and Chinese docs and the incompatible-changes pages state this.

1.3 Performance / Side Effects

No per-row cost. Restore cost is one temporary producer per distinct namespace plus one probe per unused ID, and the scan starts after the last saved sequence, so it stays short. Legacy shared-prefix cleanup can be repeated by several restoring writers; the author explains why a single owner cannot be chosen safely, and I agree this is an efficiency note, not a correctness gap. Each new job submission (new token) leaves the previous attempt's namespace unfenced if the job is restarted without a checkpoint; such transactions expire by broker timeout (this matches the documented "stop the previous attempt first").

1.4 Error Handling and Logging, and Issues

Malformed or foreign IDs fail fast with explicit messages before any producer is created. Temporary producers are closed in finally. The previously noted async-send failure propagation is untouched.

Issue 1: A reused generation token can still produce a namespace collision under in-place rescaling

  • Location: KafkaSinkWriter.java:244-270 (adoption) with KafkaSink.java:55-58 (token chosen once)
  • Problem: The fix for the "3 -> 2 -> 3" case relies on the token changing between executions. If the same serialized sink is reused while parallelism changes in place (for example Flink's adaptive scheduler / reactive mode, which restores operator state without re-translating the job), writer 1 can adopt old namespace token+w2 after scale-down, and after scale-up the stateless writer 2 derives the very same token+w2 and fences writer 1's open transaction. I could not confirm from the Flink translation that this path is reachable in practice, so this is an inference from the code.
  • Risk: Rare ProducerFencedException loop for that topology, the same symptom this PR set out to remove.
  • Best improvement: Either document that in-place rescaling with a retained sink instance is unsupported, or make the fresh namespace of a stateless writer unable to equal any adopted one (for example, a writer that sees a restored namespace equal to its own fresh one picks a different suffix). Add one regression for "adopt w2, then stateless index 2 in the same generation".
  • Severity: Medium; non-blocking.
  • Raised by another reviewer: No.

Issue 2: Remove compatibility for numeric namespaces that were never released

  • Location: KafkaSinkWriter.java:70-71 (\d+ branch of WRITER_NAMESPACE_PATTERN) and :253-257 (Integer.toString(currentWriterIndex) match)
  • Problem: Numeric <prefix>-<index>-<seq> namespaces exist only in earlier heads of this unmerged PR; no released version ever wrote them. Accepting them adds a branch that no real checkpoint can contain.
  • Risk: Dead compatibility code that a future maintainer must reason about, and a looser parser than necessary.
  • Best improvement: Keep only the g...w<index> pattern plus the true legacy form (<prefix>-<checkpoint>), and drop the numeric branches and their test inputs.
  • Severity: Low; non-blocking.
  • Raised by another reviewer: No.

Issue 3: Same-partition Spark attempts now fence one another by design

  • Location: SparkDataWriterFactory.java:68, SeaTunnelSparkDataWriterFactory.java:69
  • Problem: Using partitionId is the right call for retries, but two concurrent attempts of one partition (Spark speculative execution, if enabled) would share a namespace and fence each other. Speculation is off by default, and I only traced this from the code path, so please treat it as an inference.
  • Risk: Spurious attempt failures with speculation enabled.
  • Best improvement: One sentence in the Kafka sink docs that exactly-once on Spark requires spark.speculation=false.
  • Severity: Low; non-blocking.
  • Raised by another reviewer: No (follows from SEZ9 Issue 4).

Carry-over from SEZ9 and my previous round

  • Duplicate legacy-namespace probing across restoring writers (SEZ9 Issue 5): acknowledged by the author with a sound rationale; non-blocking, +1.
  • Option-row documentation link (SEZ9 Issue 7): resolved.

2. Code Quality

2.1 Coding Standards

Imports, ASF headers, and formatting follow the project style. The protocol fields (transactionPrefix, writerTransactionPrefix, writerNamespaceGeneration, transactionIdPrefix) have focused Javadocs explaining which prefix is checkpointed and which one is writer-owned. The Javadoc on restoreState documents the ownership invariant clearly.

2.2 Tests and Stability

Stability rating: Stable. KafkaSinkWriterTest (14 tests) drives the real writer and sender with only producer creation mocked, uses fixed IDs and synchronous assertions, and has no Thread.sleep or fixed ports. It covers Flink-style contiguous assignment, Zeta-style modulo assignment, mixed generated prefixes, scale-down then scale-up, jumping checkpoint IDs, stateless retry, generated-prefix reuse through sink serialization, and malformed state. KafkaIT adds a two-partition parallel exactly-once batch test with exact set and count checks, and the streaming restore now goes 3 -> 2 with all three source partitions populated; topics are uniquely named. The Spark 3.3 test checks partitionId versus taskId. The gap is Issue 1 (same-generation adopt-then-stateless collision). Also note the author states that no real-broker E2E was run on the final head d8143b58 (Docker was unavailable), so the E2E evidence is from the previous head; please rely on the CI run for this head.

No src/main changes were made by me; I did not run builds or tests locally and rely on CI for runtime validation.

2.3 Documentation

English and Chinese Kafka sink pages and both incompatible-changes pages are updated consistently (opaque writer component, not necessarily the current subtask index after rescaling, stop the old attempt, distinct prefix per concurrent job). Good.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix, with a more elaborate recovery protocol than the first version. The change stays inside the Kafka connector plus a two-line Spark adapter correction, and the state DTO is untouched. The "adopt one assigned namespace, fence every assigned namespace" design is engine-neutral and does not depend on Zeta's modulo rule.

3.2 Maintainability

restoreState is dense (about 70 lines of stream chains). Splitting adoption selection into a small helper and dropping the numeric compatibility branch (Issue 2) would make the invariant easier to audit.

3.3 Extensibility

Opaque g<token>w<index> namespaces leave room for future schemes without another state change.

3.4 Historical-Version Compatibility

Legacy checkpoints (shared <prefix>-<checkpoint>) are parsed and fenced; mixed legacy and new states are handled. No serialization change. The origin/2.6-release -> 3.0 style upgrade chain is not applicable to this upstream repository. Compatibility is based on source reading and unit tests, not an executed upgrade.

4. Issue Summary

Number Issue Location Severity
1 Reused generation token can collide under in-place rescaling KafkaSinkWriter.java:244-270, KafkaSink.java:55-58 Medium, non-blocking
2 Drop never-released numeric namespace compatibility KafkaSinkWriter.java:70-71, 253-257 Low, non-blocking
3 Same-partition Spark attempts fence each other (speculation) SparkDataWriterFactory.java:68, SeaTunnelSparkDataWriterFactory.java:69 Low, non-blocking

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers: none in source. The exact-head CI (the contributor's fork run for d8143b58) was still queued or running when I looked, so merge must wait for it to pass.
  2. Recommended non-blocking fixes: Issue 1 (document or guard the same-generation case, plus one regression), Issue 2 (remove unreleased numeric compatibility), Issue 3 (one doc sentence).
  3. Overall assessment: The earlier recovery gaps are closed with a coherent, engine-neutral design and good unit coverage. Thank you for the careful iterations; I am happy to approve once CI is green and the points above are considered.

@zephyr45

Copy link
Copy Markdown
Author

Thanks @DanielLeens — I addressed all three non-blocking recommendations in 21d4cb19.

  1. Same-generation in-place rescaling: when a writer is assigned another index's base namespace from the same sink generation, it now fences that assigned namespace but writes under a deterministic relocation namespace (...r<current-writer>). A retry from the same checkpoint derives and fences the same relocation namespace. A later stateless writer can therefore reuse its base slot without fencing the relocated live writer. The derivation also avoids any relocation namespace already present in the assigned states. The regression models same-generation 3 -> 2 -> 3: writer 1 receives g...w2, relocates it, and stateless writer 2 safely uses g...w2.
  2. Unreleased numeric compatibility: removed the numeric writer-namespace parser and exact-index branch. Tests now use only the final generation-scoped namespace plus the genuinely released legacy <prefix>-<checkpoint> form.
  3. Spark speculation: documented in both English and Chinese that Kafka exactly-once on Spark requires spark.speculation=false (the default), because concurrent attempts for one partition share a writer namespace.

Validation on Java 11:

  • Kafka connector unit suite: 146 passed; KafkaSinkWriterTest 14/14.
  • Documentation checks: 7 run, 0 failures/errors (3 skipped).
  • Affected 16-module dependency reactor: package succeeded.
  • Repository-wide spotless:apply: passed.
  • Repository-wide skip-tests verify: passed.
  • git diff --check: passed.

The exact-head Build is queued at https://github.com/zephyr45/seatunnel/actions/runs/41218673502 (head 21d4cb19869a7875f52ba5035e20f177599feaaa).

@SEZ9

SEZ9 commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator

@zephyr45 Thanks for the updates in d8143b58 and 21d4cb19.

From your description, the generation token and job-level generated transaction_prefix created once in KafkaSink sound like the right shape for the stateless-writer fencing, Spark task-retry, and omitted-prefix scale-down concerns, and the deterministic relocation namespace with the 3 -> 2 -> 3 regression is the scenario I wanted modeled. I have not yet verified these against the diff, so a few things would help me close out the earlier points:

  1. Flink scale-down restore: now that the modulo assumption is gone, which test exercises a contiguous-chunk ListState redistribution (e.g. one writer receiving states for two adjacent indices) and confirms restore succeeds rather than throwing?
  2. Omitted transaction_prefix scale-down: which test covers restore with mixed historical per-writer generated prefixes plus the new job-level prefix?
  3. Legacy shared-namespace fencing: is the concurrent probe-chain growth with parallelism (every restored writer fencing the same <prefix>-<checkpoint> namespace and bumping epochs its siblings observe) addressed in either commit, or still open? If open, a short note on the intended approach is fine for this PR.
  4. Docs: please confirm the transaction_prefix option row (not only the Semantics paragraph) describes the new ID shape, and that the rescaling claim is scoped to the engines where it holds.
  5. Please report back once the queued run at https://github.com/zephyr45/seatunnel/actions/runs/41218673502 finishes for head 21d4cb19869a7875f52ba5035e20f177599feaaa.

I'll do a final pass once those are in.

@github-actions github-actions Bot added the Spark label Nov 1, 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.

Thanks for the detailed recovery work, @zephyr45, and for the concrete questions, @SEZ9. I re-read the complete 14-file diff at 7887e90947, including the later checkpoint-qualified relocation fix, the final docs, the writer/committer path and both Flink adapters. The earlier functional recovery blockers are closed in this head. Sorry for missing two items in my last review: the core-parser contract and the new batch test's completion condition below are carryovers from the previous version, not newly introduced functional regressions. I have checked that both still apply here.

What Problem Does This PR Solve?

  • User pain: Parallel exactly-once Kafka sink writers sharing a configured prefix opened the same transaction IDs and fenced each other. Naive per-index suffixes also fail when restored state moves between writers.
  • Fix approach: Create the job prefix and generation once in KafkaSink, give writers separate namespaces and contiguous sequences, adopt/fence assigned checkpoint namespaces during recovery, relocate moved same-generation base namespaces, and give Spark retries a stable partition identity.
  • One-sentence summary and example: Writers 0 and 1 can use one configured prefix without sharing a transaction, and a 3-to-2 restore cleans all assigned old namespaces before opening new work.

1. Code Change Review

1.1 Core Logic Analysis

KafkaSink now owns serialized prefix/generation fields. KafkaSinkWriter derives a restore plan, parses each state's own job prefix, selects or relocates a namespace, fences assigned/current namespaces and advances a sequence independently of checkpoint IDs. KafkaTransactionSender distinguishes the checkpointed job prefix from the operating namespace. Both Spark writer factories use partitionId.

Before:

restoreState(kafkaStates); // only first state
new KafkaTransactionSender<>(transactionPrefix, properties);
beginTransaction(generateTransactionId(transactionPrefix, lastCheckpointId + 1));
// Spark context used taskId, which changes on retries.

After:

RestorePlan plan = restoreState(states, generation + "w" + writerIndex, writerIndex);
// Same-generation moved base:
return restoredWriterNamespace + "r" + currentWriterIndex + "c" + restoredCheckpointId;
// Fence assigned namespaces from saved sequence + 1, and the current namespace.
nextSequenceByPrefix.forEach(transactionSender::abortTransaction);
// Snapshot keeps the real checkpoint ID, but transaction sequences stay contiguous.
currentTransactionSequence++;

Complete affected flow:

Factory creates KafkaSink(config,catalog)
 -> choose job prefix + generation once; serialize sink in execution graph
 -> Zeta restored logical vertices: DAGUtils.restoreLogicalDag [57-69]
 -> checkpoint coordinator redistributes old states by current action parallelism [390-432]
 -> SinkFlowLifeCycle.restoreState [380-408]: deserialize state, createWriter/restoreWriter
 -> KafkaSink -> KafkaSinkWriter
    -> parse all assigned state before producer creation [356-405]
    -> empty state: generation/index namespace, sequence 1
    -> non-legacy: prefer exact fresh match, otherwise deterministic assigned namespace
       -> same generation + moved base: checkpoint-qualified relocation, sequence 1
       -> otherwise adopted namespace, max saved sequence + 1
    -> legacy-only: adopt saved job prefix, create writer namespace
    -> abortRestoredTransactions [336-353]
       -> per namespace min(next saved sequence); include current namespace
       -> KafkaTransactionSender.abortTransaction [193-210]
          -> initialize a temporary producer per ID, fence old epoch, close in finally
          -> stop at first previously unused ID
    -> begin current transaction -> normal row serialization/send
 -> barrier: prepareCommit flushes/checks async failures; capture transaction ID/producer epoch
 -> snapshotState stores KafkaSinkState(actual ID,job prefix,real checkpoint ID,properties)
 -> increment sequence and begin next transaction
 -> KafkaSinkCommitter resumes the actual saved producer/transaction [45-87]
    -> commit/abort -> close producer

Flink common Sink.createWriter [78-91]
 or Flink 1.20 restoreWriter [141-161]
 -> unwrap engine-assigned ListState -> KafkaSink.restoreWriter (no modulo assumption)
Spark 2.4/3.3 writer factory -> stable partitionId context -> same serialized sink token
 -> task retry reuses/fences that partition namespace

Key findings:

  1. The normal exactly-once path reaches the isolation fix. Non-transactional senders retain their behavior; the snapshot DTO/serializer is unchanged.
  2. Recovery parses each saved prefix independently, handles contiguous and modulo assignments, and does not impose Zeta's remap rule on Flink.
  3. Contiguous sequences remove the former scale-up 1,10,... cleanup hole. Fencing begins after the saved sequence, preserving the restored checkpoint's pending commit transaction itself.
  4. Checkpoint-qualified relocation (...r1c4, later ...r1c6) prevents the repeated-rescale namespace collision; one old state belongs to one restoring writer. This relies on normal engine state assignment and stopping the previous attempt, not arbitrary concurrent independent submissions.
  5. This is a focused connector recovery protocol plus the necessary Spark identity correction. Tests model the supported ownership invariants; they do not prove every scheduler/recovery topology by execution.

Replies to @SEZ9's latest questions:

  • Flink contiguous assignment: shouldFenceContiguouslyAssignedFlinkNamespacesAfterScaleDown supplies writer 0 the adjacent w0/w1 states at parallelism 2 and checks cleanup and successful adoption.
  • Mixed generated prefixes: shouldRestoreMixedGeneratedPrefixesAfterScaleDown parses both historical saved prefixes and checks the adopted prefix in the next snapshot. New omitted-prefix retries are separately covered by shouldReuseGeneratedPrefixWhenStatelessWriterRetries, including sink serialization.
  • Legacy shared-prefix probe growth: still possible across restoring writers; +1 to your earlier Issue 5 (Issue 6 is its duplicate). It remains a non-blocking efficiency concern. Deduplicating locally does not coordinate separate restoring tasks. A blanket "only subtask 0 cleans" is unsafe for distinct historical prefixes that subtask 0 never receives; any follow-up must establish ownership per distinct legacy prefix.
  • The option row now links the opaque <prefix>-<writer>-<sequence> shape in both languages. The latest connector paragraph explicitly scopes recovery/rescaling to Zeta and Flink; Spark speculation is separately disabled by documented requirement.
  • The queued run for 21d4cb19 is now an older-head result. Current-head Build is 41300574820, queued/incomplete at this check. I have not treated the older result or the author's local counts as acceptance of 7887e90947.

My earlier recommendations 1-3 are addressed: retained-generation relocation, removal of never-released numeric namespace compatibility, and Spark speculation guidance. The later 873a7537 adds the checkpoint discriminator and repeated-Flink-rescaling regression; that is included in this complete review.

1.2 Compatibility Impact

Partially incompatible, documented. Transactional IDs change, so ACLs and monitoring that match the old complete shape need migration; retain access to old IDs while restoring legacy checkpoints. Configuration names/defaults and state serialization fields remain unchanged. Genuine released shared-prefix state is supported; intermediate unmerged numeric-ID shapes need no compatibility branch. The sink's additional serialized fields do not establish cross-version rolling execution-graph compatibility; regenerate deployment graphs on upgrade and stop the old attempt. Distinct concurrent jobs still require distinct configured prefixes. Both incompatible-change pages describe ID migration.

1.3 Performance and Side Effects

No additional per-record coordination is introduced. Restore allocates a plan/map proportional to assigned states and performs broker initialization/close calls per distinct namespace and probed transaction. Legacy concurrent probing can amplify that work as described above. Contiguous sequences are important to bound cleanup by real historical usage. Temporary producers close in finally; normal producer transitions/async-error handling are retained. Retries deliberately reuse namespaces; independent submissions without restored state have a new token and can leave older transactions to broker timeout. Concurrent speculative Spark attempts are unsupported and must remain disabled. No new checkpoint lock, engine resource reservation or network protocol is added.

1.4 Error Handling, Logging and Formal Findings

Malformed/foreign saved IDs fail before creating producers, with transaction/checkpoint or prefix context. Existing asynchronous send failures still propagate through prepareCommit. The changed code does not add payload/credential logging. The following two carryover omissions are the complete remaining numbered findings for this head; earlier functional requests are not reopened.

Issue 4: Document the core restore parser and the distinct sequence/checkpoint contract

  • Location: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:356,423-429.
  • Description: parseRestoredTransaction implements the accepted on-state ID grammar, legacy detection and per-state prefix ownership, but has no method contract. The non-trivial state carrier also contains both transactionSequence and checkpointId without explaining that only the latter qualifies relocation, while cleanup advances the former. The broader restore-plan comment does not specify these parser/state-field constraints.
  • Potential risk: Future recovery changes can conflate checkpoint IDs with contiguous transaction sequences or accidentally broaden accepted namespace shapes, the exact boundaries this fix depends on.
  • Best improvement: Add a short parser Javadoc describing accepted released-legacy/current forms, per-state prefix validation and fail-before-producer behavior; document sequence versus checkpoint purpose on the carrier. Add a brief grammar/relocation note near the namespace pattern/decision helper. No functional rewrite is requested.
  • Severity: Medium; required core recovery-contract documentation.
  • Already raised by another reviewer: No. This was present in the previous head and I missed it, as acknowledged above.

Issue 5: The new batch regression asserts after an idle-poll cutoff rather than expected-data completion

  • Location: seatunnel-e2e/seatunnel-connector-v2-e2e/connector-kafka-e2e/src/test/java/org/apache/seatunnel/e2e/connector/kafka/KafkaIT.java:2326-2333; helper at 3032-3071.
  • Description: The new parallel batch test reads once and immediately asserts the set/count. The reused consumer helper may stop after 20 consecutive empty 100 ms polls without reaching its captured visible end offset. Under a delayed fetch, the one-shot assertion can observe a partial/empty list even though the committed job output is correct. Successful job completion establishes commit completion, not a deadline for this separate consumer's fetch.
  • Potential risk: Timing-sensitive CI failure in the new regression, especially under a slow broker/runner; this is not evidence that the sink loses rows.
  • Best improvement: Await the expected set and exact count with a bounded condition wait (as the streaming assertions already do), or make the reader await reaching the captured visible end offset with an explicit deadline and diagnostic failure. Keep the exact duplicate-count assertion.
  • Severity: Medium; stability risk, non-blocking recommendation rather than a demonstrated high-probability flake.
  • Already raised by another reviewer: No. This test usage existed in the previous head and was missed in my last stability assessment.

2. Code Quality Assessment

2.1 Coding Standards

The prefix/generation fields, restore ownership and temporary-producer behavior have useful comments. Issue 4 completes the core parser/state contract required for this recovery code. The new test class has a distinct writer-ownership focus; it exercises real writer/sender logic while mocking only the broker producer boundary. Headers/imports and scope are consistent.

2.2 Test Coverage and Stability

The writer tests cover parallel IDs, genuine legacy restore, contiguous and modulo assignments, mixed saved prefixes, malformed state, stateless retries, sink serialization, checkpoint jumps, namespace reuse and repeated rescaling with checkpoint-qualified relocations. Spark 3.3 verifies partition versus task ID. The broker IT adds a two-partition parallel batch job checking all 100 distinct records and count, and the existing Zeta streaming restore now populates three partitions and restores 3-to-2.

Stability rating: At risk (non-blocking). Issue 5 concerns the new batch test's one-shot read completion. Writer tests use fixed IDs and scoped constructor mocks/try-with-resources, with no sleep, ports or external services. Topics are unique and registered for class cleanup. The modified restore test uses Awaitility for data assertions, but retains its pre-existing discarded async-job futures; this review does not claim new failure-propagation coverage there. The restore IT remains disabled on Flink/Spark, so mocked Flink assignment is source-level coverage, not a broker-backed Flink rescaling execution. No local tests were run by me.

2.3 Documentation

EN/ZH connector rows and semantics align on opaque writer IDs, contiguous sequences, ACL migration, old-attempt shutdown and Spark speculation. Upgrade pages record the incompatible ID shape. The current connector docs appropriately name Zeta/Flink for state redistribution rather than promising Spark rescaling coverage.

3. Architectural Assessment

3.1 Solution Quality

Focused long-term fix: keep job prefix, assigned namespace and transaction sequence separate. The checkpoint-qualified relocation is more complex than an index suffix, but directly addresses repeated state movement.

3.2 Maintainability

The restore plan makes ownership explicit. Complete the parser/state comments so the sequence/checkpoint distinction survives later cleanup. Avoid collapsing them back into one counter.

3.3 Extensibility

The connector consumes the states actually assigned by an engine and does not embed a distribution algorithm. Any future legacy-cleanup optimization needs a per-prefix cross-task ownership protocol, not an assumed subtask index.

3.4 Historical Compatibility

Released legacy shared IDs remain readable and cleanable. ID ACL migration and deployment-graph regeneration require operator attention; no executed upgrade/rescale certification is claimed from these source checks alone.

4. Issue Summary

Number Issue Location Severity
4 Missing parser/state protocol contracts KafkaSinkWriter.java:356,423-429 Medium
5 One-shot consumer result after idle cutoff KafkaIT.java:2326-2333 Medium, non-blocking

Earlier numbered recommendations 1-3 are resolved. The shared legacy-probing note remains attributed to @SEZ9 rather than duplicated as another finding.

5. Merge Conclusion

Conclusion: Can merge after fixes

  1. Blockers (must fix): Issue 4: finish the small recovery-contract comments. Exact-current-head CI and effective repository approval remain gates. There is no remaining functional source blocker identified in this pass.
  2. Recommended improvements (non-blocking): Issue 5: await expected consumer data to reduce timing sensitivity. +1 to @SEZ9's legacy-probe efficiency follow-up; coordinate distinct historical prefixes safely if optimizing it.

Overall assessment: The functional ownership/retry changes answer the earlier review concerns, including the latest repeated-rescale case. I agree with the direction of @SEZ9's final-pass questions and have answered each from the actual head. The two carryover omissions above are explicitly mine; they are not presented as new regressions caused by your latest fixes.

Alternatives: Keep the current adopt/relocate scheme and add the contracts (preferred). Rejecting rescaling or returning to bare subtask IDs would remove supported behavior or recreate fencing, so neither is a better minimal implementation. An engine coordinator for legacy cleanup is a larger optional follow-up.

Gate handling: Current-head Build is incomplete, not a diagnosed source failure; no failing lane or verified upstream fix currently supplies a sync-first cure. Behind/diverged is recorded metadata. The Apache head rollup is empty at this snapshot, so fork completion and repository adoption must be distinguished. Daniel has READ permission: this technical COMMENT is not an effective write-level approval/dismissal.

Verification scope: Local fetch/isolated branch, full diff and real caller/serializer/committer reads with Git; 14 files, +1062/-50; git diff --check returned 0. No local builds, unit/E2E tests, broker jobs or runtime validation were performed by me.

Snapshot 2026-11-01T12:37:04.453467+00:00: head 7887e909479040404106b5fa36fbe8c9698f7b8a, base dev; compare diverged, ahead 7 / behind 16; merge blocked / BLOCKED, review decision REVIEW_REQUIRED. Drift is recorded separately; it does not itself request synchronization.

@zephyr45

zephyr45 commented Nov 1, 2026 •

Copy link
Copy Markdown
Author

Final review follow-ups are pushed in ba97d640. Resolved the remaining points from the latest review: - Added the transaction-ID grammar and restore-parser contract documentation in KafkaSinkWriter, including the explicit distinction between the contiguous transaction sequence and the engine checkpoint ID. - Hardened the parallel exactly-once batch E2E: exact set/count assertions now run inside a bounded Awaitility retry, so the test no longer treats one consumer read with a 2-second idle cutoff as the final broker state. - Corrected the PR description to the current counts: 147 Kafka connector tests and 15 KafkaSinkWriterTest cases. Current-head verification: - Kafka connector unit suite on Java 11: 147/147 passed. - KafkaSinkWriterTest: 15/15 passed. - Zeta + real Kafka: parallel exactly-once batch and 3-to-2 streaming restore: 2/2 passed. - Spark + real Kafka: parallel exactly-once batch on Spark 2.4.6 and 3.3.0: 2/2 passed. - Scoped Spotless for both changed files and git diff --check: passed. - Merge-tree check against current origin/dev: clean. @SEZ9, could you please re-review and dismiss the outstanding change request if these fixes satisfy it? @DanielLeens, a final maintainer review would also be appreciated.
Exact-head follow-up: 35110606 contains only the Spotless-required blank line identified by the fork build. Module-relative Spotless checks pass for both changed files. The fresh exact-head build is running at https://github.com/zephyr45/seatunnel/actions/runs/41336107891; license, dead links, code style/specification, sanity, and Helm checks are already green with no failures reported so far.

@SEZ9

SEZ9 commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the follow-up and for pushing ba97d640 plus the Spotless-only 35110606. Yes, I'll re-review the current head; here is what I need before I can dismiss the outstanding change request.

Your summary covers the transaction-ID grammar / restore-parser documentation in KafkaSinkWriter, the Awaitility-bounded E2E assertions, and the PR description counts. What I can't yet map from the comment is how each of the previously raised findings landed, so please confirm (a short per-item note is enough):

  1. Flink scale-down restore (F1) – validateRestoredStateOwner previously assumed Zeta's modulo redistribution; Flink's ListState repartitioning hands out contiguous chunks. Your verification lists Zeta 3-to-2 and Spark runs, but no Flink restore. Is the owner check now engine-agnostic, or is it scoped to Zeta only? If the latter, that scope should be stated explicitly.
  2. Unconfigured transaction_prefix (F2) – with per-writer random prefixes, does restoreState() still reject mixed prefixes on scale-down, or is that path handled now?
  3. Scale-up writer with no state (F3) – does a fresh writer still start its sequence at 1 regardless of the checkpoint ID, leaving a failed first attempt unfenced until the next checkpoint? The "contiguous transaction sequence vs. engine checkpoint ID" doc you added sounds related, so please spell out the intended behavior.
  4. Spark task retries (F4) – since the subtask index is the Spark taskId, how is the previous attempt's open transaction fenced on retry? The Spark batch E2E passing doesn't by itself exercise that.
  5. Concurrent legacy-namespace fencing (F5/F6) – is the repeated probing across restoring writers still present, or was it changed/deemed acceptable?
  6. Docs (F7) – was the transaction_prefix option row in docs/en/connectors/sink/Kafka.md aligned with the new ID-shape text and the engine scope of the rescaling claim? Your changed-file list mentions only two files, so I want to be sure this wasn't dropped.

Also, the exact-head run at 41336107891 was still in progress when you posted; please drop a note once it completes.

Once I have those answers I'll do the re-review and, if everything checks out, dismiss the change request.

@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.

Thanks a lot for the follow-up commits, @zephyr45. I re-read the complete diff at 351106062b6 (14 files) and the two commits since my last pass (ba97d640, 35110606). The two carryover points from my previous round (the restore-parser contract and the one-shot batch assertion) are both closed in this head. I found no new source-level blocker.

What Problem Does This PR Solve?

  • User pain: With semantics = EXACTLY_ONCE and parallelism > 1, every Kafka sink writer opened the same <prefix>-<checkpoint> transactional ID, so writers fenced each other with ProducerFencedException (#13044).
  • Fix approach: KafkaSink creates the job prefix and a generation token once and serializes them with the sink. Each writer gets its own namespace and a contiguous transaction sequence. Recovery adopts and fences the namespaces actually assigned to the writer, relocates a moved same-generation namespace, and Spark now uses the stable partitionId as the writer index.
  • One sentence: Writers 0 and 1 can share one configured prefix without sharing a transaction, and a 3-to-2 restore fences every assigned old namespace before opening new work.

1. Code Change Review

1.1 Core Logic Analysis

What changed since my last review (7887e90947 -> 351106062b6):

// KafkaSinkWriter: documentation only
/** Parses one checkpointed transaction before any Kafka producer is created. ... grammar ... */
private RestoredTransaction parseRestoredTransaction(KafkaSinkState state) { ... }
private final long transactionSequence;  // documented: independent of engine checkpoint ID
private final long checkpointId;         // documented: only qualifies relocation
// KafkaIT: one-shot read -> Awaitility.await().atMost(2 min).untilAsserted(set + exact count)

Runtime path (unchanged from the previous round, re-checked on this head):

KafkaSink (job prefix + generation chosen once, serialized with the sink graph)
 -> engine redistributes old KafkaSinkState entries to restoring writers
 -> KafkaSinkWriter ctor
    -> restoreState(): parse every assigned state against its own saved job prefix (fail before any producer)
       -> empty: <prefix>-<generation>w<index>, sequence 1
       -> non-legacy: prefer exact fresh match, else deterministic assigned namespace
          -> same generation + moved base: relocate to ...r<idx>c<cp>, sequence 1
          -> otherwise adopted namespace, max saved sequence + 1
       -> legacy only: adopt saved prefix, fresh writer namespace
    -> abortRestoredTransactions(): per namespace, min(saved sequence + 1), plus the current namespace
       -> KafkaTransactionSender.abortTransaction probes until the first unused ID
    -> beginTransaction(<namespace>-<sequence>)
 -> snapshotState(): KafkaSinkState(actual ID, job prefix, real checkpoint ID); sequence++
Spark 2.4 / 3.3 writer factories: DefaultSinkWriterContext(jobId, partitionId, parallelism)

Key findings:

  1. The default exactly-once path reaches the fix (KafkaSemantics.EXACTLY_ONCE branch of the constructor); non-transactional senders are untouched and the KafkaSinkState fields are unchanged.
  2. The restore parser is now documented in the class itself (accepted legacy form, current form with the optional relocation suffix, per-state prefix validation, fail-before-producer). That closes my earlier Issue 4.
  3. The batch E2E now wraps the set and exact-count assertions in a bounded Awaitility wait (2 minutes), which closes my earlier Issue 5. The duplicate-count assertion is kept, so the test did not get weaker.
  4. For information: the Spark change (taskId -> partitionId) lives in the shared Spark translation writer factories, so it changes getIndexOfSubtask() for every sink running on Spark, not only Kafka. Since partitionId is in [0, parallelism) and stable across attempts, this matches what the SinkWriter.Context contract describes, and I did not find a sink in this diff that depends on the old value. It is worth keeping in the PR description for reviewers.

1.2 Compatibility Impact

Partially incompatible, and documented. Transactional IDs change shape (<prefix>-<writer>-<sequence>), so ACLs or monitoring that match the old shape need updating; both incompatible-changes.md pages (EN and ZH) say so. Option names and defaults are unchanged. Released legacy shared-prefix checkpoints are still readable and fenced (shouldFenceLegacyTransactionsBeforeStartingWriterScopedTransactions, shouldKeepLegacyPrefixWhenConfiguredPrefixWasOmitted). The two extra serialized fields on KafkaSink mean the execution graph should be regenerated on upgrade, which the docs state.

1.3 Performance and Side Effects

No per-record cost is added. Restore creates short-lived producers per distinct namespace and per probed transaction ID and closes them in finally. The only amplification is the legacy shared-prefix probe described in Issue 1 below, which is bounded to the first restore after upgrading from a legacy checkpoint.

1.4 Error Handling, Logging and Issues

Malformed or foreign saved IDs fail with transaction/checkpoint/prefix context before any producer is created. Asynchronous send failures still surface through prepareCommit as before. No credentials or payloads are logged.

Issue 1: Concurrent fencing of the legacy shared namespace grows with parallelism

  • Location: KafkaSinkWriter.java abortRestoredTransactions and KafkaTransactionSender.abortTransaction.
  • Problem: For legacy checkpoints every restoring writer holds the same <prefix>-<checkpoint> and probes the same namespace; a sibling's initTransactions() registers an ID and pushes the next writer one probe further, so startup does about N(N+1)/2 temporary producer round-trips instead of N.
  • Risk: Wasted broker round-trips on the first restore from a legacy checkpoint only. Correctness is preserved.
  • Best improvement: Optional follow-up: fence each distinct legacy prefix once. A blanket "subtask 0 only" rule would miss distinct historical generated prefixes that subtask 0 never receives, so any optimization needs per-prefix ownership.
  • Severity: Low (non-blocking).
  • Raised by another reviewer: Yes, +1 to @SEZ9 (his Issues 5/6); you already explained the trade-off in your earlier comment.

2. Code Quality

2.1 Coding Standards

Fields and non-trivial helpers now carry comments explaining why (generation token, relocation, sequence versus checkpoint). Imports and license headers are fine. Nothing missing that I would block on.

2.2 Tests and Stability

KafkaSinkWriterTest has 15 cases covering: parallel isolation across checkpoints, legacy restore, contiguous (Flink-style) and modulo (Zeta-style) assignment after scale-down, mixed generated prefixes, malformed namespaces, stateless-writer retry, generated-prefix reuse through sink serialization, relocation, repeated rescaling and checkpoint-ID jumps. SparkSinkTest checks that partitionId (not taskId) is the writer index. KafkaIT adds the parallel batch test and a 3-to-2 Zeta restore.

Flaky-stability rating: Stable. Writer tests are deterministic with fixed IDs and scoped mocks; the new batch test now uses a bounded condition wait instead of a single idle-poll read; topics are unique. One note, not a blocker: the Flink path is verified by a source-level mock of the assignment, not by a broker-backed Flink rescale.

2.3 Documentation

EN and ZH option rows and the Semantics paragraph agree (opaque writer component, contiguous sequence, ACL migration, old attempt must be stopped, Spark speculation must stay off, recovery claim scoped to Zeta and Flink). The incompatible-changes pages in both languages are updated.

3. Architectural Soundness

3.1 Solution Quality

This is a precise fix at the right layer: the collision comes from the connector composing transactional IDs, and the connector now owns the namespace. The Spark index change is a small, necessary identity correction in the translation layer.

3.2 Maintainability

The restore plan, the parser contract and the sequence/checkpoint distinction are now written down, which is what keeps later edits from collapsing them into one counter.

3.3 Extensibility

The connector consumes whatever states an engine assigns and embeds no distribution algorithm, so it does not depend on Zeta's modulo rule.

3.4 Historical Compatibility

Released legacy IDs stay readable and cleanable. No executed upgrade or rescale certification is claimed from this source review.

4. Issue Summary

Number Issue Location Severity
1 Legacy shared-namespace probes grow with parallelism KafkaSinkWriter.java abortRestoredTransactions Low, non-blocking

5. Merge Recommendation

Conclusion: Ready to merge

CI (exact head, fork run): The fork's Build 41336107891 ended red with three failing jobs, none in code touched by this PR:

  • unit-test (17, windows-latest): RestApiSubmitJobStartWithSavePointTest.setUp "Node failed to start" in seatunnel-engine-server.
  • unit-test (11, ubuntu-latest): SeaTunnelClientTest.testGetMultiTableJobMetrics:703 in seatunnel-engine-client.
  • all-connectors-it-2 (11, ubuntu-latest): Aerospike6IT.testAerospikeSink:121.

The Kafka-relevant lanes passed in the same run: kafka-connector-it on JDK 11 and 17, and KafkaSinkWriterTest (15/15) and SparkSinkTest (2/2) inside the unit-test lanes. This PR does not touch engine-server, engine-client or the Aerospike connector. Please re-run only the three failed jobs (not the whole workflow). The branch is 16 commits behind dev, but none of those commits touch the Kafka sink or the Spark writer factories, so no sync is needed for this PR.

  1. Blockers: none from source review. The outstanding change request from @SEZ9 still needs his re-review, and the exact-head CI needs a green re-run of the three jobs above.
  2. Recommended non-blocking: Issue 1 as a follow-up; mention the shared Spark writer-index change (finding 4) in the PR description.

Answers to @SEZ9's six questions, from the actual head: (1) the owner check is gone; recovery is engine-neutral and shouldFenceContiguouslyAssignedFlinkNamespacesAfterScaleDown covers contiguous assignment. (2) Mixed saved prefixes restore; each state is parsed against its own prefix (shouldRestoreMixedGeneratedPrefixesAfterScaleDown). (3) A stateless writer fences its own namespace from sequence 1 (shouldFenceEveryStatelessWriterTransactionAfterScaleUpRetry). (4) Spark retries reuse the partitionId-based namespace and fence it (SparkSinkTest). (5) Legacy probing is still present and is Issue 1 above. (6) The option row is updated in EN and ZH.

Overall this is a careful, well-tested fix. Thank you for the thorough iterations, @zephyr45.

@zephyr45

zephyr45 commented Nov 2, 2026

Copy link
Copy Markdown
Author

@SEZ9 Thanks for the concrete final-pass questions. I reproduced the additional Flink counterexample before changing production code, and pushed the coherent fix in 97516b977. Here is the requested ledger.

  1. F1 — ownership rule, supported engines, and repeated rescaling. The connector still has no modulo/index ownership rule; it consumes exactly the states assigned by the engine. Existing regressions cover Zeta-style modulo and Flink-style balanced contiguous assignments. The new 3 -> 4 -> 3 -> 4 -> 3 regression models the common Flink adapter's writer-local counter restart. On the previous logic it failed at the final 4-to-3 restore with duplicate namespace shared-prefix-7-gtestw3r2c1. The fix replaces checkpoint-qualified relocation with a checkpoint-independent recovery revision: <base>_r<revision>w<current-index>. Same-recovery retries derive the same namespace; a later recovery sees and advances the checkpointed revision. FlinkSinkWriterTest also records that fresh/restored writers legitimately have divergent counters.

  2. F2 — mixed generated prefixes. Every KafkaSinkState is parsed relative to its own saved transactionIdPrefix; no common-prefix assumption was reintroduced. shouldRestoreMixedGeneratedPrefixesAfterScaleDown remains green, along with legacy/current mixed-path coverage. Malformed or overflowing namespace revisions fail before producer construction.

  3. F3 — contiguous sequences and stateless retry cleanup. Checkpoint IDs are no longer used for namespace identity or transaction sequence. Each namespace uses contiguous transaction numbers. Assigned old namespaces are probed from saved sequence n + 1, preserving pending checkpoint transaction n; the deterministic output namespace is probed from 1, so a stateless/recovery retry fences every transaction abandoned after the retained checkpoint. Coverage includes checkpoint jumps, omitted configured prefix, multiple abandoned IDs, and pending-transaction preservation.

  4. F4 — Spark retry identity and evidence boundary. Spark 2.4/3.3 use stable partitionId, not attempt-specific taskId, for the shared SinkWriter.Context index; the generation remains serialized in KafkaSink. The shared change affects all Spark sinks and is called out in the PR body. SparkSinkTest verifies the factory path; broker-backed parallel E2E passed on Spark 2.4.6 and 3.3.0. I am not describing that batch E2E as a broker-backed Spark crash/retry test.

  5. F5/F6 — concurrent legacy cleanup (one concern). This is not marked fixed. Multiple restoring tasks may probe the same released legacy prefix, increasing first-upgrade broker round-trips roughly quadratically while preserving correctness. Local map deduplication cannot coordinate tasks, and subtask 0 would miss historical generated prefixes assigned elsewhere. A safe optimization needs per-prefix cross-task ownership plus owner failover. Please explicitly confirm whether this low-severity startup optimization can remain a documented follow-up; this patch does not weaken cleanup to hide it.

  6. F7 — documentation and upgrade boundary. EN/ZH option rows retain the public opaque shape <prefix>-<writer>-<sequence>. Semantics document Zeta/Flink recovery scope, checkpoint-independent revisions, legacy fencing, and spark.speculation=false. Both incompatible-change pages require stopping the old attempt, rebuilding the execution graph from upgraded job configuration, restoring retained checkpoint/savepoint state, updating ACLs, and retaining legacy-ID access during the first restore. KafkaSinkState, configuration, public API/SPI, and dependencies remain unchanged; old serialized KafkaSink execution graphs are explicitly not supported.

  7. Additional Flink finding and cleanup hardening. The handoff counterexample was valid as a source-level/adaptor model, not a prior full Flink rescale deployment reproduction. The new recovery-revision invariant fixes it without extending engine APIs. Cleanup now also closes temporary producers when initTransactions() or beginTransaction() fails and preserves the original exception (close failures are suppressed), with two regressions.

Verification for 97516b977f7d65ef2096ac53376e1460ee8f61d4 content:

  • Kafka focused: 27/27; full connector: 152/152.
  • Flink common: 15/15; focused adapter regression: 4/4.
  • Spark 3.3 unit: 2/2; Spark 2.4 package: pass (no tests).
  • Kafka 7.0.9 broker E2E: Zeta 2/2 (parallel + 3-to-2 restore), Flink 4/4 (1.13.6/1.15.3/1.18.0/1.20.1 parallel), Spark 2/2 (2.4.6/3.3.0 parallel).
  • Docs: 7 executed, 0 failures/errors, 3 conditional skips; git diff --check and scoped Spotless pass.
  • Repository-wide Java 11 verify -DskipTests: pass. Exact-head GitHub CI is now running; I will post the final result and investigate/rerun only genuine failed jobs.

The PR description has been rewritten around the final invariant, migration procedure, shared Spark impact, evidence boundaries, and the explicit legacy-cleanup follow-up.

@SEZ9, please re-review this head and clear the outstanding change request if the answers and implementation are satisfactory. Your collaborator review is also the maintainer-side action still required; I am not requesting or performing a merge.

@zephyr45

Copy link
Copy Markdown
Author

@SEZ9 F1–F3 at head 117dc411:

  • F3: "Ended" was unclear, sorry. Code (d8143b58, b9ed7c12): a stateless writer starts at sequence 1, and initTransactions on that ID fences a failed first attempt before the first send. Tests: KafkaSinkWriterTest#shouldReuseGeneratedPrefixWhenStatelessWriterRetries, #shouldNotWalkStatelessWriterTransactionHistory. Docs (b9ed7c12, EN/ZH Kafka.md Semantics): a later sequence abandoned before any checkpoint can block read_committed until transaction.timeout.ms expires, the limitation you accepted here.
  • F1: Fixed in 585f69b7. validateRestoredStateOwner and its modulo check are removed; a writer fences every state the engine assigns it, so a Flink contiguous scale-down restore no longer throws. Tests: #shouldFenceContiguouslyAssignedFlinkNamespacesAfterScaleDown, #shouldFenceEveryAssignedWriterNamespaceAfterScaleDown.
  • F2: Fixed in 585f69b7. With transaction_prefix unset, each restored state is parsed with its own saved prefix and every namespace is fenced. Test: #shouldRestoreMixedGeneratedPrefixesAfterScaleDown.

@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.

Thanks, @zephyr45 and @SEZ9, for following the recovery boundaries through. I checked the current source for the specific questions: KafkaSinkWriterTest.java:140 covers two contiguously assigned namespaces in a Flink 3-to-2 restore; line 227 covers mixed generated prefixes without a configured prefix; the restore plan iterates all assigned transactions before adopting a deterministic advanced namespace. The stateless boundary is explicitly limited in Kafka.md:104: sequence one is fenced, but an abandoned later sequence with no retained checkpoint state can still block read_committed until Kafka's transaction timeout. This is not a claim of scanning unknown stateless history.

The CI fact in my previous review has also changed: the exact-head Build is successful, including the formerly incomplete LocalFile JDK 17 lane, job 135617113981. My previous full source review had no remaining source blocker, and these targeted questions do not reopen one. The earlier CI-only blocker is cleared, so I am changing my review to approve.

Merge recommendation: Can merge from Daniel's technical perspective.

Blocking source items: None.

Non-blocking suggestions: Existing validation limits and documented stateless timeout behavior remain. This does not assert that another reviewer has approved or replace an effective write-capable maintainer approval.

Checked unchanged head 117dc411e51af449798fc14b2e0f3fff0e2dae6d against dev: compare diverged, ahead 15 / behind 11. This drift is recorded independently; it does not by itself request synchronization. This is a discussion/CI follow-up, not another full source review. No local build, test or runtime execution was performed. Daniel has READ repository permission; effective maintainer approval/dismissal remains a separate repository gate. Checked 2026-11-20T12:05:54.019197+00:00.

@SEZ9

SEZ9 commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator

@zephyr45 thanks for the clear breakdown of F1–F3 at 117dc411. I have not checked these against the diff or run the tests myself, so I am recording them as reported rather than confirmed.

  • F1: You report this fixed in 585f69b7 by removing validateRestoredStateOwner and its modulo check, so a writer fences every state the engine assigns it. That approach matches the finding about the Flink contiguous scale-down restore.
  • F2: You report this fixed in 585f69b7 by parsing each restored state with its own saved prefix when transaction_prefix is unset and fencing every namespace, with #shouldRestoreMixedGeneratedPrefixesAfterScaleDown as the test. That approach matches the mixed-prefix finding.
  • F3: Thanks for clarifying "Ended". As you describe it, a stateless writer starts at sequence 1, and initTransactions on that ID fences a failed first attempt before the first send, which was the core of the finding. You also note that a later sequence abandoned before any checkpoint can still block read_committed until transaction.timeout.ms expires, and that this is documented in the EN/ZH Kafka.md Semantics section. If the docs state that, I don't expect to ask for more code on F3.

I'll confirm F1–F3 once I have gone through the diff.

Your comment covers only F1–F3, so could you post the same kind of short status for the rest at 117dc411?

  • F4: How are Spark task retries handled, given that the subtask index is the Spark taskId and each retry gets a new transactional namespace?
  • F5 / F6: Is the concurrent fencing of the legacy shared namespace by every restoring writer changed, or left as is?
  • F7: Is the transaction_prefix option row aligned with the Semantics paragraph, and is the engine scope of the rescaling claim stated?

For each one, "fixed in " or "left as is, because …" is enough.

@zephyr45

Copy link
Copy Markdown
Author

@SEZ9 All of F1–F7 at head 117dc411, in one place:

  • F1: Fixed in 585f69b7 (modulo owner check removed). Test: KafkaSinkWriterTest.java:140.
  • F2: Fixed in 585f69b7 (each state parsed with its own saved prefix). Test: KafkaSinkWriterTest.java:227.
  • F3: Fixed in d8143b58/b9ed7c12 (a stateless writer fences sequence 1). The remaining timeout case is documented in Kafka.md:104 (b9ed7c12).
  • F4: Fixed in 9e4aad72. Kafka uses getStableSubtaskIndex(), which is the partition ID on Spark, so a retry reuses and fences the same namespace. Tests: KafkaIT#shouldFenceAbandonedAttemptWithStableIndex, SparkSinkTest#shouldSeparateTaskIdentityFromStablePartitionAcrossRetriesAndEpochs.
  • F5/F6: Left as is: a one-time migration cost, tracked in [Improve][Connector-V2][Kafka] Coordinate legacy shared-prefix transaction cleanup #13298.
  • F7: Fixed in 7887e909/9e4aad72. The EN/ZH option row shows <prefix>-<writer>-<sequence>, and rescaling is scoped to Zeta/Flink.

DanielLeens checked F1–F3 against these lines and approved. Could you update your review for 117dc411?

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks, @SEZ9 and @Zephyr-Dawn. Daniel's existing approval of this unchanged head stands: the saved prefix is per restored state, modulo reuse was removed, and stateless sequence 1 has an explicit fence. I am not treating the later abandoned-sequence wait as immediately resolved; the documented Kafka transaction-timeout boundary still applies. Spark still depends on stable partition identity, and the separately tracked schema/option work should stay in #13298. The current Build is green. I cannot update another reviewer's opinion on their behalf, so @SEZ9 should make the requested final review-state decision independently.

Checked unchanged head 117dc411e51af449798fc14b2e0f3fff0e2dae6d against dev: compare diverged, ahead 15 / behind 14. This drift is recorded independently; it does not by itself request synchronization. This is a discussion/CI follow-up, not another full source review. No local build, test or runtime execution was performed. Daniel has READ repository permission; effective maintainer approval/dismissal remains a separate repository gate. Checked 2026-11-21T12:06:29.365986+00:00.

@SEZ9

SEZ9 commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator

@zephyr45 Thanks for putting F1–F7 in one place. To answer your question directly: I have not updated my review yet. I will re-check each finding against the commits and tests you cited at 117dc411 and then update it.

Going by your summary, this is where each finding stands for me:

  • F1 / F2: Removing the modulo owner check and parsing each restored state with its own saved prefix (585f69b7) is the fix I asked for. Both have tests, so I only need to confirm them at head.
  • F3: An explicit fence for a stateless writer at sequence 1 (d8143b58/b9ed7c12) covers the finding. I am fine with the remaining timeout case being documented rather than removed.
  • F4: Using getStableSubtaskIndex(), so that a Spark retry reuses and fences the same namespace (9e4aad72), addresses the finding. The two tests you named are the ones I will look at.
  • F5 / F6: Leaving these as a one-time migration cost is acceptable to me at LOW severity, on one condition below.
  • F7: Aligning the EN/ZH option row with <prefix>-<writer>-<sequence> and scoping the rescaling claim to Zeta/Flink (7887e909/9e4aad72) is what I asked for.

One thing I need from you: please confirm that #13298 explicitly records the F5/F6 behaviour. That is, every restoring writer fences the legacy shared namespace concurrently, so the probe chain grows with parallelism. If it does not say so yet, please add a short note there so the deferral is traceable.

@zephyr45

Copy link
Copy Markdown
Author

@SEZ9 #13298 described the overlap but didn't state the growth explicitly, so I added a note. Precisely: only writers assigned a legacy state probe the shared namespace, and the chain is shared only if the old job set transaction_prefix. Each such writer creates the first unused ID, so the next goes one ID further; the chain grows with the number of those writers (at most the smaller of old and new parallelism), and each retried restore repeats this. dev already probes this way; #13060 keeps it.

Full status at 117dc411:

  • F1/F2: Fixed in 585f69b7. Tests: KafkaSinkWriterTest.java:140, :227.
  • F3: Fixed in d8143b58/b9ed7c12; the timeout case is documented in Kafka.md:104.
  • F4: Fixed in 9e4aad72. Tests: KafkaIT#shouldFenceAbandonedAttemptWithStableIndex, SparkSinkTest#shouldSeparateTaskIdentityFromStablePartitionAcrossRetriesAndEpochs.
  • F5/F6: Left as is, tracked in [Improve][Connector-V2][Kafka] Coordinate legacy shared-prefix transaction cleanup #13298.
  • F7: Fixed in 7887e909/9e4aad72.

@SEZ9

SEZ9 commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator

@zephyr45 thanks for spelling that out. That explicit growth statement was what was missing for F5/F6, and I'm fine leaving both as is.

F5/F6

Rest of your status at 117dc411

  • F1/F2: Noted as fixed in 585f69b7 with the two KafkaSinkWriterTest cases. Nothing more from me.
  • F3: Noted as fixed in d8143b58/b9ed7c12. My understanding is that the remaining case is the abandoned-transaction wait bounded by the Kafka transaction timeout, which you documented at Kafka.md:104. I accept that as a documented limitation, but please correct me if that reading is wrong.
  • F4: Noted as fixed in 9e4aad72 with KafkaIT#shouldFenceAbandonedAttemptWithStableIndex and SparkSinkTest#shouldSeparateTaskIdentityFromStablePartitionAcrossRetriesAndEpochs.
  • F7: Noted as fixed in 7887e909/9e4aad72. One confirmation please, since the status doesn't say: does the doc change cover both halves, i.e. the transaction_prefix option row now matches the Semantics paragraph, and the rescaling claim states which engines it applies to?

That F7 confirmation is the only thing I still need from you. Once I have it, I'll make my final review decision on 117dc411.

@zephyr45

Copy link
Copy Markdown
Author

@SEZ9 F7: Yes, both halves, in EN and ZH Kafka.md:

  • The transaction_prefix row (EN line 66, ZH 63) gives <prefix>-<writer>-<sequence> and links to Semantics, which uses the same shape (EN 102, ZH 98).
  • Rescaling is scoped: "On Zeta and Flink, during stateful recovery or rescaling…" (EN 104, ZH 100). For Spark it makes no rescaling claim; it requires spark.speculation=false (EN 108, ZH 104).

One disclosure: the incompatible-change pages describe recovery and rescaling without naming engines. Only Zeta and Flink reach that path (Spark never restores sink writer state), but I can name them there too if you prefer.

F3: Your reading is right. The remaining case is a writer with no retained state that abandoned a later sequence before any checkpoint; it can block read_committed until transaction.timeout.ms (EN Kafka.md:104, ZH :100).

Rest, unchanged at 117dc411: F1/F2 fixed in 585f69b7; F4 fixed in 9e4aad72; F5/F6 left as is, tracked in #13298.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks for confirming both halves of the documentation update. On this head, docs/en/connector-v2/sink/Kafka.md:102-108 describes the prefix behavior, explicitly names Zeta and Flink for recovery/rescaling, and limits Spark to stable writer indexes with speculation disabled. The Chinese section carries the same scope. That supports the clarification you described; no new implementation change is claimed here. I agree with @SEZ9's separation of the legacy shared-prefix probe-chain work into #13298, provided this PR's documented recovery contract remains intact. My existing technical approval stands, with the separate maintainer approval gate still applicable. A matching engine qualifier in the incompatible-change note would improve consistency; it does not require an unrelated Kafka behavior patch.

@zhangshenghang

Copy link
Copy Markdown
Member

Thanks, that answers F7. The EN/ZH connector docs now agree. Please add the same Zeta/Flink qualifier to the incompatible-change notes, so the recovery/rescaling guarantee isn't read as applying to Spark. No implementation change needed; F5/F6 stay in #13298.

Name the engines in the EN/ZH incompatible-change notes so the recovery
and rescaling guarantee is not read as applying to Spark.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@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.

Thanks for aligning the migration notes with the connector docs. I re-reviewed the entire current head, including the Kafka recovery protocol, shared Context API and both Spark factories. The requested Zeta/Flink qualifiers are present in English and Chinese, and my source clearance stands.

What problem does this PR solve?

User pain: Parallel exactly-once Kafka writers sharing one transaction_prefix fence each other because they reuse the same transactional ID.

Fix: Persist a sink-level generation and job prefix, derive distinct writer namespaces, and recover/fence the namespaces actually assigned by restored state.

In one sentence: Parallel Kafka writers can use one job prefix without aborting their siblings. For example, writers 0 and 1 now open different IDs instead of both opening customer-export-1.

1. Code changes

1.1 Core logic

Complete runtime path:

KafkaSink construction -> resolve job prefix and generation once -> serialize sink with execution graph
  -> Zeta/Flink writer create/restore receives engine-assigned KafkaSinkState list
  -> KafkaSinkWriter.restoreState parses each state relative to its own persisted prefix before broker side effects
  -> adopt one assigned lineage -> advance saved recovery revision independent of checkpoint counters
  -> abortRestoredTransactions: assigned namespace sequence n+1 plus deterministic output namespace sequence 1
  -> KafkaTransactionSender initializes separate producers until first unused ID, closing each temporary producer
  -> begin output transaction -> write -> prepareCommit flush and async-failure check
  -> snapshotState saves full transactional ID/job prefix/checkpoint/properties, then advances contiguous transaction sequence
  -> existing Kafka committer publishes retained pending transaction n; recovery probes start after n
Spark 2.4/3.3 writer factory -> SparkSinkWriterContext: legacy getIndexOfSubtask=task attempt, stable index=partition
  -> Kafka consumes stable index; Doris and other sinks retain historical attempt-based identifiers
Fresh/stateless writer -> opens/fences sequence 1 only; absent later history remains bounded by broker transaction timeout.

Key findings and correctness:

The collision is on a normal parallel writer path, not only a malformed checkpoint. The current implementation separates the checkpointed job prefix from the writer-owned namespace and transaction sequence. The parser accepts the released shared-ID format plus the current generation/revision grammar, validates foreign/malformed/overflowing revisions before constructing producers, and uses each saved state's own prefix. No Zeta modulo-ownership assumption remains, so Flink contiguous assignments and historical generated mixed prefixes are accepted.

A same-recovery retry deterministically derives the same advanced namespace; a later recovery reads the revision from the saved full transaction ID and advances it again. The current writer index prevents restoring siblings from choosing one output ID, while revision advancement avoids repeated-rescale collisions when adapter checkpoint counters restart. Old saved transaction n is preserved for commit; probing n+1 fences abandoned later work. Fresh writers deliberately do not scan all historical IDs, avoiding an ever-growing scan on Spark micro-batches; later abandoned IDs with no retained state still wait for transaction.timeout.ms, as documented.

The shared API adds a default stable-index method and leaves getIndexOfSubtask unchanged. Both Spark factories preserve attempt identity for existing sinks and supply partition identity separately to Kafka, closing the previously demonstrated Doris label reuse regression. KafkaSink does not implement SupportMultiTableSink, and the unrelated SinkContextProxy override is absent from the complete current diff; this PR does not claim replica rescaling support. Temporary producers close on initialization/begin failures and preserve the original failure with cleanup failures suppressed.

Before:

writerTransactionId = transactionPrefix + "-" + checkpointId;
// Parallel writers could initialize the same transactional ID.

After:

String namespace = generateWriterNamespace(generation, context.getStableSubtaskIndex());
RestorePlan plan = restoreState(states, namespace, context.getStableSubtaskIndex());
abortRestoredTransactions(sender, plan);
sender.beginTransaction(generateTransactionId(plan.writerTransactionPrefix, plan.nextTransactionSequence));
// Snapshot persists the full ID; recovery advances its saved revision.

Current CI: Build 45184080151 is queued for head 32fb522. The earlier green run/approval was for 117dc41, not proof for this head. Compare against dev: ahead 16 / behind 24, diverged. This drift is recorded separately; no failed current-head lane establishes a sync-first cure, so I am not asking for unrelated changes. A write-capable maintainer must handle effective approval/dismissal and queue entry.

1.2 Compatibility

Partially incompatible externally: transactional-ID ACLs/monitoring must permit the new opaque writer/sequence shape, and operators must stop the old attempt, rebuild the execution graph with the upgraded version, then restore retained state. Old serialized execution graphs lack the new sink fields and are explicitly unsupported. KafkaSinkState fields/serialization, configuration names/defaults and existing getIndexOfSubtask semantics are preserved; the new Context method has a compatible default. Spark speculation must remain false. The connector and migration docs cover these boundaries in both languages.

1.3 Performance and side effects

Per-writer namespace selection and state parsing occur during initialization/restore; per-row serialization and sending do not acquire new global locks. The sink-level UUID/prefix are small graph fields. Stateful probing creates/closes temporary network producers until an unused ID; legacy shared-prefix cross-writer duplication and retry-growth remain the accepted pre-existing efficiency follow-up in #13298, not a solved bounded scan. Fresh construction fences ID 1 without extending full history. The two Doris dependencies are test-scoped and support production label regressions, not deployed runtime dependencies.

1.4 Errors, logging, and findings

No new source-level blocker found. Exceptions must still reach the existing job failure path; this review does not substitute for current-head CI.

I reconciled @SEZ9's CHANGES_REQUESTED F1-F7 with all inline discussions and later comments: F1/F2 are fixed in the engine-neutral parser/restore tests; F3 is the explicit stateless timeout boundary; F4 uses the new stable index while preserving Doris identities; F5/F6 remain accepted deferred work in #13298; F7 now includes engine qualifiers in both migration notes. I agree with @nzw921rx that Kafka multi-table support is outside scope; removal of the proxy override addresses that concern. Their historical change requests remain their own review decisions and are not silently dismissed by Daniel's technical clearance. No new numbered source blocker is added.

2. Code quality

2.1 Conventions

Reviewed all changed files for license, imports, naming, core-method and state-field comments. No additional convention blocker found.

2.2 Test coverage and stability

Stability rating: Stable. Read every changed unit, adapter and KafkaIT test. Deterministic producer-construction mocks are scoped and closed; cases exercise parallel isolation, legacy/mixed prefixes, Flink contiguous and Zeta striped state models, repeated 3->4->3->4->3 recovery, same-generation scale-up, revision overflow, contiguous sequences and sink serialization across retries. Broker tests check actual read_committed progress and abandoned-record invisibility, plus bounded fresh-writer ID initialization. Parallel batch E2E uses bounded Awaitility exact set/count assertions; streaming restore covers source parallelism 3->2 and all three input partitions. Both Spark suites assert stable partition versus changing task IDs across epochs and invoke production Doris label generation. See seatunnel-connectors-v2/connector-kafka/src/test/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriterTest.java:337, seatunnel-e2e/seatunnel-connector-v2-e2e/connector-kafka-e2e/src/test/java/org/apache/seatunnel/e2e/connector/kafka/KafkaIT.java:2415 and seatunnel-translation/seatunnel-translation-spark/seatunnel-translation-spark-2.4/src/test/java/org/apache/seatunnel/translation/spark/sink/writer/SparkDataWriterFactoryTest.java:58. Fixed host values in mocked adapter fixtures do not bind external ports. Real Flink savepoint/rescaling remains model/adapter coverage, not a deployed rescale proof; author-reported broker runs are not Daniel executions.

2.3 Documentation

The current English and Chinese incompatible-change notes now explicitly name Zeta and Flink for stateful recovery/rescaling, matching the connector Semantics and transaction_prefix option row. This answers @zhangshenghang's latest request and the author's F7 clarification. Spark is described separately with stable retry identity, historical IDs for other sinks and speculation disabled. The stateless timeout limitation and graph/ACL migration remain explicit.

3. Architecture

3.1 Change location

The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.

3.2 Maintainability

Keep the behavior, lifecycle ownership, and failure contract together. The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.

3.3 Extensibility

Prefer the existing component boundary and tests over unrelated shared abstractions.

3.4 Upgrade impact

Partially incompatible externally: transactional-ID ACLs/monitoring must permit the new opaque writer/sequence shape, and operators must stop the old attempt, rebuild the execution graph with the upgraded version, then restore retained state. Old serialized execution graphs lack the new sink fields and are explicitly unsupported. KafkaSinkState fields/serialization, configuration names/defaults and existing getIndexOfSubtask semantics are preserved; the new Context method has a compatible default. Spark speculation must remain false. The connector and migration docs cover these boundaries in both languages.

4. Findings summary

Completeness check: All changed files and affected entry/failure paths were reviewed; configuration/serialization compatibility, test failure capability and stability, documentation/examples, change ownership, and current CI/conflict/review gates are covered above. No unreviewed source scope is claimed complete.

# Finding Location Severity
- No new source blocker found - -

5. Merge recommendation

Can merge once the recorded CI and repository gates are satisfied

Blocking items: No source blocker. Current-head CI and write-capable maintainer review remain independent requirements.

Non-blocking suggestions: None beyond the validation limits above.

Overall: the reviewed source path is coherent; no runtime acceptance is claimed beyond the actual CI result. Daniel has READ permission, so this COMMENT cannot dismiss historical requested changes or satisfy a write-capable maintainer approval gate.

CI and repository state: no check reported in the Apache rollup; Build: queued. GitHub reports BLOCKED / CHANGES_REQUESTED.

Verification: Reviewed all changed files and the referenced call sites at 32fb52215ab395d604f1e9120f85afe40246ada8 against merge base 89f91a89af15f33d97a942d8b65f4fc1b0c80bf5. git diff --check passed. I did not build, run tests, or execute SeaTunnel locally.

Review time: 2026-11-23T09:54:17.641411-05:00

Local evidence: git fetch obtained head 32fb52215ab395d604f1e9120f85afe40246ada8; git merge-base returned 89f91a89af15f33d97a942d8b65f4fc1b0c80bf5; git diff --stat reports 21 files changed, 1860 insertions(+), 55 deletions(-). git show and source searches were used for the entry points above. No local build, unit test, E2E, Docker run or service startup was executed.

@zephyr45

zephyr45 commented Nov 23, 2026 •

Copy link
Copy Markdown
Author

@zhangshenghang Done in 32fb5221: the EN/ZH incompatible-change notes now limit recovery and rescaling to Zeta and Flink. Could you approve the pending PR signal run so the required Build check appears?

@SEZ9 32fb5221 is 117dc411 plus that docs change only (four Markdown lines); code and tests are identical. Could you make your final decision on it? Status:

  • F1/F2: fixed in 585f69b7 (KafkaSinkWriterTest).
  • F3: fixed in d8143b58/b9ed7c12. Your reading is right: the remaining case is bounded by transaction.timeout.ms (EN Kafka.md:104, ZH :100).
  • F4: fixed in 9e4aad72 (KafkaIT, SparkSinkTest).
  • F5/F6: left as is, tracked in [Improve][Connector-V2][Kafka] Coordinate legacy shared-prefix transaction cleanup #13298; accepted by you on Nov 22.
  • F7: both halves confirmed, EN and ZH (7887e909, 9e4aad72): the transaction_prefix row gives <prefix>-<writer>-<sequence>, and rescaling is scoped to Zeta and Flink.

CI: 117dc411 was fully green. On 32fb5221 (build), Kafka IT and unit tests pass; 6 other jobs need a re-run. Update (Nov 24): all 6 passed on re-run, so the build is fully green (88 passed, 9 skipped).

@SEZ9

SEZ9 commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

@zephyr45 thanks for the clear status rundown.

Your two asks

  • Approving the pending PR signal run: I can't confirm this as done yet, so please treat it as still open on my side. If the required Build check still hasn't appeared on 32fb5221, ping here again.
  • Final decision on 32fb5221: not made yet. You describe it as 117dc411 plus the four-line docs change only, so the one thing it is waiting on is CI. You report that Kafka IT and unit tests pass on run 45184080151, but that 6 other jobs need a re-run.

Findings, as you report them

  • F1/F2: fixed in 585f69b7, covered by KafkaSinkWriterTest.
  • F3: fixed in d8143b58/b9ed7c12, with the remaining case bounded by transaction.timeout.ms and documented in EN and ZH.
  • F4: fixed in 9e4aad72, covered by KafkaIT and SparkSinkTest.
  • F5/F6: left as is and tracked in [Improve][Connector-V2][Kafka] Coordinate legacy shared-prefix transaction cleanup #13298.
  • F7: the transaction_prefix row gives <prefix>-<writer>-<sequence> and rescaling is scoped to Zeta and Flink, in EN and ZH (7887e909, 9e4aad72, plus the incompatible-change notes in 32fb5221).

I have no further requests on F1–F7 beyond the CI items below.

Remaining asks

  1. Please re-run the 6 jobs on 32fb5221 and post the result here.
  2. If any of them still fails, please say which job and whether it touches the Kafka connector.

Once Build is present and those jobs are green, the final decision can be made on 32fb5221.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks, @zephyr45 and @SEZ9. The CI status has advanced since both earlier notes: exact-head Build 45184080151 is now SUCCESS, so the six-job rerun request is outdated.

My full review at 32fb522 already closed the source requests, including F7's four-line EN/ZH scope correction. I am not reopening F5/F6, which are explicitly tracked separately in #13298. There is still no required Apache Build check attached in the current snapshot, and GitHub reports CHANGES_REQUESTED/BLOCKED. A maintainer with workflow/review authority needs to approve or otherwise reconcile the pending PR-signal bridge for this head and the review summary; Daniel's READ permission cannot do that. This is not evidence that the fork's CI is disabled — its exact-head Build is green.

From Daniel's side the source blocker is cleared. The remaining gates are the required check publication/workflow gate and effective maintainer approval or dismissal of the historical request. Please keep the PR focused; another source patch is not the next step.

This is a discussion follow-up on unchanged head 32fb52215ab395d604f1e9120f85afe40246ada8, not a new full source review. I inspected the named local source paths; no local build, test or SeaTunnel runtime was executed. Daniel has READ permission; effective maintainer approval and historical review dismissal remain separate repository actions.

@zephyr45

Copy link
Copy Markdown
Author

@SEZ9 All 6 jobs now pass on 32fb5221: build 45184080151 is fully green (88 passed). The 9 skipped jobs don't apply, as on 117dc411: the full connector matrix replaces 8 updated-modules jobs, and edge-agent-it is unaffected. None of the 6 tests the Kafka connector; the first failures were Maven Central 429s, job time limits and one Kubernetes test error. Kafka IT passed 292/292 on JDK 11 and 17.

F1–F7 are unchanged: F1/F2 fixed (585f69b7), F3 fixed (d8143b58/b9ed7c12) with the documented transaction.timeout.ms limit, F4 fixed (9e4aad72), F5/F6 left as is in #13298, F7 fixed (7887e909, 9e4aad72, 32fb5221).

Build only appears once a committer approves the pending PR signal run. @davidzollo or @nzw921rx, could you approve it? @nzw921rx, cf52689e removed the multi-table change you flagged; could you re-review 32fb5221?

@SEZ9 once Build is present, could you make your final decision on 32fb5221?

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks for the detailed run and blocker reconciliation. The exact-head fork Build is still successful, and I agree the previous six-job rerun request is obsolete. The current Apache rollup still has no required Build attached, so the next action belongs to a maintainer with workflow/review authority: reconcile the PR-signal bridge and the effective review gate on 32fb522. My source conclusion remains clear; F5/F6 remain separately tracked as already agreed. There is no reason to patch unrelated source or blindly sync just because the branch is behind. I cannot perform that maintainer-only gate action with Daniel's READ permission.

This is a discussion follow-up on unchanged head 32fb52215ab395d604f1e9120f85afe40246ada8, not a new full source review. I inspected the named local source paths; no local build, test or SeaTunnel runtime was executed. Daniel has READ permission; effective maintainer approval and historical review dismissal remain separate repository actions.

@SEZ9

SEZ9 commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator

@zephyr45 Sorry for the slow answer on this. Yes, I will make my final decision on 32fb5221 once Build is present on it. That is not done yet, because the pending PR signal run still needs committer approval before Build attaches to that head.

  • CI: I've noted your report that all 6 jobs now pass on 32fb5221, with build 45184080151 fully green (88 passed) and Kafka IT at 292/292 on JDK 11 and 17. On that basis the earlier request to rerun those six jobs is obsolete.
  • F1/F2: I take these as fixed in 585f69b7.
  • F3: I take this as fixed in d8143b58/b9ed7c12, with the documented transaction.timeout.ms limit.
  • F4: I take this as fixed in 9e4aad72.
  • F5/F6: I'm fine with these staying out of this PR and being tracked in the separate follow-up you referenced.
  • F7: I take this as fixed in 7887e909, 9e4aad72 and 32fb5221.

I have no further source asks on F1–F7. Two things from you:

  1. Please keep the head at 32fb5221, so the decision applies to exactly the commit you validated.
  2. Please drop a short note here with the run link as soon as Build shows up on 32fb5221, and I'll make the final decision then.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks, @SEZ9. The current snapshot still has no Apache Build entry on this head, so I cannot treat the missing repository check as satisfied merely from the successful fork result. The next step is for a write-capable maintainer to resolve the PR-signal/check-adoption gate and obtain the required check on this exact commit. My prior source clearance remains unchanged; no unrelated source patch or drift-only sync is requested.

Discussion-only follow-up on unchanged head 32fb52215ab395d604f1e9120f85afe40246ada8; no new full source review or local build/test/runtime execution is claimed. Daniel's technical conclusion does not replace write-capable maintainer approval or dismissal of historical changes requested.

…er-identity

Resolve docs/en/connectors/sink/Kafka.md: take dev's format row and keep
this branch's transaction_prefix row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@zephyr45

Copy link
Copy Markdown
Author

@SEZ9 I had to move the head. #13436 was merged into dev today and conflicts with this PR in docs/en/connectors/sink/Kafka.md, so 32fb5221 can no longer be merged. 8382fbed merges dev into it. I resolved only that conflict, taking dev's format row and keeping this PR's transaction_prefix row. The PR still adds and removes the same lines against dev (21 files, +1860/−55).

F1–F7 are unchanged, as in your last reply: F1/F2 fixed (585f69b7), F3 fixed (d8143b58/b9ed7c12) with the documented transaction.timeout.ms limit, F4 fixed (9e4aad72), F5/F6 left as is in #13298, F7 fixed (7887e909, 9e4aad72, 32fb5221).

CI: build is running on 8382fbed; I'll update this line with the result.

@davidzollo, could you approve the new PR signal run so Build appears?

@SEZ9 once Build is present, could you make your final decision on 8382fbed?

@SEZ9

SEZ9 commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator

@zephyr45 Moving the head is fine. A merge of dev was unavoidable once 32fb5221 could no longer be merged.

On your request for a final decision on 8382fbed: it is not done yet, and I will make it once Build is present on 8382fbed. Going by your comment, the fork build is still running and the new PR signal run is still waiting for approval, so there is nothing for me to decide against yet.

On F1–F7, I agree the status carries over as you listed it:

  • F1/F2: fixed in 585f69b7.
  • F3: fixed in d8143b58/b9ed7c12, with the documented transaction.timeout.ms limit.
  • F4: fixed in 9e4aad72.
  • F5/F6: left as is and tracked separately, which was already agreed, so they do not block this PR.
  • F7: fixed in 7887e909, 9e4aad72 and 32fb5221.

What I still need from you:

  1. Please update the CI line with the result of the fork build on 8382fbed once it finishes.
  2. The conflict was in the file F7 covers. Please confirm that the transaction_prefix row and the Semantics paragraph, including the engine scope of the rescaling claim, read exactly as they did on 32fb5221.
  3. Please ping me here once Build shows up on 8382fbed.

If the head has to move again before then, please note what changed in the same way you did here.

@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.

Thanks for the update and contribution to Apache SeaTunnel. I re-reviewed the full merged head rather than only the conflict resolution. The source fixes for F1/F2/F4 and the documented F3/F7 boundaries are coherent, and the earlier multi-table override is absent. Sorry for missing the small helper-comment gap earlier; the optional observation below is a carryover maintenance point. The previously running fork Build has now finished, so I am also updating that CI guidance explicitly.

What problem does this PR solve?

User pain: Parallel EXACTLY_ONCE Kafka writers sharing transaction_prefix could open the same transactional ID and fence one another.

Fix: Choose a sink-level generation, stable writer namespace and contiguous transaction sequence; restore/fence every assigned saved namespace, then advance an adopted recovery revision independently of engine checkpoint counters.

One sentence: Isolate parallel writers and make their stateful retry ownership explicit.

Example: Two writers sharing orders now open orders-g...w0-1 and orders-g...w1-1; a 3-to-2 restore fences all assigned old namespaces and derives distinct revision-qualified outputs.

1. Code changes

1.1 Core logic

Complete runtime path:

KafkaSink factory -> constructor chooses transactionPrefix/generation once -> serialized sink execution graph
  -> createWriter/restoreWriter -> KafkaSinkWriter:91 -> stable index -> restoreState
  -> parse every KafkaSinkState against its own saved job prefix before broker effects
  -> select deterministic assigned nonlegacy lineage -> advance revision + current writer index
  -> legacy-only/empty state uses generation/current-index base; empty state starts sequence one
EXACTLY_ONCE -> KafkaTransactionSender -> fence all assigned prefixes after saved sequence
  -> also fence deterministic recovered output from sequence one -> beginTransaction
write -> serializer -> async producer send -> prepareCommit flush/check error -> commit info
snapshotState(checkpointId) -> persist unchanged KafkaSinkState shape with current transaction ID
  -> increment contiguous transaction sequence -> open next ID; checkpoint ID remains separate
KafkaSinkCommitter:45-86 -> resume saved producer ID/epoch and transaction -> commit
Flink ListState assignment -> common FlinkSink:78-91 or Flink20 restoreWriter:141 -> assigned states unchanged
Spark2.4/3.3 factory -> SparkSinkWriterContext(partitionId, taskId)
  -> historical getIndexOfSubtask=taskId; new getStableSubtaskIndex=partitionId -> Kafka only

Key findings and correctness:

  • Read all 21 changed files, both Spark factories, the complete namespace parser/planner, sender and E2E assertions. The normal parallel exactly-once write path reaches the fix; rescaling and task retries reach the additional ownership protocol.
  • F1 is closed: there is no modulo ownership rejection; the writer consumes the engine-assigned list, with explicit contiguous-assignment and modulo-style scale-down tests. F2 is closed: parseRestoredTransaction uses each state's own saved prefix, so mixed generated historical prefixes are accepted/fenced before one deterministic lineage is adopted.
  • F3 is bounded, not a blanket no-orphan guarantee: the no-state path initializes sequence one only. Higher abandoned sequences not identified by retained checkpoint state can hold back read_committed until transaction.timeout.ms. That limit is explicit in both guides and both incompatible-change entries. Sequence allocation no longer jumps with Flink's local checkpoint counters.
  • Stateful retries from the same assigned state derive the same advanced namespace and scan its contiguous sequence; a later retained state advances the revision again. The current-index suffix separates restoring writers, and revision-qualified outputs cannot equal an unsuffixed stateless sibling. The 3-to-4-to-3-to-4-to-3 model checks divergent adapter counters and sibling fencing.
  • F4 is closed in the reviewed source: Spark partition identity is separate from the old task-attempt index. Kafka opts into the new default SPI method; Doris labels retain task-attempt identity, with production-label tests for both Spark versions. Concurrent speculative attempts remain excluded by the documented spark.speculation=false requirement.
  • The SinkContextProxy override and multi-table test changes discussed by @nzw921rx are absent from this target-relative diff. KafkaSink does not advertise multi-table support here; this is not a hidden activation of that capability. The default SPI addition preserves existing implementations and other sinks' identifiers.
  • F5/F6 remain the accepted legacy shared-namespace migration cost tracked in #13298: per-writer deduplication does not coordinate different writers' probes. I agree with @SEZ9's explicit non-blocking deferral and do not create duplicate findings. F7 is closed: both option rows and semantics/incompatible notes say opaque writer/sequence and scope stateful recovery to Zeta/Flink. The merge retained dev's format row.
  • The actual current fork Build has now completed with failure, replacing the earlier running status: IcebergFlinkRecoveryIT.testV2TaskManagerCrashRecovery times out in completeCheckpoint, expected checkpoint 3 but observed 4. Kafka IT on JDK11 and JDK17 succeeded. Five other jobs were cancelled, not proven test failures. This Iceberg fixture is unchanged against latest fetched dev; no corresponding fix is present there. A sync alone is therefore not an evidenced cure. Rerun the Iceberg lane and the cancelled jobs; maintainers must separately resolve required Apache check adoption. Please keep any fixture correction outside this Kafka PR.

Before:

        /** @return The index of this subtask. */
        int getIndexOfSubtask();

        /** @return parallelism of this writer. */
        default int getNumberOfParallelSubtasks() {
            return 1;

After:

        /** @return The index of this subtask. */
        int getIndexOfSubtask();

        /**
         * Returns the logical writer index retained across task attempts. Transactional sinks may
         * use it to fence an abandoned attempt without changing the external identifiers of sinks
         * that depend on {@link #getIndexOfSubtask()}.
         *
         * <p>On Spark this is the partition ID, while {@code getIndexOfSubtask()} retains the
         * historical task-attempt ID. The stable index can be reused across streaming epochs; it
         * must not be used alone as a unique identifier for a completed batch.
         */
        default int getStableSubtaskIndex() {
            return getIndexOfSubtask();
        }

        /** @return parallelism of this writer. */
        default int getNumberOfParallelSubtasks() {
            return 1;

1.2 Compatibility

Partially incompatible external identity/upgrade behavior, documented in both incompatible-change files. Config keys/defaults and KafkaSinkState serialVersionUID/field shape remain unchanged. The SPI addition is a default method; Spark historical task IDs remain available. Transactional-ID ACL/monitoring patterns must allow writer-specific IDs and legacy restore access. Added sink-level fields require rebuilding an execution graph with the upgraded version before restoring retained checkpoint/savepoint state; reusing an old serialized execution graph is explicitly unsupported. No new production dependency; connector-doris is test-scoped in the two Spark modules.

1.3 Performance and side effects

Hot writes keep existing serializer/send behavior. Startup adds parsing, deterministic sorting and temporary producer fencing proportional to assigned namespaces and discovered contiguous IDs. Each temporary producer closes in finally; init/begin failure cleanup preserves the original error. The accepted legacy probe chain may grow with participating restored writers and repeats on retry (#13298). Fresh writers avoid full-history scans, important for Spark micro-batches. No new row buffer, per-record global lock or shared retry owner; no throughput measurement claimed.

1.4 Errors, logging, and findings

Issue 1: Add short contracts to the new namespace/failure-cleanup helpers

  • Location: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:289.
  • Description and risk: The overall restore/parser Javadocs are useful, but the new advanceWriterNamespace helper and KafkaTransactionSender.closeProducerAfterFailure:265 lack method-level contracts for revision overflow and preserving the original failure while closing a client. These are lifecycle/error paths whose intended invariants should remain clear during later maintenance; no runtime defect is demonstrated by this observation.
  • Best improvement: Add concise method comments for revision advancement and failure-cleanup ownership. Keep the production behavior and current tests; no broader refactor is needed.
  • Responsibility and trade-off: The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
  • Severity: Medium; blocking: false.
  • Previously raised by another reviewer: No, unless explicitly attributed above.

I agree with @SEZ9's latest technical direction: F1/F2/F4/F7 are addressed, F3 has the accepted documented timeout boundary, and F5/F6 remain the non-blocking #13298 follow-up. @nzw921rx's historical changes request concerns multi-table behavior; the offending proxy override is absent and only a default stable-index method plus Spark-specific context remains. A write-capable reviewer still needs to make the final approval/dismissal decision; Daniel's technical clearance does not erase those historical review records. The CI failure diagnosis above updates the stale running/approval-only guidance without attributing the Iceberg failure to this Kafka diff.

2. Code quality

2.1 Conventions

Reviewed all changed files for license, imports, naming, core-method and state-field comments. See the numbered findings for the required changes.

2.2 Test coverage and stability

Stability rating: Stable. Stable for the new/changed Kafka coverage: constructor mocks are scoped, writers and temporary producers are closed, IDs/sets are deterministic, and malformed revision input fails before client initialization. The rescaling model explicitly covers contiguous states, mixed prefixes, repeated revisions, fresh siblings and non-global checkpoint counters. Broker tests use unique topics registered for class cleanup, acknowledged sends, read_committed assertions and bounded Awaitility; batch checks assert both the exact value set and exact count, so duplicates are not hidden by set comparison. Spark tests round-trip contexts through serialization and use real Doris label generation with mocked HTTP and finally cleanup. Remaining acceptance limits: Flink rescaling is modeled at the writer boundary rather than executed by the changed Zeta-only savepoint E2E, and speculation is explicitly unsupported. No local test or broker execution occurred.

2.3 Documentation

EN/ZH option rows match semantics and describe --. Both incompatible-change entries now qualify stateful cleanup as Zeta/Flink, preserve the no-state timeout limit, require a new execution graph for upgrade and note Spark speculation/stable-index constraints. This independently answers the author and @zhangshenghang's scope question; it is not based only on the author's status table.

3. Architecture

3.1 Change location

The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.

3.2 Maintainability

Keep the behavior, lifecycle ownership, and failure contract together. The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.

3.3 Extensibility

Prefer the existing component boundary and tests over unrelated shared abstractions.

3.4 Upgrade impact

Partially incompatible external identity/upgrade behavior, documented in both incompatible-change files. Config keys/defaults and KafkaSinkState serialVersionUID/field shape remain unchanged. The SPI addition is a default method; Spark historical task IDs remain available. Transactional-ID ACL/monitoring patterns must allow writer-specific IDs and legacy restore access. Added sink-level fields require rebuilding an execution graph with the upgraded version before restoring retained checkpoint/savepoint state; reusing an old serialized execution graph is explicitly unsupported. No new production dependency; connector-doris is test-scoped in the two Spark modules.

4. Findings summary

Completeness check: All changed files and affected entry/failure paths were reviewed; configuration/serialization compatibility, test failure capability and stability, documentation/examples, change ownership, and current CI/conflict/review gates are covered above. No unreviewed source scope is claimed complete.

# Finding Location Severity
1 Add short contracts to the new namespace/failure-cleanup helpers seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/sink/KafkaSinkWriter.java:289 Medium

5. Merge recommendation

Can merge once the recorded CI and repository gates are satisfied

Blocking items: No source blocker. Current-head CI and write-capable maintainer review remain independent requirements.

Non-blocking suggestions: Issue 1: Add short contracts to the new namespace/failure-cleanup helpers

Overall: the reviewed source path is coherent; no runtime acceptance is claimed beyond the actual CI result. Daniel has READ permission, so this COMMENT cannot dismiss historical requested changes or satisfy a write-capable maintainer approval gate.

CI and repository state: no check reported in the Apache rollup; Build: failure. GitHub reports BLOCKED / CHANGES_REQUESTED.

Verification: Reviewed all changed files and the referenced call sites at 8382fbed6edb10c9282c9f39dedbb901b98a2f61 against merge base 113cea2a9c67878dd1f21e2e57f3add0f4603a51. git diff --check passed. I did not build, run tests, or execute SeaTunnel locally.

Review time: 2026-11-26T08:54:07.792103-05:00

Local evidence: git fetch obtained head 8382fbed6edb10c9282c9f39dedbb901b98a2f61; git merge-base returned 113cea2a9c67878dd1f21e2e57f3add0f4603a51; git diff --stat reports 21 files changed, 1860 insertions(+), 55 deletions(-). git show and source searches were used for the entry points above. No local build, unit test, E2E, Docker run or service startup was executed.

@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.

Thanks for keeping the checks moving. A closeout refresh supersedes the current-failure wording in my full review: the exact-head fork Build is now running attempt 2. The Iceberg checkpoint-3-versus-4 failure and the successful Kafka JDK 11/17 jobs I cited are evidence from the earlier attempt, not a completed result for this active attempt.

The source-level conclusion remains clear at 8382fbed6edb10c9282c9f39dedbb901b98a2f61. Please let attempt 2 finish; do not launch a duplicate rerun while it is active. The Iceberg fixture was unchanged in latest checked dev, so syncing alone was not a verified fix and no unrelated Iceberg patch is requested in this Kafka PR. The current Apache rollup still has no Build entry; a write-capable maintainer must resolve required-check adoption and final approval/dismissal independently. Daniel's technical clearance does not replace those gates.

CI-only follow-up on unchanged code; no new full source review or local execution is claimed.

@SEZ9

SEZ9 commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator

Quick CI status update on this PR; the source-level conclusion from the earlier review is unchanged at 8382fbed6edb10c9282c9f39dedbb901b98a2f61.

  • The fork Build run 45624383266 is now on attempt 2 and still in progress. Please let it finish, and don't start another rerun while it is active.
  • The Iceberg checkpoint failure and the passing Kafka JDK 11/17 jobs cited earlier came from the previous attempt, so they are not the result of this one.
  • No Iceberg change is requested in this Kafka PR. The Iceberg fixture was unchanged in the latest checked dev, so syncing alone was not a verified fix.
  • This follow-up is CI-only on unchanged code. It involved no new full source review and no local execution.

Remaining items:

  1. When attempt 2 completes, please post the outcome here with the run link.
  2. The Apache rollup still has no Build entry. Required-check adoption and final approval have to be resolved by a write-capable maintainer, and the technical clearance does not replace those gates.

Thanks for keeping the checks moving.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks, @SEZ9. The run has progressed beyond the attempt-2 snapshot: exact-head Build 45624383266 is now on attempt 3 and has completed as CANCELLED. The latest manifest has only the two MySQL CDC JDK11/17 lanes cancelled and no failed child job; the old Iceberg failure is not the result of this attempt. The Apache bridge is now present but remains IN_PROGRESS. Please rerun the cancelled MySQL CDC lanes once, retain their completed results, and let the bridge reconcile them; do not start overlapping reruns. No Kafka/Iceberg source change is requested from a cancellation, and no verified upstream fix makes a blind sync the cure. My prior source clearance remains; effective maintainer review and completed CI are still required.

Current-head Build, head 8382fbed6edb10c9282c9f39dedbb901b98a2f61; compare diverged, ahead 17 / behind 32. Discussion/CI follow-up only; no new full source review or local build/test/runtime execution. Daniel has READ permission; effective maintainer approval/dismissal remains separate.

Current snapshot (2026-11-27T03:08:16.144426+00:00): Signal pull request update: SUCCESS; Build: IN_PROGRESS; merge state BLOCKED; review decision CHANGES_REQUESTED.

@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.

The CI fact cited in my last follow-up has changed again: Build attempt 4 has completed with failure. Its remaining failed MySQL CDC / JDK 17 job stops before tests: Maven-wrapper download returns HTTP 429, then MavenWrapperMain is missing. It does not exercise this Kafka change. Latest dev still uses the same wrapper and #13466 remains open, so sync is not a verified cure. When artifact access recovers, rerun that specific failed lane without unrelated Kafka/dependency changes. The prior source-clear conclusion remains, but this head still lacks a successful completed Build.

This is a discussion/gate follow-up on unchanged head 8382fbed6edb10c9282c9f39dedbb901b98a2f61, not a new full source review. Base dev compare: diverged, ahead 17 / behind 34. Branch drift alone is not a request to sync. No local build/test/runtime execution was performed. Daniel has READ permission; any required write-capable maintainer approval or historical-review dismissal remains separate.

@SEZ9

SEZ9 commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator

Thanks for sticking with this one. Here is where head 8382fbed6edb10c9282c9f39dedbb901b98a2f61 stands.

Build 45624383266 completed attempt 4 with a failure. The one remaining failed job, MySQL CDC / JDK 17 (140280168741), stops before any tests run: the Maven wrapper download returns HTTP 429 and MavenWrapperMain is then missing. It does not exercise this Kafka change, so no source change is requested.

  • Please rerun that specific failed lane once artifact access recovers, and avoid overlapping reruns.
  • Please don't add unrelated Kafka or dependency changes for the rerun.
  • A sync with dev is not being asked for; it is not a verified cure for this failure.

The prior source-clear conclusion remains. This head still needs a successful completed Build, and any required maintainer approval remains separate.

This branch has not been deployed

No deployments
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.

[Bug][Connector-V2][Kafka] EXACTLY_ONCE sink fails with ProducerFencedException when parallelism > 1

5 participants