Repository navigation
Conversation
DanielLeens
left a comment
There was a problem hiding this comment.
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 collideAfter:
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 coveredKey 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
- 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.
- 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.
|
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 Base |
|
Thanks @DanielLeens — both review points are addressed in
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, For @SEZ9's failure-status question, the PR description now records that current |
SEZ9
left a comment
There was a problem hiding this comment.
Thanks for working on this. I reviewed the latest head 10e618cb3815.
What this PR fixes
- User pain: With
semantics = EXACTLY_ONCEand a sharedtransaction_prefix, parallel Kafka sink writers all open<prefix>-<checkpoint>and fence each other withProducerFencedException(#13044), so any exactly-once Kafka sink with parallelism > 1 is unusable. - Fix approach:
KafkaSinkWriterderives a per-writer namespace<prefix>-<subtask>(KafkaSinkWriter.java:84) and passes it alongside the persisted job prefix into a new two-prefixKafkaTransactionSenderconstructor (KafkaTransactionSender.java:81-86). On restore,abortRestoredTransactionsparses each saved transaction ID back to its namespace, checksrestoredWriterIndex % parallelism == currentWriterIndex, and fences every assigned namespace (including the legacy shared one) viaabortTransaction(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
restoreStatebreaks scale-down for jobs that omittransaction_prefix(each writer draws its own randomSeaTunnel%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 unlessrestoredWriterIndex % parallelism == currentWriterIndex. That rule mirrors Zeta'sCheckpointCoordinator.restoreTaskStateloop (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 operatorListStaterepartitioner 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-Nand is restored at parallelism 2. Subtask 0 receives<prefix>-0-Nand<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
abortRestoredTransactionsand its Javadoc rely on). Fencing every namespace present instatesis therefore safe without ownership validation; the check only adds a failure mode. - Test coverage:
testRestoreKafkaToKafkaExactlyOnceOnStreaminginKafkaITis@DisabledOnContainer(type = {SPARK, FLINK}), so the Flink restore path is not exercised by the e2e suite. - Suggested fix: keep the
Integer.parseIntformat check as the only hard failure, fence every namespace that arrives instates, 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 != currentWriterIndexrule encodes Zeta'sCheckpointCoordinator.restoreTaskStateloop (i = tuple.f1(); i += currentParallelism). The Flink adapter (FlinkSink.createWriter->sink.restoreWriter(...)) gets its states from Flink's operatorListStaterepartitioner, 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 invariantabortRestoredTransactionsrelies on), so the check only adds a failure mode. Please fence whatever arrives instatesand downgrade this to a WARN log (keep theInteger.parseIntformat check as the only hard failure). Note thattestRestoreKafkaToKafkaExactlyOnceOnStreamingis@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_prefixis absent (the default), lines 78-79 still give every writer instance its own randomSeaTunnel%04dprefix, andKafkaTransactionSender.snapshotState(KafkaTransactionSender.java:219-221) persists that per-writer value intoKafkaSinkState.transactionIdPrefix. On a Zeta scale-down,CheckpointCoordinator.restoreTaskStatehands subtaskkthe states of original subtasksk, k+P, k+2P, ..., so the restored list legitimately contains two or more different random prefixes. The new loop inrestoreState(lines 182-187) throwsIllegalStateException("Cannot restore Kafka sink states with different transaction prefixes")as soon as the second prefix differs fromstates.get(0). - Failure scenario: parallelism 3 -> 2 with no
transaction_prefix. Writer 0 receivesSeaTunnel0001-0-4(from original subtask 0) andSeaTunnel0002-2-4(from original subtask 2).restoreStatethrows 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 singlethis.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 aKafkaSinkWriterTestcase that restores writer 0 at parallelism 2 fromSeaTunnel0001-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_prefixis not set, lines 78-79 give every writer its own randomSeaTunnel%04dprefix, and that per-writer value is whatKafkaTransactionSender.snapshotStatestores inKafkaSinkState.transactionIdPrefix. Zeta'srestoreTaskStateassigns subtaskkthe states of original subtasksk, k+P, ..., so after a 3->2 restore writer 0 legitimately receives two states with different random prefixes and this loop throws;getRestoredTransactionIdPrefixwould 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 owngetTransactionIdPrefix()and fence all of them instead of requiring a single prefix, and add aKafkaSinkWriterTestcase restoring writer 0 at parallelism 2 fromSeaTunnel0001-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:
abortRestoredTransactionsonly runs when!kafkaStates.isEmpty()(line 93), andlastCheckpointIdstays 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. OnsnapshotState(9)writer 2 then jumps to<prefix>-2-10, so the id sequence in that namespace is1, 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-1again, 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 thegetEpoch()==0scan in this namespace, so that transaction stays open untiltransaction.timeout.ms, blockingread_committedconsumers on the affected partitions. - Suggested fix: seed
lastCheckpointIdfor stateless writers from the job-wide restored checkpoint (e.g. via a committer-side or shared max), or always runabortTransaction(writerTransactionPrefix, lastCheckpointId + 1)for the writer's own namespace on restore even whenkafkaStatesis 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:
writerTransactionPrefixis built fromcontext.getIndexOfSubtask()(line 84). On Spark,SeaTunnelSparkDataWriterFactory.createWriter(partitionId, taskId)constructsnew DefaultSinkWriterContext(jobId, (int) taskId, parallelism)(spark-3.3 line 69; the spark-2.4SparkDataWriterFactorydoes the same at line 68), andDefaultSinkWriterContext.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 differenttaskId, so it opens a fresh namespace, and becausekafkaStatesis empty on Spark the fence path at line 93-94 never runs. The previous attempt's<prefix>-<oldTaskId>-1stays open untiltransaction.timeout.ms, blockingread_committedconsumers 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
partitionIdas the subtask index, or guard here againstidx >= 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)buildsnew DefaultSinkWriterContext(jobId, (int) taskId, parallelism), sogetIndexOfSubtask()is Spark's ever-increasing task id. A retried task therefore opens<prefix>-<newTaskId>-1and nothing ever fences<prefix>-<oldTaskId>-1(the fence path below only runs whenkafkaStatesis non-empty), leaving an open transaction that blocks read_committed consumers untiltransaction.timeout.ms. Could we either make the Spark context exposepartitionIdas the subtask index, or guard here againstidx >= 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.transactionIdis<prefix>-<cp>, sovalidateRestoredStateOwnerreturns early for all of them (lines 240-243) and each writer callsabortTransaction(transactionPrefix, cp+1)via line 205. The loop inKafkaTransactionSender.abortTransaction(String,long)(lines 193-210) stops only whenproducer.getEpoch() == 0, i.e. when the ID has never been registered with the coordinator; but a sibling writer'sinitTransactions()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 runabortTransaction(transactionPrefix, cp+1)on the same shared namespace at the same time. Because that loop stops only ongetEpoch() == 0, a sibling'sinitTransactions()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 callsabortTransaction(prefix, ckpt+1)on the same shared namespace (KafkaTransactionSender.java:193-210). EachinitTransactions()on an id bumps its epoch, so once writer A has probed<prefix>-6(epoch 0, stops), writer B sees epoch 1 on<prefix>-6and 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 runabortTransaction(prefix, ckpt+1)concurrently against the same shared namespace. Because eachinitTransactions()bumps the epoch, the writer that probes<prefix>-6second 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 thedocs/zhcounterpart) describes the<prefix>-<subtask>-<checkpoint>shape and the recovery/rescaling cleanup, but thetransaction_prefixrow 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:19correctly 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 thetransaction_prefixrow 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 inKafkaSinkWriter#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_prefixis 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()==0loop, 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_prefixoption 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
left a comment
There was a problem hiding this comment.
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
- 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.
- 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.
|
Thanks @SEZ9 and @DanielLeens — I addressed the blocking findings in
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:
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 |
|
Thanks @SEZ9 and @DanielLeens — I found and fixed two residual correctness gaps in the previous update with
Final local validation on Java 11:
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 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
left a comment
There was a problem hiding this comment.
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 istoken+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), andthis.transactionPrefixfollows the adopted state. The unit testshouldRestoreMixedGeneratedPrefixesAfterScaleDowncovers 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-210cannot be hidden behind a gap (the former1, 10, 11case). The generated prefix is also chosen once, so a stateless retry can find its previous attempt. - Spark attempt identity (Issue 4): resolved.
partitionIdis stable across attempts and the sink-level token is shared, so a retried attempt fences the previous one. BothSparkDataWriterFactory.java:68andSeaTunnelSparkDataWriterFactory.java:69are changed. - Prefix-lifetime Javadocs: resolved. Docs for the option row now cross-link to
#semanticsin 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) withKafkaSink.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+w2after scale-down, and after scale-up the stateless writer 2 derives the very sametoken+w2and 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
ProducerFencedExceptionloop 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 ofWRITER_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
partitionIdis 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
- 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. - 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).
- 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.
|
Thanks @DanielLeens — I addressed all three non-blocking recommendations in
Validation on Java 11:
The exact-head Build is queued at https://github.com/zephyr45/seatunnel/actions/runs/41218673502 (head |
|
@zephyr45 Thanks for the updates in From your description, the generation token and job-level generated
I'll do a final pass once those are in. |
DanielLeens
left a comment
There was a problem hiding this comment.
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:
- The normal exactly-once path reaches the isolation fix. Non-transactional senders retain their behavior; the snapshot DTO/serializer is unchanged.
- Recovery parses each saved prefix independently, handles contiguous and modulo assignments, and does not impose Zeta's remap rule on Flink.
- 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. - 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. - 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:
shouldFenceContiguouslyAssignedFlinkNamespacesAfterScaleDownsupplies writer 0 the adjacentw0/w1states at parallelism 2 and checks cleanup and successful adoption. - Mixed generated prefixes:
shouldRestoreMixedGeneratedPrefixesAfterScaleDownparses both historical saved prefixes and checks the adopted prefix in the next snapshot. New omitted-prefix retries are separately covered byshouldReuseGeneratedPrefixWhenStatelessWriterRetries, 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
21d4cb19is 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 of7887e90947.
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:
parseRestoredTransactionimplements 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 bothtransactionSequenceandcheckpointIdwithout 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 at3032-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
- 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.
- 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.
|
Final review follow-ups are pushed in |
|
Thanks for the follow-up and for pushing Your summary covers the transaction-ID grammar / restore-parser documentation in
Also, the exact-head run at Once I have those answers I'll do the re-review and, if everything checks out, dismiss the change request. |
DanielLeens
left a comment
There was a problem hiding this comment.
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_ONCEand parallelism > 1, every Kafka sink writer opened the same<prefix>-<checkpoint>transactional ID, so writers fenced each other withProducerFencedException(#13044). - Fix approach:
KafkaSinkcreates 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 stablepartitionIdas 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:
- The default exactly-once path reaches the fix (
KafkaSemantics.EXACTLY_ONCEbranch of the constructor); non-transactional senders are untouched and theKafkaSinkStatefields are unchanged. - 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.
- 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.
- For information: the Spark change (
taskId->partitionId) lives in the shared Spark translation writer factories, so it changesgetIndexOfSubtask()for every sink running on Spark, not only Kafka. SincepartitionIdis in[0, parallelism)and stable across attempts, this matches what theSinkWriter.Contextcontract 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.javaabortRestoredTransactionsandKafkaTransactionSender.abortTransaction. - Problem: For legacy checkpoints every restoring writer holds the same
<prefix>-<checkpoint>and probes the same namespace; a sibling'sinitTransactions()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" inseatunnel-engine-server.unit-test (11, ubuntu-latest):SeaTunnelClientTest.testGetMultiTableJobMetrics:703inseatunnel-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.
- 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.
- 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.
|
@SEZ9 Thanks for the concrete final-pass questions. I reproduced the additional Flink counterexample before changing production code, and pushed the coherent fix in
Verification for
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. |
|
@SEZ9 F1–F3 at head
|
DanielLeens
left a comment
There was a problem hiding this comment.
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.
|
@zephyr45 thanks for the clear breakdown of F1–F3 at
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
For each one, "fixed in " or "left as is, because …" is enough. |
|
@SEZ9 All of F1–F7 at head
DanielLeens checked F1–F3 against these lines and approved. Could you update your review for |
|
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 |
|
@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 Going by your summary, this is where each finding stands for me:
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. |
|
@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 Full status at
|
|
@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
That F7 confirmation is the only thing I still need from you. Once I have it, I'll make my final review decision on |
|
@SEZ9 F7: Yes, both halves, in EN and ZH
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 Rest, unchanged at |
|
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. |
|
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
left a comment
There was a problem hiding this comment.
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.
|
@zhangshenghang Done in @SEZ9
CI: |
|
@zephyr45 thanks for the clear status rundown. Your two asks
Findings, as you report them
I have no further requests on F1–F7 beyond the CI items below. Remaining asks
Once |
|
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 |
|
@SEZ9 All 6 jobs now pass on F1–F7 are unchanged: F1/F2 fixed (
@SEZ9 once |
|
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 |
|
@zephyr45 Sorry for the slow answer on this. Yes, I will make my final decision on
I have no further source asks on F1–F7. Two things from you:
|
|
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 |
…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>
|
@SEZ9 I had to move the head. #13436 was merged into F1–F7 are unchanged, as in your last reply: F1/F2 fixed ( CI: build is running on @davidzollo, could you approve the new @SEZ9 once |
|
@zephyr45 Moving the head is fine. A merge of On your request for a final decision on On F1–F7, I agree the status carries over as you listed it:
What I still need from you:
If the head has to move again before then, please note what changed in the same way you did here. |
DanielLeens
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
|
Quick CI status update on this PR; the source-level conclusion from the earlier review is unchanged at
Remaining items:
Thanks for keeping the checks moving. |
|
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 Current snapshot (2026-11-27T03:08:16.144426+00:00): Signal pull request update: SUCCESS; Build: IN_PROGRESS; merge state |
DanielLeens
left a comment
There was a problem hiding this comment.
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.
|
Thanks for sticking with this one. Here is where head 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
The prior source-clear conclusion remains. This head still needs a successful completed Build, and any required maintainer approval remains separate. |
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_ONCEand one configuredtransaction_prefixpreviously generated the same<prefix>-<checkpoint>IDs and fenced one another. This PR gives each active writer a disjoint transactional namespace with a contiguous sequence:Current
devalready flushes and propagates asynchronous Kafka send failures. This PR removes the transaction-ID collision that triggered fencing. The silent lossyFINISHEDcomparison was reproduced separately on released SeaTunnel 2.3.13.Current status
The head is
32fb52215ab395d604f1e9120f85afe40246ada8:117dc411plus 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 on32fb5221(88 passed, 9 skipped; six jobs passed on re-run). The branch was last synced withdevon 2026-11-18 (89f91a89), which includes the IRIS (#13285) and SFTP (#13203) fixture fixes. Fork Build 44311890713 is fully green on117dc411, includingkafka-connector-itand all unit tests on JDK 11/17 (connector-file-local-it (17)passed on re-run after an earlier 2-hour timeout that also affectsdev). Since7c272c5a, this PR's only own code change iscf52689e, which removes the unused multi-table stable-index override and its test. DanielLeens approved117dc411on 2026-11-20. Pending: committer approval of thePR signalrun (theBuildcheck appears after it), re-reviews from SEZ9 and nzw921rx, and committer approval of the PR.Review findings status (SEZ9, F1–F7) at
32fb5221585f69b7KafkaSinkWriterTest#shouldFenceContiguouslyAssignedFlinkNamespacesAfterScaleDown,#shouldFenceEveryAssignedWriterNamespaceAfterScaleDowntransaction_prefixunset585f69b7#shouldRestoreMixedGeneratedPrefixesAfterScaleDowntransaction.timeout.ms(documented)d8143b58,b9ed7c12#shouldReuseGeneratedPrefixWhenStatelessWriterRetries,#shouldNotWalkStatelessWriterTransactionHistory; EN/ZHKafka.mdSemanticsgetStableSubtaskIndex()(Spark partition ID), so a retry fences the same namespace9e4aad72KafkaIT#shouldFenceAbandonedAttemptWithStableIndex,SparkSinkTest/SparkDataWriterFactoryTest#shouldSeparateTaskIdentityFromStablePartitionAcrossRetriesAndEpochs<prefix>-<writer>-<sequence>; rescaling scoped to Zeta/Flink, also in the incompatible-change notes7887e909,9e4aad72,32fb5221Kafka.mdandincompatible-changes.mdNamespace and recovery contract
KafkaSinkcreates the job prefix and generation token once and serializes them with the execution graph. Fresh writers useg<generation>w<index>.<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.getIndexOfSubtask(). The new defaultgetStableSubtaskIndex()delegates to the existing index; Spark overrides it withpartitionId, 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_committedconsumers until Kafka'stransaction.timeout.msexpires. 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:
abortRestoredTransactionsdeduplicates 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
KafkaSinkStateserialization 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:
Earlier validation on 7c272c5
The November 15–16 Java 11 validation passed 583 JUnit tests, with zero failures, errors or skips:
Coverage includes contiguous state assignment, mixed prefixes, repeated
3 -> 4 -> 3 -> 4 -> 3recovery 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 useread_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
b9ed7c1297d9factories, loaded as controls against the same clean server, failed on batch two withLabel Already Exists; the current factories passed. Loaded class locations and control hashes were recorded.The affected reactor and dependencies passed
install -DskipTestsacross 75 modules, including formatting/package checks;git diff --checkpassed. 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.9andapache/doris:doris-all-in-one-2.1.0(reportingdoris-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