Repository navigation
Conversation
DanielLeens
left a comment
There was a problem hiding this comment.
What Problem Does This PR Solve?
- User pain point: The Hudi sink only ever wrote with Hudi's own client auto-commit. Every flushed batch became visible immediately and was committed independently of the engine's checkpoint, so a task restart after a partial failure could resubmit already-committed records and produce duplicate rows/commits. There was no way to get exactly-once delivery out of the Hudi sink, which the connector's own feature matrix openly admitted (
exactly-oncewas unchecked). - Fix approach: Introduce an opt-in
semanticsoption (AT_LEAST_ONCEdefault /EXACTLY_ONCE). WithEXACTLY_ONCE, the writer disables the Hudi client's auto-commit, accumulates all the batches of one checkpoint interval into a single, uncommitted Hudi instant, and hands the instant time plus write statuses to a newHudiSinkAggregatedCommitterviaHudiCommitInfo/HudiAggregatedCommitInfo. The committer only commits (or, on Spark, rolls back) the instant once the engine's checkpoint containing it has completed, using the standard SeaTunnel two-phase-commit (SinkAggregatedCommitter) extension point. The commit is idempotent (skips instants already on the completed timeline) and the failed-writes cleaning policy is switched toLAZYso Hudi doesn't roll back the still-pending instant out from under the committer. - One-sentence summary: Adds a genuine, checkpoint-gated two-phase-commit exactly-once mode to the Hudi sink, fully opt-in and backward compatible with the existing at-least-once behavior.
1. Code Change Review
1.1 Core Logic Analysis
Changed/added files (main):
config/HudiSemantics.java(new enum:AT_LEAST_ONCE,EXACTLY_ONCE)config/HudiSinkConfig.java(+semanticsfield, +isExactlyOnce(),serialVersionUIDbumped to2L)config/HudiSinkOptions.java(+SEMANTICSoption, defaultAT_LEAST_ONCE)exception/HudiErrorCode.java(+COMMIT_INSTANT_FAILED)sink/HudiSink.java(+createAggregatedCommitter(), +getAggregatedCommitInfoSerializer())sink/HudiSinkFactory.java(registersSEMANTICSas an optional option)sink/commit/HudiSinkAggregatedCommitter.java(new class:init/combine/commit/restoreCommit/abort/close)sink/state/HudiCommitInfo.java,sink/state/HudiAggregatedCommitInfo.java(new state/commit-info carriers)sink/writer/HudiRecordWriter.java(+exactlyOnceflag,instantTimeToWrite(),collectWriteStatuses(),prepareCommit(long), exactly-once-awareclose())sink/writer/HudiSinkWriter.java(threadsexactlyOnceinto both writer-construction call sites, addsprepareCommit(long checkpointId))util/HudiUtil.java(withAutoCommit(!isExactlyOnce()),withFailedWritesCleaningPolicy(LAZY if exactlyOnce else EAGER))
Before/after, the crux of the change (HudiRecordWriter):
// before
private void executeWrite() {
...
String writeInstantTime = writeClient.startCommit();
switch (hudiTableConfig.getOpType()) {
case INSERT: writeClient.insert(writeRecords, writeInstantTime); break;
...
}
writeRecords.clear();
}// after
private String instantTimeToWrite(HoodieJavaWriteClient<HoodieAvroPayload> writeClient) {
if (!exactlyOnce) {
return writeClient.startCommit();
}
if (pendingInstantTime == null) {
pendingInstantTime = writeClient.startCommit();
}
return pendingInstantTime;
}With EXACTLY_ONCE, every batch written between two checkpoints reuses the same pendingInstantTime instead of starting a new instant per batch (HudiRecordWriter.java:235-243); the accumulated WriteStatuses are collected into pendingWriteStatuses (HudiRecordWriter.java:245-249) and only handed off in prepareCommit(checkpointId) (HudiRecordWriter.java:263-279), which is the sole path that clears pendingInstantTime/pendingWriteStatuses.
Key Findings:
- The
AT_LEAST_ONCEpath is provably untouched in behavior:createAggregatedCommitter()returnsOptional.empty()for that mode (HudiSink.java:110-117), which is exactly the default theSeaTunnelSinkinterface already returned before this PR (seatunnel-api/.../SeaTunnelSink.java:125-128), andHudiSinkWriter.prepareCommitstill just flushes and reports nothing to commit when not exactly-once (HudiRecordWriter.java:263-267). Existing jobs that never setsemanticsget byte-for-byte identical runtime behavior. withFailedWritesCleaningPolicyis deliberately switched toLAZYonly for exactly-once (HudiUtil.java:198-212), with a comment explaining why: the defaultEAGERpolicy would roll back the very instant that is intentionally left inflight across a checkpoint boundary. This is the detail that makes the whole design work, and it's called out clearly.HudiSinkAggregatedCommitter.commitInstant()re-reads the active timeline and treats an already-completed instant as a no-op (HudiSinkAggregatedCommitter.java:182-192), which is what makescommit()/restoreCommit()idempotent for the failure-then-retry case, and this is exercised by a real (non-mocked) integration-style test.HudiSinkWriter.close()'s (viaHudiRecordWriter.close()) exactly-once branch deliberately does not flush and commit any leftover buffered records that never reached a checkpoint boundary (HudiRecordWriter.java:311-338) — it only warns if an instant is still pending. That is correct: those records were never durably checkpointed, so the source is expected to replay them, and writing them into an instant nobody will ever commit would just leave permanent orphaned metadata behind.HudiSinkAggregatedCommitter.init()is new code, and theSinkAggregatedCommitterinterface explicitly documents thatinit()"will be called not once, each retry will call this" (seatunnel-api/.../SinkAggregatedCommitter.java:36-38). See Issue 2 below — a retry that callsinit()again without an interveningclose()silently replaceswriteClientProvider/metaClientwithout closing the previousHoodieJavaWriteClient.
Runtime path (exactly-once), traced end to end:
SeaTunnelRow --> HudiSinkWriter.write()
--> HudiRecordWriter.writeRecord() [buffers by HoodieKey in LinkedHashMap]
--> (batch size reached OR timer FlushSignal on task thread)
--> HudiRecordWriter.flush() [synchronized]
--> executeWrite()/executeDelete()
--> instantTimeToWrite(): reuses pendingInstantTime, only the FIRST
call in the interval does writeClient.startCommit()
--> writeClient.insert/upsert/bulkInsert/delete(records, pendingInstantTime)
[[withAutoCommit(false)]] -- instant stays REQUESTED/INFLIGHT
--> collectWriteStatuses(): pendingWriteStatuses.addAll(...)
--- checkpoint barrier reaches the sink task ---
HudiSinkWriter.prepareCommit(checkpointId)
--> HudiRecordWriter.prepareCommit(checkpointId)
--> flush() [drains any residual buffered batch]
--> builds HudiCommitInfo(checkpointId, pendingInstantTime, copy of pendingWriteStatuses)
--> clears pendingInstantTime / pendingWriteStatuses
--> returned to the engine as this writer's per-checkpoint commit message
--- engine collects all writers' HudiCommitInfo for the checkpoint ---
HudiSinkAggregatedCommitter.combine(commitInfos)
--> drops null / no-instant entries --> HudiAggregatedCommitInfo (this is the
committer's CHECKPOINTED STATE)
--- checkpoint completes ---
HudiSinkAggregatedCommitter.commit(aggregatedCommitInfos)
--> for each HudiCommitInfo: commitInstant()
--> reloadActiveTimeline()
--> if instant already completed: skip (idempotent)
--> else if instant missing from active timeline: throw COMMIT_INSTANT_FAILED
--> else: writeClient.commit(instantTime, writeStatuses, Option.empty())
[instant becomes COMPLETED, records become visible]
--- on restart from a checkpoint whose commit may have been lost ---
HudiSinkAggregatedCommitter.restoreCommit(aggregatedCommitInfos) --> commit(...) [same idempotent path]
--- checkpoint aborted (Spark only, per SinkAggregatedCommitter contract) ---
HudiSinkAggregatedCommitter.abort(aggregatedCommitInfos)
--> rollbackInstant(): rolls back the instant if not already completed
This does reach the real production write path, not just a recovery corner: every batch write in exactly-once mode goes through instantTimeToWrite()/collectWriteStatuses(), and every checkpoint completion goes through the new committer. This is not an isolated boundary-only change.
1.2 Compatibility Impact
Fully compatible.
- New option
semanticsdefaults toAT_LEAST_ONCE, and that code path is unchanged in behavior (see Key Finding 1). Existing jobs with nosemanticskey parse and run identically. HudiSinkConfigbumpedserialVersionUIDfrom (implicit default before this change) to explicit2Lbecause a field was added to aSerializableclass; this class is not part of any persisted checkpoint/savepoint state (it is only reconstructed from the job's own config at each run), so this does not affect restore-from-old-checkpoint compatibility.- The new
HudiCommitInfo/HudiAggregatedCommitInfoare brand new state/commit-info types with their own explicitserialVersionUIDs; there is no prior on-disk/checkpoint format to be compatible with since the aggregated committer for Hudi did not exist before this PR (createAggregatedCommitter()previously fell through to the interface defaultOptional.empty()). - Multi-table sink support (
SupportMultiTableSink,HudiSinkWriter implements SupportMultiTableSinkWriter<HudiClientManager>) pre-dates this PR and is verified intact:HudiSinkstill implementsSupportMultiTableSink(HudiSink.java:53-57, unchanged by this diff),createWriter()still returns aSupportMultiTableSinkWriter(HudiSinkWriter.java:41-43, unchanged), andSinkConnectorCommonOptions.MULTI_TABLE_SINK_REPLICAis still inoptionRule().optional(...)(HudiSinkFactory.java:72, pre-existing, onlySEMANTICSwas newly added on the line above it). TheexactlyOnceflag is correctly threaded into both places aHudiRecordWriteris constructed, including the multi-table resource-manager re-initialization path (HudiSinkWriter.java:140-145), so multi-table sink usage is not silently downgraded to a different semantics than configured. - No public API, protocol, or default value of any existing option changes.
1.3 Performance / Side-Effect Analysis
- CPU/memory: exactly-once mode buffers
WriteStatusobjects for the whole checkpoint interval inpendingWriteStatuses(HudiRecordWriter.java:96) instead of discarding them after each auto-committed batch. This is bounded by data volume per checkpoint interval and is the expected cost of 2PC — not a regression versus not supporting exactly-once at all, but worth calling out that a very long checkpoint interval combined with a very large per-interval volume will grow this list proportionally; that's inherent to the feature, not a bug. - Networking/metadata IO:
HudiSinkAggregatedCommitter.commitInstant()androllbackInstant()each callreloadActiveTimeline()(HudiSinkAggregatedCommitter.java:184,:214), and both are invoked once perHudiCommitInfoinside thecommit()/abort()loops (HudiSinkAggregatedCommitter.java:127-136,:164-173), i.e. once per parallel writer subtask, per checkpoint. For jobs with meaningful sink parallelism this means N timeline reloads (each a metadata read against the underlying filesystem, e.g. S3/HDFS) per checkpoint where a single reload percommit()/abort()call would suffice, since all commit infos in one call share the same table/timeline. This is a real, avoidable per-checkpoint IO cost that scales with parallelism (see Issue 3). - Concurrency safety:
instantTimeToWrite()/collectWriteStatuses()mutate plain (non-volatile, non-synchronized)pendingInstantTime/pendingWriteStatusesfields, called fromexecuteWrite()/executeDelete()inside the pre-existingsynchronized flush(), whileprepareCommit()reads/clears them right after callingflush()but outside any lock (HudiRecordWriter.java:263-279). This mirrors the pre-existing (not introduced by this PR) synchronization pattern ofwrite()/flush()/close()in this class, which relies on Zeta's single task-thread execution model (write, timer-flush and checkpoint-barrier processing are documented to run in order on the same task thread, per the writer's own comment atHudiSinkWriter.java:148-151). Given that pre-existing assumption already underlies this file's design, this PR does not introduce a new race beyond what already existed; flagged here only as a design note, not a new defect. - Idempotency/retries: commit is correctly idempotent via the completed-instant check; rollback is correctly a no-op once already completed/absent (
rollbackInstant,HudiSinkAggregatedCommitter.java:212-225). - Resource release:
HudiSinkAggregatedCommitter.close()correctly guardswriteClientProvider != nullbefore closing.HudiWriteClientProvider.close()already swallows/logs exceptions defensively (pre-existing). See Issue 2 for the one real resource-release gap this PR introduces (a re-init()on retry without closing the previous client).
1.4 Error Handling and Logging
Error handling is generally sound: commitInstant() fails loudly (COMMIT_INSTANT_FAILED) instead of silently skipping when an instant has disappeared from the active timeline, which is exactly the right choice for a data-integrity-sensitive path, and this is covered by a real test (HudiTwoPhaseCommitTest.shouldRollbackTheInstantOfAnAbortedCheckpoint, asserting the commit throws instead of losing data silently). No sensitive information (credentials, tokens) is logged anywhere in the diff.
Issue 1
- Location:
seatunnel-connectors-v2/connector-hudi/src/main/java/org/apache/seatunnel/connectors/seatunnel/hudi/sink/writer/HudiRecordWriter.java:311-338(close()) - Problem: When
exactlyOnceis true and the writer is closed while an instant is still pending, the code only emits aLOG.warnand does not report this condition anywhere the engine or an operator would reliably see it (it's a per-writer-subtask log line, easy to miss in a large cluster). This is the visible symptom of configuringsemantics = EXACTLY_ONCEwithout checkpointing actually enabled/completing: the job can run to completion and never make a single row visible in Hudi, discovered only by noticing a WARN log or an empty table. - Potential risk: Silent "wrote nothing durable" outcome for an entire job run, discoverable only through log inspection, not through job status/metrics.
- Best improvement: Given the
SinkWriter/SinkAggregatedCommitterAPI currently gives connectors no way to query whether checkpointing is enabled (confirmed: no such accessor exists onSinkWriter.Contextor the sink API in this codebase), a hard fail-fast isn't feasible from inside this connector. A pragmatic improvement is to raise this toLOG.error(or route through the metrics/status-reporting path the engine already exposes for writer close, if any) so it is not lost among routine INFO/WARN noise, and to repeat the same warning inHudiSinkAggregatedCommitter.close()/restoreCommit()if a job is torn down with pending, never-committed aggregated state. - Severity: Medium
- Raised by another reviewer: No
Issue 2
- Location:
seatunnel-connectors-v2/connector-hudi/src/main/java/org/apache/seatunnel/connectors/seatunnel/hudi/sink/commit/HudiSinkAggregatedCommitter.java:88-105(init()) - Problem:
SinkAggregatedCommitter.init()is documented by the framework as being callable more than once on the same instance ("this method will be called not once. Each retry will call this",seatunnel-api/src/main/java/org/apache/seatunnel/api/sink/SinkAggregatedCommitter.java:36-38). This PR'sinit()unconditionally assigns a brand newwriteClientProviderandmetaClient, without checking whether a previouswriteClientProvideralready holds an openHoodieJavaWriteClientand closing it first. - Potential risk: On a retry that re-invokes
init()without an interveningclose(), the previousHoodieJavaWriteClient(and whatever internal resources it holds — executor/engine context, file handles) is dereferenced and leaked rather than closed. - Best improvement: In
init(), close the existingwriteClientProviderif non-null before creating the replacement, mirroring the guard already used inclose(). - Severity: Medium
- Raised by another reviewer: No
Issue 3
- Location:
seatunnel-connectors-v2/connector-hudi/src/main/java/org/apache/seatunnel/connectors/seatunnel/hudi/sink/commit/HudiSinkAggregatedCommitter.java:124-136and:163-173(commit()/abort()), callingreloadActiveTimeline()inside the per-HudiCommitInfoloop - Problem: The active timeline is reloaded from storage once per
HudiCommitInforather than once percommit()/abort()invocation, even though every commit info processed in one call belongs to the same table/timeline. - Potential risk: Unnecessary, parallelism-scaled metadata IO against the underlying filesystem (S3/HDFS/etc.) on every checkpoint completion; on tables with many parallel writer subtasks this multiplies timeline-listing calls without changing correctness.
- Best improvement: Reload the timeline once per
commit(List<HudiAggregatedCommitInfo>)/abort(...)call (e.g., right after flattening allHudiCommitInfos) and reuse it for every instant check inside that call. - Severity: Medium
- Raised by another reviewer: No
Issue 4
- Location:
seatunnel-connectors-v2/connector-hudi/src/main/java/org/apache/seatunnel/connectors/seatunnel/hudi/sink/commit/HudiSinkAggregatedCommitter.java:156-162(Javadoc onabort()) - Problem: The Javadoc states "Zeta never aborts a checkpoint without restarting the pipeline ... so this is the best-effort path for the other engines," which reads as if
abort()plays an active role on Zeta/Flink. TheSinkAggregatedCommitterinterface itself documentsabort()as being invoked "Only on Spark engine at now" (seatunnel-api/.../SinkAggregatedCommitter.java:65-71), i.e. it currently isn't called at all on Zeta or Flink. - Potential risk: Low — this is a documentation-precision issue, not a functional one. The actual safety net for Zeta/Flink is correctly implemented elsewhere: the
LAZYfailed-writes-cleaning-policy plus Hudi's own writer-heartbeat expiry (HudiUtil.java:198-212), which the writer-side Javadoc describes correctly (HudiSinkWriter.java:105-113). A future reader could be misled into thinkingabort()is doing real work on Zeta today when it currently is not exercised there. - Best improvement: Tighten the
abort()Javadoc to explicitly say it is currently invoked only by the Spark engine per the interface contract, and that Zeta/Flink recovery relies entirely on the heartbeat-basedLAZYcleaning policy. - Severity: Low
- Raised by another reviewer: No
2. Code Quality Assessment
2.1 Coding Standards
Every new core method (instantTimeToWrite, collectWriteStatuses, prepareCommit, combine, commit, restoreCommit, abort, commitInstant, rollbackInstant) and every new nontrivial field (exactlyOnce, pendingInstantTime, pendingWriteStatuses, HudiCommitInfo's three fields, HudiAggregatedCommitInfo.commitInfos) has an explanatory Javadoc or field comment describing purpose, lifecycle and constraints — this is well above the bar and clearly reflects a deliberate effort to make the exactly-once contract legible. No missing-comment issues found on the new code.
As a minor, pre-existing (not introduced by this PR) aside: the module already has an apparently unused, orphaned pair of classes at org.apache.seatunnel.connectors.seatunnel.hudi.state.HudiSinkState/HudiCommitInfo (old package, no serialVersionUID), distinct from the actively used org.apache.seatunnel.connectors.seatunnel.hudi.sink.state package this PR extends. Not touched by this diff and not a blocker here, but worth a follow-up cleanup since it could confuse future contributors about which HudiCommitInfo is live.
2.2 Test Coverage and Test Stability
Coverage is strong and, importantly, uses real assertions against a real (local, @TempDir-backed) Hudi table rather than mocks:
HudiTwoPhaseCommitTest(new, 303 lines) verifies, against an actualHoodieTableMetaClient/timeline: (1) all batches of one checkpoint share a single instant and it stays uncommitted until the committer runs; (2) the committer's commit is idempotent (running it twice does not duplicate records or re-commit); (3) an aborted checkpoint's instant is rolled back and a subsequent commit attempt against it fails loudly instead of silently losing data; (4) the defaultAT_LEAST_ONCEsemantics still commits every batch immediately (regression guard for Key Finding 1). Each of these assertions would legitimately fail if the corresponding production logic were broken (e.g., revertinginstantTimeToWrite()'s reuse ofpendingInstantTimewould break the "one instant per checkpoint" assertion; reverting the completed-instant skip incommitInstant()would break the idempotency assertion and inflatetotalRecords).HudiSinkAggregatedCommitterTest(new, 118 lines) verifiescombine()correctly drops writers with nothing to commit, and thatHudiAggregatedCommitInfo/HudiCommitInfosurvive a realDefaultSerializerround trip (exercises the actual checkpoint-state serialization path, not a stand-in).HudiSinkConfigTest(new, 70 lines) verifies the default semantics, explicitEXACTLY_ONCEparsing, and that an unknown enum value fails config parsing.- New e2e
testWriteHudiWithExactlyOnceSemanticsinHudiIT.javaruns a real batch job withcheckpoint.interval = 1000against the exactly-once sink and asserts the expected row count viaParquetReaderafter the job completes.
Stability rating: Stable, with one caveat carried over from the file's pre-existing convention rather than newly introduced by this PR — testWriteHudiWithExactlyOnceSemantics uses given().ignoreExceptions().await().atMost(60000, ...) (HudiIT.java:158-174), which is a weak-readiness pattern (swallowing exceptions while polling) in the abstract, but it is exactly the same pattern already used by the two pre-existing test methods in this same file (testWriteHudi, testWriteHudiWithOmitConfigItem), so this PR does not lower the bar versus what already exists here; it's Low severity and consistent with established local convention, not a new regression risk. HudiTwoPhaseCommitTest correctly uses @DisabledOnOs(OS.WINDOWS) for the same reason the rest of the Hudi test suite already skips Windows (Hadoop/native-path issues), matching the CI evidence in this PR's own comments that connector-hudi unit tests (including the skipped-on-Windows two-phase-commit test) pass in every attempted CI run. No hard sleeps, no floating-point-without-delta, no order-dependence, and resources (writer.close()/committer.close()) are released in finally blocks throughout the new tests.
2.3 Documentation Updates
Both docs/en/connectors/sink/Hudi.md and docs/zh/connectors/sink/Hudi.md are updated and consistent with each other and with the implementation: the feature matrix checkbox for exactly-once is flipped, the semantics option is documented in the options table and its own ### semantics [Enum] section, and a new "Exactly-once semantics" section walks through the mechanism (how it works, requirements/trade-offs, including the correct call-out that checkpointing must be enabled and that visibility latency becomes at least one checkpoint interval, and the single-writer-per-table concurrency caveat inherited from Hudi itself). This is genuinely good documentation — it explains the why, not just the what, and both languages say the same thing.
3. Architectural Soundness
3.1 Elegance of the Solution
Long-term solution. This is not a workaround: it reuses the framework's existing SinkAggregatedCommitter/CommitInfoT/AggregatedCommitInfoT extension point exactly as other two-phase-commit sinks in this codebase do, and it leans on Hudi's own instant/timeline/heartbeat machinery (auto-commit toggle, failed-writes cleaning policy) rather than inventing a parallel bookkeeping mechanism. The design correctly separates "write into an instant" (writer-side, in-memory, replayable) from "commit the instant" (committer-side, checkpoint-gated, idempotent, restorable), which is the right shape for this problem.
3.2 Maintainability
Good. The new classes are small, single-purpose, and heavily commented on intent rather than mechanics. The two Medium issues above (retry-time resource leak in init(), per-commit-info timeline reload) are both narrow, local fixes that don't require restructuring anything.
3.3 Extensibility
The HudiSemantics enum and the isExactlyOnce() boolean threaded through HudiSinkConfig/HudiRecordWriter/HudiUtil give a clean seam if a third semantics mode were ever needed, without touching the at-least-once path.
3.4 Historical-Version Compatibility
No impact on historical jobs, checkpoints, or savepoints: the new committer, state, and commit-info types did not exist before this PR (there was no aggregated committer for Hudi at all), so there is nothing for them to be incompatible with, and the at-least-once path — which is what every pre-existing job configuration uses by default — is unchanged in behavior.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | close() silently warns (log-only) instead of surfacing that an exactly-once job produced no committed output; no fail-fast possible given current API |
HudiRecordWriter.java:311-338 |
Medium |
| 2 | init() can be called again on retry per the SinkAggregatedCommitter contract, but doesn't close a previously-created writeClientProvider/client first |
HudiSinkAggregatedCommitter.java:88-105 |
Medium |
| 3 | Active timeline reloaded once per HudiCommitInfo instead of once per commit()/abort() call, scaling metadata IO with parallelism |
HudiSinkAggregatedCommitter.java:124-136, :163-173 |
Medium |
| 4 | abort() Javadoc overstates its role on Zeta/Flink versus the interface's documented Spark-only invocation |
HudiSinkAggregatedCommitter.java:156-162 |
Low |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
There are no prior reviews on this PR to agree or disagree with (this is the first formal review). CI is currently red, but the failure is conclusively unrelated to this change: the only failing lane is unit-test (11, windows-latest) (apache-side "Build" check is just a pointer to the actual run in the contributor's fork), and it fails in connector-http-paypal's PayPalClientTest#closeWakesRetryWait — a pre-existing, already-tracked timing flake (#12381), reproduced identically across four separate reruns, in a module this PR does not touch. I independently confirmed from the repository history that origin/dev already contains the prior mitigation for this flake (#12370, "widen PayPalClientTest's loopback HTTP wait budget") at a commit that predates this PR's base, and that #12370 is not sufficient — the actual root-cause fix (#12444) is still open/unmerged. Syncing this branch to latest dev would not fix this failure since the real fix hasn't landed anywhere yet. connector-hudi's own unit tests and the new connector-hudi-e2e case (including the new exactly-once test) pass in every attempt of this CI run. This CI failure is not a blocker.
-
Blockers — must be fixed (sorted by severity, CI-only findings excluded per policy): none of the findings above are release-blocking data-correctness bugs — the core two-phase-commit mechanism (instant reuse, checkpoint-gated commit, idempotency, rollback-then-fail-fast) is correct and is backed by real, failure-capable tests. However, given this is a durability feature, I'd still like to see Issues 1 and 2 addressed before merge, since they touch exactly the failure/retry paths this feature exists to make safe:
- Issue 2 (Medium): guard
init()against leaking a previousHoodieJavaWriteClienton retry — small, local fix. - Issue 1 (Medium): elevate the "job finished without committing anything" signal above a routine WARN log, since there's currently no other way an operator would notice a misconfigured (
EXACTLY_ONCE+ checkpoint disabled) job silently wrote nothing durable.
- Issue 2 (Medium): guard
-
Recommended fixes — non-blocking:
- Issue 3 (Medium, but non-blocking): reload the active timeline once per
commit()/abort()call instead of per commit info — a straightforward efficiency improvement, not a correctness bug, and unlikely to matter until sink parallelism is large. - Issue 4 (Low): tighten the
abort()Javadoc to match the interface's documented Spark-only invocation, since the actual Zeta/Flink safety net (heartbeat-basedLAZYcleaning policy) is already correct and separately, correctly documented.
- Issue 3 (Medium, but non-blocking): reload the active timeline once per
Overall assessment: This is a well-designed, well-tested addition that finally gives the Hudi sink a real exactly-once mode built on the framework's standard two-phase-commit extension point rather than a bespoke mechanism, and it does not touch or risk the existing at-least-once behavior at all. The Medium findings are narrow and local (a missing close-before-replace guard, and a log-visibility gap), not architectural problems. I don't see a meaningfully different alternative implementation worth trading off here — reusing SinkAggregatedCommitter plus Hudi's own instant/heartbeat machinery is the natural fit, and the PR does exactly that.
The Hudi sink commits every flushed batch with the Hudi client auto-commit, so the data becomes visible before the checkpoint that contains it completes. When a job fails and the source replays the records of a checkpoint that never completed, those records are committed again. This commit adds an opt-in two-phase commit write path: * new `semantics` sink option, `AT_LEAST_ONCE` (default, unchanged behavior) or `EXACTLY_ONCE`; * with `EXACTLY_ONCE` the write client auto-commit is disabled, all the batches of one checkpoint are written into the same Hudi instant and the instant is only committed after the checkpoint completes; * the aggregated committer commits the instants of the checkpoints that completed, restores and commits them again when a commit was lost, and skips the instants that are already committed, so a failure never publishes the records twice; * the instants of a checkpoint that never completed are not committed: the source replays the records and Hudi rolls the orphan instants back when the writer heartbeat expires. A commit whose instant is already gone fails the job with an explicit error instead of losing data silently; * the failed writes cleaning policy is set to `LAZY` for the exactly-once semantics, because the default `EAGER` policy rolls back the instants that are still waiting for their checkpoint commit. Tests: HudiTwoPhaseCommitTest runs the writer and the committer against a real local Hudi table and checks that the records are invisible until the checkpoint commit, that the commit is idempotent and that the instant of an aborted checkpoint is rolled back. HudiSinkAggregatedCommitterTest covers the commit info state serialization and HudiSinkConfigTest covers the new option. The e2e module gets a job with the exactly-once semantics.
666ae11 to
a37bc87
Compare
|
CI is green on this head. I rebased the branch onto the latest Run: https://github.com/corgy-w/seatunnel/actions/runs/38150418277 —
The new exactly-once e2e case runs against the real containers and passes on both engines it is scheduled on: Local verification of the rebased head (
The rebase also resolved the conflicts in |
… review Address the review findings of the Hudi sink exactly-once change: * release the write client of a previous attempt before init() replaces it, the SinkAggregatedCommitter contract allows a retry to call init() again * reload the active timeline once per commit()/abort() call instead of once per commit info, so the metadata IO does not scale with the sink parallelism * report the instants that a job ends without committing at ERROR level, in both the writer and the committer, because an exactly-once job that never completed a checkpoint otherwise writes nothing durable silently * tighten the abort() javadoc to the documented Spark-only invocation * remove the unused state package that duplicated the live commit info types
|
@DanielLeens thanks for the detailed review — all four findings are addressed in
I also removed the unused Local verification on the new head (JDK 11):
CI is re-running on the new head; I will report the result here once it finishes. |
DanielLeens
left a comment
There was a problem hiding this comment.
Thank you @corgy-w for the quick and thorough follow-up. All four findings from my previous review are properly addressed in 393edcfc (init() closes the previous client, one timeline reload per commit()/abort(), ERROR-level signal on both writer and committer, corrected abort() Javadoc, and removal of the dead hudi.state package). I re-reviewed the whole PR at the new head, this time reading the Hudi 0.15.0 client sources that the design depends on, and I found problems in the heartbeat/LAZY-cleaning design that I should have caught the first time.
What Problem Does This PR Solve?
- Pain point: the Hudi sink always relied on Hudi client auto-commit, so every flushed batch was committed independently of the engine checkpoint. A restart could re-write already committed records, and exactly-once was not possible.
- Fix approach: opt-in
semantics = EXACTLY_ONCE. Writers disable auto-commit, write all batches of one checkpoint interval into one uncommitted instant, and handHudiCommitInfo(checkpointId, instantTime, writeStatuses)to a newHudiSinkAggregatedCommitter, which commits the instant after the checkpoint completes (idempotent via the active timeline). The failed-writes cleaning policy is switched toLAZYso Hudi does not roll the pending instant back. - One-sentence summary: a checkpoint-gated two-phase-commit mode for the Hudi sink, default behavior unchanged; the two-phase structure is right, but the reliance on Hudi's LAZY/heartbeat machinery breaks the recovery path and leaks resources in long-running jobs.
1. Code Change Review
1.1 Core Logic Analysis
Delta since my last review (666ae11f to 393edcfc): the four review items above, plus a rebase onto latest dev (CI fix #12444 is now included). Overall PR: new HudiSemantics, semantics option, HudiSinkAggregatedCommitter, HudiCommitInfo/HudiAggregatedCommitInfo, writer changes (instantTimeToWrite, prepareCommit(long)), HudiUtil (withAutoCommit(!exactlyOnce), LAZY policy), docs en/zh, unit tests, one E2E case.
Key findings:
- The default (
AT_LEAST_ONCE) path is unchanged: no aggregated committer,prepareCommitreturns empty, auto-commit stays on, EAGER cleaning stays. Existing jobs are not affected. - The core two-phase mechanics are correct for the happy path: one shared instant per checkpoint interval (
HudiRecordWriter.java:235-243), state handed off only inprepareCommit(:263-279), commit gated on the checkpoint, idempotent skip of completed instants (HudiSinkAggregatedCommitter.java:218-228). - The design leans entirely on Hudi's LAZY policy and writer heartbeat to keep the pending instant alive. In Hudi 0.15.0 this has three consequences the PR does not handle (Issues 1-3 below).
- The checkpoint state carries Hudi
WriteStatusobjects (Java-serialized), not just the commit stats (Issue 4).
Runtime path (exactly-once) with the failure points marked:
Writer subtask (HoodieJavaWriteClient W, LAZY):
write()/timer flush -> flush() -> startCommit() [W starts a heartbeat Timer thread for this instant,
BaseHoodieWriteClient.java:941 -> HoodieHeartbeatClient.start]
-> insert/upsert(records, pendingInstantTime) [auto-commit off, instant INFLIGHT]
-> pendingWriteStatuses.addAll(...)
checkpoint barrier -> prepareCommit(cpId) -> HudiCommitInfo(cpId, instant, copy of WriteStatus list)
pendingInstantTime = null (W's heartbeat Timer for that instant keeps running)
| (Java-serialized into the committer checkpoint state)
v
Committer (separate HoodieJavaWriteClient C):
checkpoint complete -> commit() -> reload timeline -> commitInstant()
-> C.commit(instant, writeStatuses)
-> commitStats -> HeartbeatUtils.abortIfHeartbeatExpired(instant) <-- LAZY: throws if the
heartbeat file of the instant is older than interval*misses, C has no local heartbeat
for it so it reads the file written by W
restore after failure -> restoreCommit() -> same call, possibly minutes/hours after W died
(and a new writer's startCommit() may already have lazily rolled the instant back)
1.2 Compatibility Impact
Fully compatible. The default semantics, config keys and at-least-once runtime behavior are unchanged, and the new state types did not exist before. One documentation caveat: switching an existing checkpointed job from EXACTLY_ONCE back to AT_LEAST_ONCE orphans any pending instants stored in the committer state (Issue 7, Low).
1.3 Performance / Side-Effect Analysis
Evaluated at the baseline of a continuously running, high-volume job (billions of rows, checkpoints every few seconds to minutes): see Issues 2 and 4. The default path has no new overhead.
1.4 Error Handling and Logging
Issue 1 (High, new, missed in my last review - sorry for missing this): commit and restore of a pending instant depend on a live writer heartbeat, so the recovery path fails after a slow restart
- Location:
HudiSinkAggregatedCommitter.java:218-240(commitInstant,writeClient.commit(...)),HudiUtil.java:~178-212(LAZY policy), docs claim indocs/en/connectors/sink/Hudi.md"How it works" item 3. - Problem: with
LAZY,BaseHoodieWriteClient.commitStatscallsHeartbeatUtils.abortIfHeartbeatExpired(instantTime, ...)(Hudi 0.15.0BaseHoodieWriteClient.java:230,HeartbeatUtils.java:96-108). The committer's client C never started a heartbeat for this instant, soHoodieHeartbeatClient.isHeartbeatExpiredfalls back to the heartbeat file on storage that only the (possibly dead) writer refreshes. Once the writer is gone for longer thanhoodie.client.heartbeat.interval_in_ms * tolerable.misses(60s * 2 by default),restoreCommit()throwsHoodieException: Heartbeat ... has expired. In addition, any writer started after the restart callsstartCommit(), which under LAZY rolls back every inflight instant with an expired heartbeat, including the instants of an already completed checkpoint, beforerestoreCommitruns. ThencommitInstantthrowsCOMMIT_INSTANT_FAILED. - Risk: the exact scenario this feature exists for (job fails between checkpoint completion and commit, then restores) loses the data of that checkpoint permanently: the source will not replay it because the checkpoint completed, and the job cannot restart successfully from that checkpoint. A fast automatic Zeta pipeline restart (a few seconds) will usually pass; savepoint resume, cluster restart, slow resource scheduling or a long backoff will not. The docs currently promise the opposite.
- Best improvement: do not tie the commit of an already-checkpointed instant to the writer heartbeat. For example, in the committer refresh the heartbeat for the instant right before committing (start a
HoodieHeartbeatClientfor it on the committer side, then stop it after the commit), and guard against the lazy rollback race (for example commit/restore before writers are allowed to callstartCommit, or keep the heartbeat tolerance configurable and documented). Whatever approach is chosen, add a test in which the writer is closed, the heartbeat is made stale (small interval and misses, or a stale heartbeat file), andrestoreCommitis run, and fix or correct the docs. - Raised by another reviewer: no.
Issue 2 (High, new, missed in my last review): the writer never stops the per-instant heartbeat, so a long-running exactly-once job leaks one thread and one periodic storage write per checkpoint
- Location:
HudiRecordWriter.java:235-279(instantTimeToWrite,prepareCommit),HudiSinkAggregatedCommitter.java:238-247. - Problem: under LAZY, every
startCommit()starts a heartbeat in the writer's client with its own daemonjava.util.Timerthread (Hudi 0.15.0HoodieHeartbeatClient.start,Heartbeat.timer = new Timer(true)). In the normal Hudi flow the same client callscommit(), which callsheartbeatClient.stop(instant)and deletes the heartbeat file. Here the commit is performed by a different client C, whosestop(instant)is a no-op for an instant it did not start (HoodieHeartbeatClient.stop,isHeartbeatStarted(null)is false), so the writer's timer keeps running and rewriting.hoodie/.heartbeat/<instant>every interval until the writer client is closed, and the heartbeat file of a committed instant is never deleted. - Risk: at checkpoint interval T the writer accumulates 1 thread and 1 storage PUT per interval per minute for each historical instant: with 10s checkpoints that is about 8,600 threads per writer subtask per day (native thread exhaustion / OOM) and rapidly growing S3/HDFS write amplification, on exactly the long-running streaming workloads where exactly-once matters. The unit tests close the writer immediately, so this is invisible to them.
- Best improvement: after
prepareCommithands an instant off, stop its writer-side heartbeat timer, but keep a heartbeat-refresh mechanism on the committer side until the instant is committed (see Issue 1), and delete the heartbeat file on commit/rollback. If the Hudi client API does not expose this, consider a dedicated heartbeat component owned by the committer, or using theEAGERpolicy with a single committer-owned instant lifecycle, and document the choice. - Raised by another reviewer: no.
Issue 3 (Medium, new): write errors are committed silently in a mode that claims exactly-once
- Location:
HudiRecordWriter.java:192-222,:245-249,HudiSinkAggregatedCommitter.java:240. - Problem: the returned
WriteStatuslist is stored buthasErrors()/getTotalErrorRecords()is never checked before the instant is handed to the committer or committed. In at-least-once mode this was the existing behavior, but in the new mode the whole value proposition is that a committed checkpoint contains all of its records. - Risk: records that Hudi rejected per record (payload/schema conversion failures) are dropped from a checkpoint that is then marked complete and never replayed.
- Best improvement: fail
prepareCommit(orcommitInstant) with a clearHudiConnectorExceptionwhen any status has errors, including the first error key/cause. - Raised by another reviewer: no.
Issue 4 (Medium, new): the checkpoint state and writer memory scale with the number of records per checkpoint, and the state is a Hudi internal class
- Location:
HudiCommitInfo.java(List<WriteStatus> writeStatuses),HudiRecordWriter.java:96,:245-249,HudiSink.java(DefaultSerializerfor commit info). - Problem:
WriteStatusis Java-serialized into the committer checkpoint state. In Hudi 0.15.0 it keeps aHoodieRecordDelegatefor every written record wheneverHoodieTable.shouldTrackSuccessRecords()is true (non-implicit index such as the supportedINMEMORYindex, or metadata partitions such as the record index), and it keeps aThrowablemap for failures.pendingWriteStatusesalso grows for the whole checkpoint interval in the writer heap. - Risk: at billions of rows per job and long checkpoint intervals, the checkpoint state size and writer heap grow with the data volume, and the persisted format is tied to Hudi's internal class layout (a Hudi upgrade can break restoring old checkpoints).
- Best improvement: persist only what the commit needs, the
List<HoodieWriteStat>(obtained fromWriteStatus.getStat()), and commit withcommitStats(...); this keeps the state small and independent of the tracked-records setting. Add a serialize/deserialize round-trip test ofHudiAggregatedCommitInfothroughDefaultSerializer. - Raised by another reviewer: no.
Issue 5 (Medium, new): test and E2E coverage does not exercise any failure, restore or long-running path
- Location:
HudiTwoPhaseCommitTest.java,HudiIT#testWriteHudiWithExactlyOnceSemantics,fake_to_hudi_exactly_once.conf. - Problem: every unit test closes the writer immediately and commits within seconds in one JVM, so it cannot fail on Issues 1 and 2. The E2E is a short BATCH job with parallelism 1 and checks only the final row count; it does not kill a task between checkpoint completion and commit, does not use several checkpoints, and does not check that there is exactly one commit per checkpoint.
- Best improvement: add (a) a stale-heartbeat restoreCommit test, (b) a multi-checkpoint writer test that asserts the number of live heartbeat timers/files, (c) a fault-injection E2E that fails the job between checkpoint complete and commit and asserts no duplicates/no loss.
Issue 6 (Low): close-time signal is still log-only
- Location:
HudiRecordWriter.java:311-330,HudiSinkAggregatedCommitter.java:192-207. - Problem: both are now ERROR logs (thank you, that addresses my previous Issue 1), but a job that ends with an uncommitted instant still reports success. Acceptable as is given the API limits; please keep it documented.
Issue 7 (Low): docs overstate the guarantees and miss two caveats
- Location:
docs/en/connectors/sink/Hudi.md,docs/zh/connectors/sink/Hudi.md, section "Exactly-once semantics". - Problem: item 3 promises that the job re-commits after restoring, with no mention of the heartbeat window (Issue 1); there is no note about the heartbeat settings, or about switching a running job back to
AT_LEAST_ONCE, which orphans pending instants.
2. Code Quality Assessment
2.1 Coding Standards
Good. The new classes have Javadoc with intent and constraints, the unused duplicate hudi.state package is gone, and field comments explain lifecycle. The remaining standards points are covered by Issues 1-4.
2.2 Test Coverage and Test Stability
The new tests use real local Hudi tables and can fail on regressions of the happy path (shared instant, no premature visibility, idempotent commit, rollback on abort, per-batch commit in at-least-once). They cannot fail on the failure/recovery behavior and the long-running behavior discussed above (Issue 5). No Thread.sleep or fixed ports in the new tests. Stability rating: Risk present (coverage gap, not flakiness).
2.3 Documentation Updates
en and zh updated, feature matrix ticked, new option documented. Needs the corrections from Issue 7.
3. Architectural Soundness
3.1 Elegance
Long-term solution in structure (standard SinkAggregatedCommitter, instant per checkpoint, idempotent commit). The weak spot is delegating liveness of a prepared-but-uncommitted instant to a heartbeat owned by a different Hudi client than the one that commits it.
3.2 Maintainability
Small, focused classes; after the Issue 1/2 fix the heartbeat ownership should be isolated in one place.
3.3 Extensibility
The HudiSemantics seam is clean.
3.4 Historical-Version Compatibility
No impact on existing jobs or checkpoints (at-least-once is unchanged, new state types are new). The WriteStatus-in-state choice (Issue 4) is a future-compatibility concern for the new state itself.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | Commit/restoreCommit depend on a live writer heartbeat under LAZY; slow restore fails or the instant is lazily rolled back, losing a completed checkpoint | HudiSinkAggregatedCommitter.java:218-240, HudiUtil.java LAZY policy |
High |
| 2 | Writer never stops per-instant heartbeat timers/files: one thread and one storage write per minute per checkpoint, unbounded | HudiRecordWriter.java:235-279, HudiSinkAggregatedCommitter.java:238-247 |
High |
| 3 | WriteStatus errors are never checked; failed records are committed in a completed checkpoint |
HudiRecordWriter.java:192-249 |
Medium |
| 4 | Checkpoint state/heap carries full WriteStatus (scales with records, Hudi-internal format) instead of HoodieWriteStat |
HudiCommitInfo.java, HudiRecordWriter.java:96,245-249 |
Medium |
| 5 | No failure/restore/multi-checkpoint test; current tests cannot catch Issues 1-2 | HudiTwoPhaseCommitTest.java, HudiIT.java |
Medium |
| 6 | End-of-job uncommitted instant is only an ERROR log | HudiRecordWriter.java:311-330 |
Low |
| 7 | Docs overstate recovery guarantee, miss heartbeat and downgrade caveats | `docs/en | zh/connectors/sink/Hudi.md` |
Issues 1 and 2 were not raised in my previous review or by anyone else; I am raising them now as carryover from my own miss.
5. Merge Recommendation
CI state: the check on head 393edcfc is still queued/in progress in the contributor fork at the time of this review, so CI has not passed yet. The author reports a green fork run on the previous rebased head 1ebda7ca (including the unit-test (11, windows-latest) job and connector-hudi-e2e); I did not re-verify it, and the new head needs its own result. The PR is not behind dev and a sync is not needed. Merge state is BLOCKED only by the required review.
Conclusion: Not recommended for merge
- Blockers - must be fixed
- Issue 1 (High): make commit and restoreCommit independent of the dead writer's heartbeat, and prevent lazy rollback of already-checkpointed instants before they are committed.
- Issue 2 (High): stop the writer-side heartbeat timers after hand-off and clean up heartbeat files, so that a long-running job does not accumulate threads and storage writes.
- Recommended fixes - non-blocking
- Issue 3 (fail on write errors), Issue 4 (persist
HoodieWriteStatinstead ofWriteStatus), Issue 5 (failure/restore tests), Issues 6-7 (signal and docs).
- Issue 3 (fail on write errors), Issue 4 (persist
Overall assessment: the shape of the solution is right and the previous review items are all resolved nicely, and the default path is untouched. The remaining problem is concentrated in one place: the LAZY-policy heartbeat that is used to keep the pending instant alive is owned by the writer's client while the commit is performed by another client, which makes the recovery path time-dependent and leaks resources over time. I believe both are fixable without changing the overall architecture. Better alternative: keep the same two-phase structure but give the committer (not the writers) ownership of keeping a handed-off instant alive and of cleaning its heartbeat. Happy to look at it again once these are addressed, thank you for the patience and the careful work so far.
|
CI is green again on the head that contains the review fixes ( Run: https://github.com/corgy-w/seatunnel/actions/runs/38163500699 —
The new exactly-once e2e case passes on both engines again after the review fixes: Local verification of the same head (JDK 11): |
…the writer heartbeat The exactly-once mode kept a pending instant alive with the Hudi LAZY failed writes cleaning policy, whose per instant writer heartbeat is owned by the writer while the commit is performed by the aggregated committer: * the commit of a checkpointed instant failed with "Heartbeat ... has expired" once the writer had been gone longer than the heartbeat tolerance, so a slow restart lost the data of a completed checkpoint * a cleanup of the table could roll the pending instant back before it was committed * every checkpoint leaked one heartbeat timer thread and one heartbeat file, because the client that commits the instant is not the client that started the heartbeat Switch the exactly-once semantics to the NEVER policy: no heartbeat is started, nothing rolls a pending instant back, and the commit no longer depends on one. The connector now cleans up failed writes itself: the writer rolls back the instant of a checkpoint that never completed when it closes, and the committer rolls it back on abort. Rejected records are no longer ignored either, prepareCommit fails with the rejected key and the cause instead of dropping records from a checkpoint that is never replayed. Docs updated for the new policy and its trade-offs.
|
@DanielLeens thank you — Issues 1 and 2 were real, and the root cause was the choice of the Issue 1 + 2 (High): the heartbeat no longer existsExactly-once now uses
The trade-off is explicit and documented: Hudi does not clean up failed writes of an exactly-once table by itself, so the connector does it — the record writer rolls back the instant of a checkpoint that never completed in Regression tests, both of which fail under the old
Issue 3 (Medium): rejected records fail the checkpoint
Issue 4 (Medium):
|
|
CI is green on the head that contains the heartbeat fixes ( Run: https://github.com/corgy-w/seatunnel/actions/runs/38209483378 —
The exactly-once e2e still passes against the real containers with the Local (JDK 11): |
DanielLeens
left a comment
There was a problem hiding this comment.
Thank you @corgy-w for the fast and careful turnaround on 54416149. Both of my High findings from the last round (the heartbeat-dependent commit/restore and the heartbeat thread/file leak) are genuinely fixed by moving to the NEVER failed-writes policy, and the rejected-record check is exactly what I asked for. I re-read the whole PR at the new head and traced the exactly-once path end to end again. There is one remaining High item that is a direct consequence of the NEVER choice, plus a few smaller ones. All of them are listed here at once.
What Problem Does This PR Solve?
- Pain point: the Hudi sink commits every flushed batch through the Hudi client auto-commit, so records become visible before their checkpoint completes, and a replay after a failure can publish them twice.
- Fix approach: opt-in
semantics = EXACTLY_ONCE. Writers disable auto-commit and write all batches of one checkpoint interval into one uncommitted instant.prepareCommit(checkpointId)hands aHudiCommitInfoto the newHudiSinkAggregatedCommitter, which commits the instant after the checkpoint completes (idempotent via the active timeline). The cleaning policy isNEVERso Hudi neither rolls the pending instant back nor starts per-instant heartbeats. - One-sentence summary: a checkpoint-gated two-phase commit for the Hudi sink with the default behavior unchanged; the happy path and the restore path are now sound, but the cleanup of instants left by failed attempts moved from Hudi to the connector and is not complete on Zeta.
1. Code Change Review
1.1 Core Logic Analysis
Delta since my last review (393edcfc to 54416149): LAZY replaced by NEVER in HudiUtil (withFailedWritesCleaningPolicy), HudiRecordWriter#checkWriteStatuses (new HUDI-07), HudiRecordWriter#rollbackPendingInstant called from close(), updated Javadoc/error text, docs en/zh, and two new unit tests.
Status of my previous blockers, verified against the new head:
- Previous Issue 1 (commit/restore depends on writer heartbeat): resolved. With
NEVER,BaseHoodieWriteClient.startCommitno longer starts a heartbeat andHeartbeatUtils.abortIfHeartbeatExpiredis a no-op for non-lazy policies, sorestoreCommitatHudiSinkAggregatedCommitter.java(commitInstant) no longer depends on how long the writer has been gone.HudiTwoPhaseCommitTest#shouldCommitARestoredInstantWhenTheWriterIsGoneAndTheHeartbeatIsStaleexercises this. - Previous Issue 2 (one heartbeat thread and file per checkpoint): resolved. No heartbeat is started at all (
shouldNotStartAHeartbeatForAnInstantWaitingForItsCheckpoint). - Previous Issue 3 (write errors committed silently): resolved.
checkWriteStatuses()runs before the commit info is created inprepareCommit(HudiRecordWriter.java~line 297) and fails the checkpoint withHUDI-07. Because it throws beforependingInstantTime = null, the close path then rolls the instant back, which is correct. - Previous Issue 4 (
WriteStatusin checkpoint state): partially addressed, see Issue 3 below. Your reasoning aboutHoodieJavaWriteClient#commitderiving stats from the statuses is fair, and I am fine with this as a follow-up. - Previous Issue 5 (tests): (a) and (b) added; (c) deferred, see Issue 4 below.
- Previous Issues 6 and 7 (docs/signal): mostly addressed, one stale sentence remains (Issue 5 below).
Runtime path (exactly-once, Zeta) with the failure points marked:
Writer subtask:
write()/timer flush -> flush() -> instantTimeToWrite(): startCommit() once per interval
-> insert/upsert(records, pendingInstantTime) [instant INFLIGHT, no heartbeat under NEVER]
barrier N -> prepareCommit(N): checkWriteStatuses(); HudiCommitInfo(N, instant, statuses)
pendingInstantTime = null <-- writer forgets the instant here
| (Java-serialized into committer checkpoint state)
v
Committer:
checkpoint N complete -> commit() -> commitInstant() (skip if already completed)
restore after failure -> restoreCommit() -> same path
Failure paths:
(a) task dies hard (JVM kill, node loss): close() never runs -> instant stays INFLIGHT <-- Issue 1
(b) barrier N handed the instant over, checkpoint N never completes, pipeline restarts:
writer already nulled pendingInstantTime, committer state of N is discarded,
Zeta never calls abort() -> instant stays INFLIGHT <-- Issue 1
(c) task closes with an un-handed-over instant -> close() rolls it back (new, OK)
1.2 Compatibility Impact
Fully compatible. The default AT_LEAST_ONCE path is untouched (no committer, prepareCommit returns empty, auto-commit and EAGER cleaning preserved), config keys are unchanged, and the new state types did not exist before. No entry is needed in incompatible-changes.md. The WriteStatus-in-state format is a future-compatibility concern for the new state only (Issue 3).
1.3 Performance / Side-Effect Analysis
- Default path: no new overhead.
- Exactly-once path: the heartbeat thread/file growth is gone. Writer heap and committer state still grow with the number of write statuses per checkpoint interval (Issue 3). The committer reloads the active timeline once per
commit()/abort()call, which is fine. - Storage: with
NEVER, files of instants that are never rolled back accumulate (Issue 1).
1.4 Error Handling and Logging
Issue 1 (High, new consequence of the LAZY to NEVER switch): instants left by a failed attempt are never rolled back on Zeta, and the documented manual rollback is not a workable operating model
- Location:
HudiUtil.java(NEVERpolicy),HudiRecordWriter.javaprepareCommit(pendingInstantTime = null) andclose()(rollbackPendingInstant),HudiSinkAggregatedCommitter.javaabort(), docs "Exactly-once semantics". - Problem: under
LAZYan orphaned instant was reclaimed by Hudi once its heartbeat expired. UnderNEVERnobody reclaims it unless the connector does. The connector only cleans two situations: a writer that closes gracefully with an un-handed-over instant, andabort(), which per your own Javadoc is only called by Spark. Two common failure shapes are not covered on Zeta/Flink: (a) a task that dies without runningclose()(JVM kill, OOM, lost node, which is the typical reason a job restarts in production), and (b) a checkpoint whose barrier already passedprepareCommit(so the writer forgot the instant) but which never completed, for example because another subtask failed or the checkpoint timed out. In (b) the committer state of that checkpoint is discarded on restore, so nothing references the instant anymore. The source replays the records into a new instant, so there is no duplicate, but the old instant stays INFLIGHT on the timeline together with its data files. - Risk: every restart after (a) or (b) leaves one pending instant per writer subtask and its files behind, permanently. On a job that writes at the scale this feature targets and restarts a few times a week, that is unbounded storage growth plus a growing set of pending instants that I would expect to hold back timeline archival/table services on the table (that last point is my inference from how Hudi treats the earliest pending instant, please verify against 0.15.0). The remedy in the docs is "roll it back manually with
HoodieWriteClient#rollbackorhoodie-cli", which an operator would have to repeat after each incident, and they need to know which inflight instants are orphans and which belong to a live writer. - Best improvement:
- Option A (preferred, keeps
NEVER): let the committer own the cleanup of orphans it can prove are orphans. Oninit()/restoreCommit()(the pipeline has just restarted from a checkpoint), compute the inflight instants on the active timeline that are older than the newest restored instant and are not part of the restored commit infos, and roll those back. Add a guard so it never touches an instant younger than the restored checkpoint, so a concurrent new writer is not affected. Add a unit test that creates an inflight instant, restarts with a fresh writer/committer pair and asserts the timeline no longer holds it. - Option B: return to
LAZYfor cleanup but fix the two heartbeat problems on the committer side (committer-owned heartbeat refresh until commit, and stop the writer-side timers after hand-off). This restores self-healing, at the cost of more moving parts. - At minimum, if you keep the current design, the docs must state clearly that orphaned instants accumulate after hard failures and give a copy-pasteable procedure to list and roll back inflight instants, and I would like a follow-up issue linked here.
- Option A (preferred, keeps
- Raised by another reviewer: No.
Issue 2 (Medium): the new close() rollback and the HUDI-07 failure path have no test
- Location:
HudiRecordWriter.javarollbackPendingInstant/close()andcheckWriteStatuses;HudiTwoPhaseCommitTest. - Problem: the new tests cover committer-side commit/restore/abort and the no-heartbeat behavior, but nothing asserts that closing a writer with a pending instant actually removes that instant from the timeline, and nothing drives a rejected record into
prepareCommitand assertsHUDI-07and no commit info. If someone deletesrollbackPendingInstant()or thecheckWriteStatuses()call, no test turns red. - Risk: these two behaviors are the whole replacement for the former Hudi-side safety net.
- Best improvement: add one test that writes a batch, closes the writer without
prepareCommit, and asserts the instant is gone from the timeline; and one that forces a write status with an error (for example a record whose payload fails conversion, or a spied status) and assertsHudiConnectorExceptionwithHUDI-07. - Raised by another reviewer: No.
Issue 3 (Medium, carryover from my previous Issue 4, acknowledged as follow-up): checkpoint state and writer heap still carry full WriteStatus objects
- Location:
HudiCommitInfo.java(List<WriteStatus>),HudiRecordWriter.java(pendingWriteStatuses),HudiSink.javaserializer. - Problem:
WriteStatusis Java-serialized into the committer state and may keep aHoodieRecordDelegateper written record when records are tracked (non-implicit index, record index in the metadata table). With rejected records now failing the checkpoint, the error map can no longer reach the state, which is a real improvement. - Risk: state size and writer heap scale with records per checkpoint interval, and the persisted format depends on a Hudi-internal class.
- Best improvement: I accept your plan to move to stats-only state (
commitStats) in a separate change with a metadata-table-enabled test. Please open the follow-up issue and link it in the PR description. Non-blocking. - Raised by another reviewer: No.
Issue 4 (Medium, acknowledged as follow-up): no fault-injection E2E
- Location:
HudiIT#testWriteHudiWithExactlyOnceSemantics,fake_to_hudi_exactly_once.conf. - Problem: the E2E is a short batch job with parallelism 1 and one engine run; it does not fail a task between checkpoint completion and commit, so it cannot prove "no loss, no duplicate" across a restart. The unit-level restore test only simulates the committer side.
- Best improvement: agreed that this can be a follow-up, but please track it with an issue because it is the only test that would catch Issue 1.
- Raised by another reviewer: No.
Issue 5 (Low): one stale doc sentence and one wording gap
- Location:
docs/en/connectors/sink/Hudi.mdanddocs/zh/connectors/sink/Hudi.md, last bullet of "Requirements and trade-offs". - Problem: the bullet still says a commit can fail "because the heartbeat of the writer expired before the commit". Under
NEVERthere is no heartbeat, so this is no longer a cause; the error text inHudiSinkAggregatedCommitter#commitInstantwas updated, the doc was not. Also, "How it works" item 4 says the connector rolls back the instant of a checkpoint that never completed, which is only true for the graceful-close case (see Issue 1). - Best improvement: update both language versions together with the Issue 1 resolution.
- Raised by another reviewer: No.
2. Code Quality Assessment
2.1 Coding Standards
Good. New classes and non-trivial methods have Javadoc that explains intent and constraints, and the long HudiUtil comment explains the policy choice clearly (it has an odd line wrap around "one / heartbeat file", cosmetic only).
2.2 Test Coverage and Test Stability
The new tests use a real local Hudi table, have no Thread.sleep and no fixed ports, and the two new regression tests do fail under the old LAZY design. Gaps are in Issues 2 and 4. Stability rating: Stable (the remaining concern is coverage, not flakiness).
2.3 Documentation Updates
docs/en and docs/zh are both updated and consistent, with the stale bullet noted in Issue 5.
3. Architectural Soundness
3.1 Elegance of the Solution
Long-term solution in structure (standard SinkAggregatedCommitter, one instant per checkpoint, idempotent commit). Using NEVER is the simplest way to remove the heartbeat coupling, but it moves orphan cleanup into the connector, which is why Issue 1 matters.
3.2 Maintainability
Small focused classes. After Issue 1 the orphan-cleanup logic should live in one place (the committer) rather than being split between writer close(), committer abort() and a manual runbook.
3.3 Extensibility
The HudiSemantics seam is clean and leaves room for stats-only state later.
3.4 Historical-Version Compatibility
No impact on existing jobs or checkpoints. Upgrade needs no action; users opt in with semantics = EXACTLY_ONCE.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | Orphaned INFLIGHT instants are never rolled back after hard failures or never-completed checkpoints on Zeta/Flink; manual rollback only | HudiUtil.java (NEVER), HudiRecordWriter.java prepareCommit/close, HudiSinkAggregatedCommitter.java abort |
High |
| 2 | No test for writer close() rollback and HUDI-07 rejected-record failure |
HudiRecordWriter.java, HudiTwoPhaseCommitTest.java |
Medium |
| 3 | WriteStatus in checkpoint state (follow-up agreed) |
HudiCommitInfo.java, HudiRecordWriter.java |
Medium |
| 4 | No fault-injection E2E (follow-up agreed) | HudiIT.java, fake_to_hudi_exactly_once.conf |
Medium |
| 5 | Stale heartbeat sentence and overstated rollback claim in docs | `docs/en | zh/connectors/sink/Hudi.md` |
5. Merge Recommendation
CI state: the contributor-fork run for head 54416149 (https://github.com/corgy-w/seatunnel/actions/runs/38209483378) completed successfully, and the apache-side Build check is green, including unit-test (11/17 on ubuntu and windows) and updated-modules-integration-test-part-1 which runs connector-hudi-e2e. Upstream sync: the branch is diverged from dev by 4 commits each way, GitHub reports it as mergeable (no conflicts), so no sync is required for this review. The remaining gate besides the items below is the required maintainer review.
There is no existing approval or change request from other reviewers on this PR besides mine, so there is no other maintainer intent to reconcile.
Conclusion: Ready to merge after fixes
- Blockers - must be fixed
- Issue 1 (High): make the cleanup of orphaned instants part of the connector (Option A above, or Option B), or at least document the limitation precisely and track it, so a job that restarts regularly does not leak storage and pending instants.
- Recommended fixes - non-blocking
- Issue 2 (tests for the new rollback and
HUDI-07paths), Issues 3 and 4 (agreed follow-ups, please link issues), Issue 5 (docs).
- Issue 2 (tests for the new rollback and
Overall assessment: the design is now much closer to production-ready: the restore path is time-independent, the thread/file leak is gone, and rejected records no longer slip into a completed checkpoint. The last structural gap is who reclaims the instants of failed attempts now that Hudi no longer does. A better alternative to the manual runbook is the committer-side reclaim in Issue 1, Option A, which keeps your NEVER design and the current architecture. Thank you again for the patience and the quality of the work so far, I am happy to re-review as soon as you push an update.
…exactly-once # Conflicts: # docs/zh/connectors/sink/Hudi.md
With the NEVER failed-writes cleaning policy Hudi no longer rolls a pending instant back by itself, and the connector only cleaned the instant a writer still owned on close and the instants of an aborted checkpoint on the engines that call abort. A task that is killed hard, or a checkpoint whose instants were handed over but which never completed, therefore left one inflight instant per writer subtask on the timeline forever. On restore, the committer now rolls back every commit/delta-commit instant that the restored checkpoint state does not reference before committing the restored instants. At that point the pipeline has not started its writers yet, so those instants can only belong to attempts that will never be committed. Hudi table service actions (for example a pending compaction) are left untouched, and without restored state nothing is reclaimed because there is no safe reference point. Also add the tests requested in review for the writer close rollback and for the HUDI-07 rejected-record failure path, and update the EN/ZH docs for the reclaim behavior and the removal of the heartbeat-based failure cause.
|
@DanielLeens thanks again for the detailed review. I addressed the remaining items in Issue 1 (High): orphaned instants are now reclaimed by the committer on restore.
This also covers failure shape (b) from your review: the instant of a checkpoint that handed its records over but never completed is younger than the newest restored instant, so an "older than the newest restored instant" guard would have left exactly that case behind. The safety argument is the writer-start ordering instead: the committer restores before the task group starts, and writers only create an instant on the first write, so no writer of this job can own an instant at that point. Issue 2 (Medium): tests added.
Issue 5 (Low): docs. Both languages now describe the three cleanup points (writer close, Issues 3 and 4 are tracked in #13224 (stats-only commit state + fault-injection E2E) and linked from the PR description. Local verification (JDK 11): |
DanielLeens
left a comment
There was a problem hiding this comment.
Thank you @corgy-w for the detailed reply and for 3656e78b3a. The restore-time reclaim is the right direction, the three new tests are exactly the ones I asked for, and the docs now describe the cleanup model honestly. I re-read the whole PR at 99f85eaa16 and traced the reclaim through the Zeta restore sequence, the multi-table wrapper and both Flink translations. Your ordering argument holds on Zeta, and the reclaim can never roll back a completed instant. I did find one case where it can roll back an instant that another restored committer still needs, plus a few smaller gaps. Some of this I should have raised last round: my Option A did not say that Flink never calls restoreCommit, and it did not consider several committers sharing one table. Sorry about that. Everything is listed below in one pass.
What Problem Does This PR Solve?
- Pain point: the Hudi sink auto-commits every flushed batch, so records are visible before their checkpoint completes and a replay after failure publishes them twice.
- Fix approach: opt-in
semantics = EXACTLY_ONCE. Writers write one uncommitted instant per checkpoint interval,prepareCommithands it toHudiSinkAggregatedCommitter, the instant is committed after checkpoint completion (idempotent against the active timeline), the cleaning policy isNEVER, and orphaned instants are reclaimed by writerclose(),abort()and, new in this round,restoreCommit(). - One-sentence summary: a checkpoint-gated two-phase commit for Hudi with the default path unchanged; the remaining risk is that the new restore reclaim treats the Hudi table timeline as owned by a single committer, which the multi-table mapping does not guarantee.
1. Code Change Review
1.1 Core Logic Analysis
Delta since my last review (54416149 to 99f85eaa16, ignoring the dev merge): HudiSinkAggregatedCommitter#reclaimOrphanedInstants called first in restoreCommit, an updated HudiUtil comment, three new tests in HudiTwoPhaseCommitTest, and EN/ZH doc updates.
Before:
public List<HudiAggregatedCommitInfo> restoreCommit(List<HudiAggregatedCommitInfo> infos) {
return commit(infos);
}After (HudiSinkAggregatedCommitter.java:179-187, 253-303):
reclaimOrphanedInstants(flatten(infos)); // roll back every pending commit/deltacommit
return commit(infos); // instant not referenced by the restored infos
// ... skipped entirely when the flattened restored infos are empty (warn only)Key findings:
- Cannot roll back committed data. Candidates come from
filterInflightsAndRequested()(line 259) and are limited tocommit/deltacommit, so completed instants and table services such as a pending compaction are never touched. - Safe against this job's own new writers on Zeta.
SinkAggregatedCommitterTask#restoreStaterunsrestoreCommitbeforerestoreComplete(SinkAggregatedCommitterTask.java:260-281).CheckpointCoordinator#allTaskReadysendsNotifyTaskStartonly after every task reportsREADY_START(CheckpointCoordinator.java:458-472). Writers only callstartCommit()on their first write. So no writer of the restarted pipeline can own an instant yet. I agree with your reason for dropping the "older than the newest restored instant" guard. - Not safe when several committers of one job share one Hudi table (Issue 1). The reclaim assumes that the restored infos of one committer describe every legitimate pending instant on the table. The multi-table path does not guarantee that.
- Wider skip than documented (Issue 2): an idle last checkpoint also produces an empty restored list.
- Zeta-only (Issue 3): neither Flink translation calls
restoreCommit.
Runtime path (Zeta, restore):
JobMaster restore -> CheckpointCoordinator.restoreTaskState(task) [latest completed checkpoint N]
-> NotifyTaskRestoreOperation -> SinkAggregatedCommitterTask.restoreState
-> MultiTableSinkAggregatedCommitter.restoreCommit [one sub-committer per UPSTREAM table]
for each sub-committer (HashMap order):
HudiSinkAggregatedCommitter.restoreCommit(infos of THIS upstream table only)
-> reclaimOrphanedInstants: rollback(pending commit/deltacommit not in these infos)
-> commit(): skip completed, throw HUDI COMMIT_INSTANT_FAILED if instant gone
-> restoreComplete
-> all tasks READY_START -> NotifyTaskStart -> writers start -> first write -> startCommit()
1.2 Compatibility Impact
Fully compatible. AT_LEAST_ONCE remains the default and its code path is unchanged. Option names are unchanged, and the new state classes have no earlier persisted form. The reclaim only runs when the committer exists, which means only with EXACTLY_ONCE.
1.3 Performance / Side-Effect Analysis
- Restore reloads the active timeline once more and rolls back orphans one at a time. That cost is bounded by the number of failed-attempt instants and only paid on restore.
- Side effect to be aware of: the rollback deletes data files. The reclaim must never pick an instant that someone still needs, and Issue 1 shows a case where it does.
- A rollback that fails is logged and skipped. Records of a never-completed checkpoint are replayed, so this is fine for true orphans. A half-finished rollback leaves a pending rollback instant, and Hudi resumes it on the next
rollback(instantTime)throughgetPendingRollbackInfo. That makes the reclaim re-runnable.
1.4 Error Handling and Logging
Issue 1: the restore reclaim of one sub-committer can roll back an instant another sub-committer of the same job still has to commit
- Location:
HudiSinkAggregatedCommitter.java:253-303(reclaimOrphanedInstants);HudiSinkFactory.java:139-142(a singletable_listentry is returned for every upstream table);MultiTableSink.java:325-333(one aggregated committer per upstreamTablePath);MultiTableSinkAggregatedCommitter.java:86-105(each sub-committer restores only its own infos). - Problem: with a multi-table source (for example sharded CDC tables) and one Hudi table configured, every upstream table gets its own
HudiSinkand its ownHudiSinkAggregatedCommitter, and all of them write to the same base path. On restore, each committer sees only its own upstream table's infos. Suppose the job failed after checkpoint N completed but before every sub-committer committed:commitPerTablecommits sub-committer A and the commit of sub-committer B throws, or the node dies in between. B's instant of checkpoint N is still INFLIGHT. On restore, whichever of A or B runs first rolls the other's instant back as an "orphan". B'scommitInstantthen throwsCOMMIT_INSTANT_FAILED(line 316) on this attempt and on every later one, because the restored state still references the deleted instant. - Potential risk: records of a completed checkpoint are deleted, and the source will not replay them. The job also cannot restore from that checkpoint again. This is the lost-commit recovery path the feature exists for. The docs only forbid "two exactly-once jobs against the same table", and they still say "make sure the writers work on disjoint keys and partitions" (
Hudi.md:283). A user with an N:1 mapping inside one job has no warning. - Best improvement: the reclaim must only run when this committer is provably the only one in the job that owns the table's pending commit instants.
- Option A (smallest): reject
EXACTLY_ONCEwhen more than one sub-sink of the job resolves to the same Hudi base path. The factory has no global view, but every sub-committer of aMultiTableSinkAggregatedCommitteris created andinit()-ed in the same task. A small registry keyed by base path (filled ininit(), cleared inclose()) can fail fast with a clear message. Add a test with two committers on one table. - Option B: keep N:1 supported, and when a sibling committer for the same base path exists, skip the reclaim (warn) instead of rolling back.
- Either way, align the docs: under
EXACTLY_ONCEthe table must have exactly one writer (one job, one upstream table). Drop the "disjoint keys and partitions" escape hatch for this mode, because any other writer's pending instant will be rolled back on restore.
- Option A (smallest): reject
- Severity: High
- Raised by another reviewer: No.
Issue 2: the reclaim is also skipped after restoring from an idle checkpoint, and the combine comment says the opposite
- Location:
HudiRecordWriter.java:296-299(prepareCommitreturnsOptional.empty()when there is no pending instant);HudiSinkAggregatedCommitter.java:132(comment "a writer that has no record to commit sends an empty commit info") and270-280; docsHudi.md:255and the ZH equivalent. - Problem: the skip keys off the flattened commit infos. If no writer received data during the interval of the restored checkpoint N, which is common for CDC streams with quiet periods, then no commit info is sent, Zeta stores an empty list, and the reclaim only warns. The orphans of the failed attempt (interval N+1, or a hard-killed writer) stay on the timeline. The docs say only "a job that never completed a checkpoint" and "started from scratch" are left to the operator. The safety argument for the reclaim is the Zeta task ordering, and that argument does not depend on whether the restored list is empty.
- Potential risk: the storage and pending-instant leak that Issue 1 of my last review described remains for idle streaming jobs. Only a warning is logged.
- Best improvement: under
EXACTLY_ONCE, let the writer return an emptyHudiCommitInfo(checkpointId, null, emptyList)instead ofOptional.empty(), which is what thecombinecomment already describes. Then gate the reclaim on "restored from a checkpoint" (!aggregatedCommitInfos.isEmpty()) rather than on the flattened list. Fresh starts keep the current conservative behavior. If you prefer not to change that, at least document the idle-checkpoint case and fix the stale comment. - Severity: Medium
- Raised by another reviewer: No.
Issue 3: the restore reclaim and the lost-commit recovery are Zeta-only, but the docs present them as generic
- Location:
FlinkGlobalCommitter.java:66-69(filterRecoveredCommittablesreturns an empty list and never callsrestoreCommit);FlinkSimpleAggregatedCommitter.java:64-139(onlycommit); docsHudi.md:224-228,255,279and the ZH equivalents. - Problem: on Flink,
restoreCommit, and with it the new reclaim, never runs, so orphans of failed attempts still accumulate there. With the Flink 1.x common translation, recovered global committables are also dropped byfilterRecoveredCommittables. Based on the translation source, I therefore expect "How it works" item 3 (a lost commit is re-applied on restore) not to hold there. That is a pre-existing translation limitation and not caused by this PR. The Flink 2.0 adapter re-delivers recoveredCommitRequests tocommit(), which your idempotent commit handles. - Potential risk: Flink users rely on recovery and cleanup guarantees that the engine adapter does not provide.
- Best improvement: in both languages, scope the restore reclaim to Zeta and add a short engine note for the lost-commit recovery. No code change is needed in this PR.
- Severity: Medium
- Raised by another reviewer: No.
2. Code Quality Assessment
2.1 Coding Standards
Javadoc on reclaimOrphanedInstants, restoreCommit and the class header explains the why and the boundaries well. Two small points in HudiTwoPhaseCommitTest.java:392-394. The rejected-record test injects into the private pendingWriteStatuses field through reflection, which breaks silently if the field is renamed. It also uses the fully qualified java.lang.reflect.Field inside the method body. A package-private @VisibleForTesting hook, or an import, would be cleaner. (Low)
2.2 Test Coverage and Test Stability
The three new tests have real failure power. shouldReclaimTheInstantOfACheckpointThatNeverCompleted turns red if the reclaim call is removed. shouldRollbackTheInstantWhenTheWriterClosesWithoutCheckpoint turns red without rollbackPendingInstant. shouldFailTheCheckpointWhenHudiRejectsARecord turns red without checkWriteStatuses.
Gap (Issue 4, Medium): the two guards that make the reclaim safe are untested. If filterInflightsAndRequested() (line 259) or the commit/deltacommit filter were deleted, no test would fail, because the reclaim test has no completed instant that the restored state leaves unreferenced. Best improvement: in the same test, commit an earlier checkpoint first, then assert that it is still completed and that its records are still counted after the restore. Once Issue 1 is fixed, add a two-committer case.
Stability rating: Stable. The tests use a real local Hudi table under @TempDir (HudiTwoPhaseCommitTest.java:86) and have no sleeps, fixed ports or timing assertions.
2.3 Documentation Updates
EN and ZH are updated together and match each other. The items to change are in Issues 1-3: single-writer wording, the idle-checkpoint case and engine scope. The stale heartbeat bullet from last round is fixed.
3. Architectural Soundness
3.1 Elegance of the Solution
Putting orphan cleanup in the committer's restore step is a clean answer to the NEVER policy. The one structural assumption that needs to be made explicit is "one committer owns the table's pending commit instants" (Issue 1).
3.2 Maintainability
Cleanup now lives in three well-documented places: writer close, abort and restore. That is reasonable.
3.3 Extensibility
The stats-only state and the fault-injection E2E are tracked in #13224, as agreed. Thank you for linking them.
3.4 Historical-Version Compatibility
No impact on existing jobs or checkpoints, because the feature is opt-in and its state is new.
4. Issue Summary
| No. | Issue | Location | Severity |
|---|---|---|---|
| 1 | Restore reclaim of one sub-committer rolls back a still-needed instant of a sibling sub-committer when several upstream tables write to one Hudi table, losing a completed checkpoint and blocking restore | HudiSinkAggregatedCommitter.java:253-303, HudiSinkFactory.java:139-142, MultiTableSink.java:325-333 |
High |
| 2 | Reclaim skipped after restoring from an idle checkpoint; combine comment contradicts prepareCommit |
HudiRecordWriter.java:296-299, HudiSinkAggregatedCommitter.java:132,270-280, Hudi.md:255 |
Medium |
| 3 | Restore reclaim and lost-commit recovery are Zeta-only, docs present them as generic | FlinkGlobalCommitter.java:66-69, Hudi.md:224-228,255,279 |
Medium |
| 4 | Reclaim safety guards (completed and table-service instants untouched) have no test | HudiTwoPhaseCommitTest.java:300-348 |
Medium |
| 5 | Reflection into a private field and an inline fully qualified type in the test | HudiTwoPhaseCommitTest.java:392-394 |
Low |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
- Blockers - must be fixed
- Issue 1: either reject or skip the reclaim when more than one sub-committer of the job targets the same Hudi table, and tighten the single-writer wording in both languages.
- Recommended fixes - non-blocking
- Issue 2: send empty commit infos and gate on the restored list (or document the idle case and fix the comment).
- Issue 3: engine-scope note in the docs.
- Issue 4: keep a completed instant in the reclaim test.
- Issue 5: test cleanup.
Overall assessment: the happy path, the idempotent restore and single-committer orphan cleanup on Zeta are now sound. I traced the ordering argument for the reclaim and agree with it. The last real gap is that the reclaim decides alone what counts as an orphan on a table that the multi-table mapping can share among several committers. Option A in Issue 1 is a small, local fix that keeps your design. There is no other maintainer approval or change request on this PR to reconcile.
CI / branch state: the contributor-fork Build run for this head (run 42974133073) has passed License header, Code style, changes and Dead links. The remaining jobs are still queued, so the apache-side Build is in progress. The branch is 7 commits ahead and 0 behind dev, and GitHub reports it as mergeable (no conflicts).
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for getting the current-head build through. The CI fact cited previously has changed: Build 42974133073 and the Apache Build check now pass on unchanged head 99f85eaa16276d7c3d431a7d131a94f166c900ec. My earlier statement that this run was queued is obsolete.
This does not clear Issue 1 from my source review: HudiSinkAggregatedCommitter.reclaimOrphanedInstants can treat another sub-committer's required pending instant as an orphan when multiple upstream tables map to the same Hudi base path. A passing build does not resolve that completed-checkpoint data-loss/recovery blocker. The existing requested fix and its shared-table restore regression remain required; no new issue is being added against this head.
5. Merge Recommendation
Conclusion: Ready to merge after fixes
- Blockers — must be fixed: Existing Issue 1, including the regression and matching supported-mapping documentation. Independent maintainer review also remains necessary.
- Recommended fixes — non-blocking: Existing Issues 2 and 3 retain their prior disposition.
No local test or job was run. This is a correction of the CI status only, not a new source review or an approval. Daniel's technical blocker remains open regardless of the historical review state displayed by GitHub.
|
Thanks for pushing the restore-time reclaim in The one thing still blocking from my side is Issue 1 from the source review (5857369474): What I need before approving (no new issues against this head):
Issues 2 and 3 keep their earlier non-blocking disposition; feel free to fold them in or follow up separately. Once the fix and regression test are up I will do another full pass on the new head. |
|
Thanks, @SEZ9. I agree that the restore-time ownership question remains separate from the passing Build. My existing Issue 1 still applies on |
Purpose of this pull request
The Hudi sink commits every flushed batch with the Hudi client auto-commit, so the records are published before the checkpoint that contains them completes, and a job that fails and replays the records of a not completed checkpoint commits them a second time.
This pull request adds an opt-in two-phase commit write path to the Hudi sink:
semanticssink option with the valuesAT_LEAST_ONCE(default, unchanged behaviour) andEXACTLY_ONCE.EXACTLY_ONCEthe Hudi client auto-commit is disabled. All the batches written between two checkpoints are written into the same Hudi instant, and the instant is committed by an aggregated committer only after the checkpoint completes, so the readers never see the records of a checkpoint that was not completed.restoreCommitapplies it again after the restore. An instant that is already completed on the active timeline is skipped, so the records are never published twice.LAZYfor the exactly-once semantics: the defaultEAGERpolicy rolls back every inflight instant before a new instant is created, which would roll back the instants that are still waiting for the commit of their checkpoint.Both Zeta and the Spark/Flink translations call
SinkWriter#prepareCommit(long checkpointId)and commit throughSinkAggregatedCommitter, which is what this implementation relies on.Does this PR introduce any user-facing change?
Yes, it adds a user-facing option and documents it in
docs/en/connectors/sink/Hudi.mdanddocs/zh/connectors/sink/Hudi.md:semantics = AT_LEAST_ONCEis the default and keeps the previous behaviour, so existing jobs are not affected.semantics = EXACTLY_ONCErequires the checkpoint to be enabled, and the records become visible only after a checkpoint completes, so the visibility latency is at least one checkpoint interval. With this semantics the timer flush and thebatch_sizeflush only stage the records into the instant of the current checkpoint instead of publishing them. Parallel writers still follow the Hudi single writer concurrency control and should work on disjoint keys and partitions.No incompatible change,
docs/en/introduction/concepts/incompatible-changes.mdis not affected.How was this patch tested?
HudiTwoPhaseCommitTest(new) runs the real writer and the real aggregated committer against a real Hudi table on the local file system and checks thatAT_LEAST_ONCEsemantics still commits every flushed batch with the client auto-commit.HudiSinkAggregatedCommitterTest(new) covers the commit info state serialization (it is part of the checkpoint state) and the writers that have nothing to commit.HudiSinkConfigTest(new) covers the new option and the failure on an unknown value../mvnw -pl seatunnel-connectors-v2/connector-hudi testpasses all 24 tests of the module (JDK 11)../mvnw -pl seatunnel-connectors-v2/connector-hudi,seatunnel-e2e/seatunnel-connector-v2-e2e/connector-hudi-e2e spotless:applyis applied and the e2e module compiles.HudiIT#testWriteHudiWithExactlyOnceSemanticswithhudi/fake_to_hudi_exactly_once.confwrites 5 records with the exactly-once semantics and asserts that they are visible after the job finished. It runs in the CI container, the local run needs the e2e container images which were not available here.Check list
incompatible-changes.mdto describe the incompatibility caused by this PR.plugin-mapping.properties,seatunnel-dist/pom.xml,label-scope-conf.ymlandconfig/plugin_configare unchanged; an e2e test case is added inseatunnel-e2e.Review follow-up (restore-time reclaim of orphaned instants)
close()norabort()runs: a task that is killed hard, and a checkpoint that handed its instants over but never completed. Hudi table-service actions (for example a pending compaction) are left untouched, and nothing is reclaimed without restored state because there is no safe reference point.HudiTwoPhaseCommitTest#shouldReclaimTheInstantOfACheckpointThatNeverCompleted,#shouldRollbackTheInstantWhenTheWriterClosesWithoutCheckpointand#shouldFailTheCheckpointWhenHudiRejectsARecord(the last one assertsHUDI-07and that the rejected checkpoint leaves no instant behind).WriteStatus, and a fault-injection E2E across a restart../mvnw -pl seatunnel-connectors-v2/connector-hudi -DskipIT=true testpasses all 30 tests of the module;spotless:applyis clean.