Skip to content

[Fix][Translation] Preserve Flink recovery commit provenance - #13110

Open
goutamadwant wants to merge 5 commits into
apache:devfrom
goutamadwant:fix/flink-recovery-commits-dev
Open

goutamadwant wants to merge 5 commits into
apache:devfrom
goutamadwant:fix/flink-recovery-commits-dev

Conversation

@goutamadwant

@goutamadwant goutamadwant commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

Purpose of this pull request

Fixes #13106. This is a separate Flink commit-recovery prerequisite for #12983.

Route restored committables through restoreCommit and preserve that provenance across aggregation, retries and partial progress. Fresh commits retain strict failure handling; pending work is no longer acknowledged as successful. Preserve existing operator identities and legacy serializer compatibility.

#12807 already handles API-level multi-table forwarding. The broader schema protocol remains in #11958/#11960; collector restoration remains in #12983.

Integration gate

Merge after #13109 and #12881. The JDBC XA ownership-cleanup fix in #13109 is required before rolling out mixed multi-table JDBC recovery. Current cleanup can roll back a peer table's prepared transaction; recovery may then mistake an absent transaction for one already resolved. This adapter change does not repair that ownership bug.

Iceberg recovery also requires the payload-based replay protection in #12881. Writer-local checkpoint counters can be reused across jobs or regrouped aggregates; counter-only deduplication can otherwise acknowledge files that were never committed. The generic adapter does not fix that connector behavior.

Mixed restored/live aggregates use restoreCommit as a whole and inherit the connector's recovery semantics. Only fresh-only aggregates retain strict ordinary commit handling. This PR alone does not establish multi-table JDBC XA exactly-once readiness; combined engine checkpoint/restore/crash validation remains pending.

Does this PR introduce any user-facing change?

Checkpoint/savepoint recovery reconciles restored transactions instead of treating them as fresh commits or dropping pending retries. No new configuration option.

How was this patch tested?

  • Historical baseline: ordinary-commit routing of legacy restored work was reproduced on dev 3244c9504c75 before the initial patch.
  • Current dev merge (f54bb5876bd2): 35 selected serializer, topology, recovery, commit and writer tests passed on each of Java 11 and Java 17, with no failures or skips.
  • The Java 11 scoped reactor packaged the Flink 1.13/1.15/1.20 starters and compiled the LocalFile E2E fixtures. This was packaging verification, not execution of the full LocalFile matrix.
  • Real Flink 1.13 and 1.15 binary-copy runs reproduced destination-directory creation failure with the original root-owned fixture setup. With only the destination fixture prepared for worker access, both runs completed and the output bytes matched the source.
  • Spotless and four repository Markdown checks passed.
  • The full hosted engine matrix and composed checkpoint/restore/crash validation with [Fix][Connector-V2] Isolate JDBC XA cleanup by table ownership #13109 and [Feature][Connector-V2][Iceberg] Support v3 CDC and replay-safe commits #12881 remain pending. Adapter tests and the binary-copy slice do not establish JDBC or Iceberg exactly-once readiness.

Run the focused checks with Java 11 and Java 17:

./mvnw -Pci -Dmaven.jar.forceCreation=true -pl seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-13,seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-15,seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-20 -am -Dtest=FlinkGlobalCommitterTest,RecoveryTopologyTest,RecoveryCommitSerializerTest,RestoredCommittableOperatorTest,CheckpointCommitWrapperSerializerTest,FlinkSimpleAggregatedCommitterTest,FlinkSinkWriterTest -Dsurefire.failIfNoSpecifiedTests=false verify

The earlier collector/JDBC/Flink prerequisite composition passed nine native cases across Flink 1.13/1.15/1.18/1.20 (restore fixture at the prerequisite commit). That is historical combined-tree evidence, not a native matrix for this standalone branch. Hosted CI is separate.

Check list

No new connector or binary package is added. Existing registration files still apply.

Route restored committables through restoreCommit across supported Flink
adapters and retain recovery provenance through retries and partial progress.
Preserve operator graph and serializer compatibility.

Add recovery routing, failure and topology regression tests.
Related to apache#12983.

(cherry picked from commit 40627c9)

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks a lot, @goutamadwant, for splitting this out as a standalone prerequisite and for the clear scope notes in the description. Fixing the Flink path that silently dropped restored global committables (and acknowledged pending retries as successful) is a real correctness improvement. I reviewed head 484f2190fdbd (one commit on top of dev 3244c9504c75), traced the Flink 1.13, 1.15-1.18 and 1.20 sink paths, and read the Flink 1.15.3 / 1.18.1 GlobalCommitterOperator, StandardSinkTopologies and SinkV1Adapter sources to check how the new decorators are actually invoked.

What Problem Does This PR Solve?

  • User pain point (#13106): after a Flink checkpoint/savepoint restore, restored committables go through the ordinary commit() path or are dropped entirely (FlinkGlobalCommitter.filterRecoveredCommittables returned an empty list), and retries returned by the aggregated committer were logged and treated as success. For two-phase-commit sinks that means lost or unreconciled transactions after recovery.
  • Fix approach: mark which committables came from restored state and route them through SinkAggregatedCommitter.restoreCommit, keep fresh commits on commit(), and stop acknowledging pending work.
    • Flink 1.13 / common: FlinkGlobalCommitter now reconciles restored global committables and returns pending retries.
    • Flink 1.15-1.18: RecoveryAwareSink wraps the existing SinkV1Adapter sink; a RecoveredCommitTracker notices committables deserialized from operator state, and RestoredCommittableOperator marks upstream replays whose checkpoint id is at or below the restored id.
    • Flink 1.20: commits carry their checkpoint id in a new versioned envelope (CheckpointCommitWrapperSerializer); FlinkSimpleAggregatedCommitter splits restored vs current requests and now fails instead of acknowledging leftovers.
  • One sentence: a sink restored from checkpoint N reconciles transactions from N or earlier via restoreCommit, and new transactions after N keep strict commit semantics.

1. Code Change Review

1.1 Core Logic Analysis

The normal path is hit: seatunnel-core/seatunnel-flink-starter/seatunnel-flink-starter-common/src/main/java/org/apache/seatunnel/core/starter/flink/execution/SinkExecuteProcessor.java:67-69 now wraps every Flink 1.15-1.18 sink with RecoveryAwareSink.wrap(...), and the 1.20 FlinkSink always uses the new committable serializer. The recovery-specific branches only trigger after a restore.

Key snippets:

// FlinkGlobalCommitter (common, used by 1.13 and 1.15-1.18)
public List<GlobalCommT> filterRecoveredCommittables(List globalCommittables) {
    if (tracker != null) tracker.finishRestore();            // mark wrappers read from state
    List<GlobalCommT> pending = aggregatedCommitter.restoreCommit(globalCommittables);
    ...
}
public GlobalCommT combine(List<CommitWrapper<CommT>> committables) throws IOException {
    boolean replay = !committables.isEmpty() && committables.get(0).isRecovered();
    if (committables.stream().anyMatch(w -> w.isRecovered() != replay)) {
        throw new IOException("Cannot combine restored and live committables");
    }
    ...
}

Runtime flow on Flink 1.15-1.18 (restore case):

restore from checkpoint N
 -> GlobalCommitterOperator.setup(): committer = GlobalCommitterAdapter (sink.createGlobalCommitter()
      -> RecoverableLegacySink.tracker() T), committableSerializer = RecoveryCommitSerializer(T)
 -> RestoredCommittableOperator.initializeState(): records restoredCheckpoint = N
 -> GlobalCommitterOperator.initializeState(): CommittableCollector state deserialized
      -> RecoveryCommitSerializer.deserialize -> T.deserialized(wrapper)
    -> FlinkGlobalCommitter.filterRecoveredCommittables(sinkV1State)
      -> T.finishRestore(): restored wrappers markRecovered()
      -> restoreCommit(sinkV1State) -> pending marked recovered by identity
    -> commit(N): sinkV1State -> FlinkGlobalCommitter.commit -> restoreCommit(pending)
                  collector up to N -> GlobalCommitterAdapter.commit -> combine(restored) -> commit -> restoreCommit
 -> processElement: upstream CommitterOperator replays (checkpointId <= N) markRecovered
 -> later checkpoints (> N): combine(live) -> commit(); pending -> retryLater
 -> endInput: CommittableCollector EOI manager (no checkpoint id) -> combine(...)

The tracker hand-off works only because the GlobalCommitterOperator's serializer supplier (() -> sink.getCommittableSerializer().get()) and its committer factory (GlobalCommitterAdapter::new) capture the same SinkV1Adapter instance, so after Java deserialization they share one RecoverableLegacySink and therefore one transient tracker. That is correct for the 1.15.3 and 1.18.1 sources I read, but it is an implicit contract (see Issue 2).

Operator identity: RecoveryDataStream.transform swaps the operator for a factory that wraps it, without changing the transformation name, parallelism or graph position, and RecoveryTopologyTest asserts the generated operator IDs are unchanged. Good. I also checked that StreamTaskStateInitializer.streamOperatorStateContext has the same 9-parameter signature from 1.15.3 through 1.19.1, so the lambda in RestoredCommittableOperator.initializeState links on every runtime that uses the 1.15 translation module.

1.2 Compatibility Impact

  • Flink 1.13 / 1.15-1.18 state: committable bytes and serializer version are unchanged (RecoveryCommitSerializer delegates getVersion/serialize), operator IDs are unchanged. Compatible both ways.
  • Flink 1.20 state: the committable serializer moves from version 0 (CommitWrapperSerializer) to version 1 (8-byte checkpoint id + legacy payload). Old v0 state is read correctly (CheckpointCommitWrapperSerializer.java:48-50). The reverse is not: the legacy CommitWrapperSerializer.deserialize ignores the version, so a savepoint taken after this change cannot be restored by an older SeaTunnel (Issue 4).
  • Behavior: restored work now goes to restoreCommit (its default is commit, so connectors that do not override it behave as before), and leftovers from commit are retried (1.13/1.15) or fail the job (1.20) instead of being acknowledged. This is the intended fix, but the 1.20 failure mode is a user-visible change (Issue 3).

1.3 Performance and Side Effects

Per committable: one weak reference and an identity-map entry on the global committer, cleared by reference queues. Committables are produced once per checkpoint per subtask, so the overhead is negligible. No new threads or I/O. RecoveredCommitTracker stays in "initializing" for the life of a never-restored job and keeps weak references for network-deserialized wrappers; they are reclaimed by GC and the queue, so this is bounded.

1.4 Error Handling and Logging

The design deliberately fails closed (IOException) when classification is inconsistent or a connector reuses a pending restored object. Fail-closed is right for silent-loss cases, but it must not trigger on a legitimate Flink state shape, otherwise a recoverable job turns into a failover loop (Issue 1).

Issue 1: Restored end-of-input committables are combined with live ones and fail the job on every restore

  • Location: seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/sink/FlinkGlobalCommitter.java:128-142; seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-15/src/main/java/org/apache/seatunnel/translation/flink/sink/RestoredCommittableOperator.java:73-80
  • Problem: In Flink 1.15+ CommittableCollector keeps end-of-input (EOI) committables in a separate manager that is not committed by commit(restoredId); they are only committed in GlobalCommitterOperator.endInput(), all in one GlobalCommitterAdapter.commit call, which calls combine once. Consider a STREAMING job with a bounded source and checkpoints enabled (checkpoints after tasks finish are on by default since 1.15): a checkpoint is taken after some writer subtasks already emitted their EOI committables, then the job restores from it. The restored EOI wrappers are deserialized from state and marked recovered by tracker.finishRestore(). The writer subtasks that had not finished yet emit their EOI committables after restore with no checkpoint id, so markRecovered leaves them live (getCheckpointId().isPresent() is false). endInput then calls combine with a mixed list and gets IOException("Cannot combine restored and live committables"), the job fails over, restores from the same checkpoint, and hits the same state again. Before this PR the same scenario committed all of them with commit().
    This is derived from the Flink 1.15.3 and 1.18.1 GlobalCommitterOperator sources and the PR code; I did not execute it. testMixedAndReusedAggregateFailClosed asserts the throw but no test builds the EOI-after-restore state.
  • Potential risk: A bounded streaming job that restores after partial completion never finishes and loops until the restart strategy gives up, with the sink's final transactions left uncommitted.
  • Best improvement: For a mixed batch, do not throw: route the whole combined committable through restoreCommit, which by contract must be idempotent and safe for both committed and uncommitted transactions (mark the combined object recovered). Keep the fail-closed check only for the "connector reused a pending restored object" case. Add a harness test (see Issue 2) that snapshots with one subtask's EOI committable already received, restores, delivers a second EOI committable and asserts endInput reconciles both exactly once through restoreCommit.
  • Severity: High; blocking.
  • Raised by another reviewer: No.

Issue 2: No test exercises a real snapshot/restore of the Flink 1.15 global committer operator

  • Location: seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-15/src/main/java/org/apache/seatunnel/translation/flink/sink/RecoveryAwareSink.java:108-145 (RecoverableLegacySink with a transient, lazily created tracker); seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/sink/RecoveredCommitTracker.java:27-51
  • Problem: The whole 1.15-1.18 classification relies on the state deserializer and the global committer sharing one tracker instance after the operator is Java-serialized to the task, and on filterRecoveredCommittables running after state is read. The new tests cover the pieces in isolation (RecoveryCommitSerializerTest builds the tracker by hand, RestoredCommittableOperatorTest calls the static helper, RecoveryTopologyTest checks IDs). None of them would fail if, for example, the serializer supplier and committer factory ended up with different RecoverableLegacySink copies (then nothing restored is ever marked and restored work silently goes through commit() again, which is the original bug). There is also no E2E restore on this branch; the description correctly says the earlier combined-tree E2E is historical.
  • Potential risk: A Flink minor upgrade or a refactor of RecoveryAwareSink.wrap can silently disable the fix while all tests stay green.
  • Best improvement: Add one OneInputStreamOperatorTestHarness-based test that builds the real global committer topology from RecoveryAwareSink.wrap(...), clones the operator with InstantiationUtil.clone (to reproduce the task-side deserialization), processes committables for checkpoint 1, snapshots, restores into a new harness, and asserts that the restored transaction reaches restoreCommit and a checkpoint-2 transaction reaches commit. The same harness covers Issue 1. Since the project rule is to extend an existing IT when the area has one, a restore assertion in the existing Flink checkpoint/restore E2E would be the ideal follow-up.
  • Severity: Medium; blocking together with Issue 1 because this is a checkpoint-recovery change whose key assumption is not exercised.
  • Raised by another reviewer: No.

Issue 3: Flink 1.20 now fails the job on leftover transactions, while 1.13/1.15 retry them

  • Location: seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-20/src/main/java/org/apache/seatunnel/translation/flink/sink/FlinkSimpleAggregatedCommitter.java:168-181
  • Problem: When commit/restoreCommit returns uncommitted items, the 1.20 committer now throws IOException, forcing a whole-job failover and restore. On 1.15-1.18 the same situation goes through GlobalCommitterAdapter, which calls retryLater() without a failover, and on 1.13 the pending list is retried at the next checkpoint. Not acknowledging the leftovers is correct; the asymmetric failure mode is the question.
  • Potential risk: On 1.20 a transient external-system hiccup that a connector reports as "retry" restarts the whole pipeline (and all sources) instead of retrying the commit, and it is a user-visible behavior change versus today's (lossy) success.
  • Best improvement: Either call request.retryLater() for the affected requests (Sink V2 supports this and keeps the restoreCommit vs commit routing via the restored checkpoint id), or keep the failover but state it explicitly in the PR description and in the docs/incompatible-changes.md (en/zh) so 1.20 users know commit retries now restart the job.
  • Severity: Medium; non-blocking.
  • Raised by another reviewer: No.

Issue 4: Flink 1.20 savepoints become forward-only

  • Location: seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-20/src/main/java/org/apache/seatunnel/translation/flink/sink/CheckpointCommitWrapperSerializer.java:41-60
  • Problem: New state is written as version 1 with a leading 8-byte checkpoint id. The previous CommitWrapperSerializer.deserialize ignores the version and would read the first 4 bytes of the long as a payload length.
  • Potential risk: Rolling back SeaTunnel after taking a savepoint on the new version fails or corrupts the committable on restore.
  • Best improvement: Document the one-way format change in docs/en/introduction/concepts/incompatible-changes.md and the zh counterpart. No code change needed.
  • Severity: Low; non-blocking.
  • Raised by another reviewer: No.

Issue 5: Fully qualified names inside fields and method bodies

  • Location: FlinkGlobalCommitter.java:51-80 (java.lang.ref.ReferenceQueue, java.util.Map, java.util.HashMap, java.lang.ref.WeakReference, java.lang.ref.Reference); RecoveryAwareSink.java:97-102,108-159 (org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator, org.apache.flink.api.common.typeinfo.TypeInformation, V1 org.apache.flink.api.connector.sink.*); FlinkSimpleAggregatedCommitter.java:172-175 (java.util.Collections).
  • Problem: Inconsistent with the rest of the module, which imports types. In RecoveryAwareSink the V1/V2 Sink/SinkWriter name clash is real; aliasing via a small nested type or importing the V2 types only where needed keeps it readable.
  • Potential risk: Readability only.
  • Best improvement: Import the types (keep FQN only where the V1/V2 name clash actually forces it).
  • Severity: Low; non-blocking.
  • Raised by another reviewer: No.

Issue 6: New recovery classes lack class-level Javadoc and why-comments

  • Location: RecoveredCommitTracker.java:27 (no Javadoc; the initializing lifecycle and the shared-instance assumption are not explained), RestoredCommittableOperatorFactory.java (no Javadoc), CheckpointCommitWrapper.java and CheckpointCommitWrapperSerializer.java (no Javadoc; the v1 envelope layout is undocumented), and the restored/current classification in FlinkSimpleAggregatedCommitter.java:78-89.
  • Problem: This is subtle checkpoint-recovery code; a future maintainer cannot tell from the code why weak references are used, when finishRestore must run, or why a legacy wrapper without a checkpoint id counts as restored.
  • Potential risk: A well-meaning cleanup breaks recovery classification.
  • Best improvement: A short class Javadoc on each new class, plus one comment on the tracker hand-off contract and one on the v1 byte layout.
  • Severity: Low; non-blocking.
  • Raised by another reviewer: No.

2. Code Quality Assessment

2.1 Coding Standards

ASF headers present, no wildcard imports. Gaps are the FQNs (Issue 5) and missing class/why comments (Issue 6). RecoveryAwareSink and RestoredCommittableOperator override interface methods without @Override, unlike the rest of the module.

2.2 Test Coverage and Test Stability

New tests: RecoveryCommitSerializerTest, RecoveryTopologyTest, RestoredCommittableOperatorTest (1.15), CheckpointCommitWrapperSerializerTest, FlinkSimpleAggregatedCommitterTest (1.20), FlinkGlobalCommitterTest (common). They are deterministic, in-memory and assert concrete routing (restoreCommit vs commit, returned pending lists, v0/v1 round trips, operator IDs), so each would fail if the corresponding branch were removed. The gap is a restore-level test of the real operator (Issue 2) and the EOI shape (Issue 1).

Test stability: Stable for what is added (no sleeps, no shared state, no network). No existing test was modified or weakened.

Local analysis: read the full diff, traced the starter-to-translation module mapping, and read the relevant Flink 1.15.3 and 1.18.1 operator sources. No local compilation, tests or jobs were run.

2.3 Documentation Updates

No docs change. The behavior is internal except for Issue 3 (1.20 failure mode) and Issue 4 (savepoint format), which should be noted in incompatible-changes.md en/zh.

3. Architectural Soundness

3.1 Fix versus Workaround

Root-cause fix at the right layer: the translation layer is where Flink's committable lineage meets SeaTunnel's restoreCommit contract, and no connector or API change is needed. On 1.20 the explicit checkpoint id in the committable is the cleanest design. On 1.15-1.18 the tracker plus operator decorator is a necessary workaround for the V1 adapter not exposing lineage, which is why it needs the stronger test in Issue 2.

3.2 Maintainability

The 1.15 path depends on Flink internals (StandardSinkTopologies calling global().transform(...), GlobalCommitterOperator calling filterRecoveredCommittables after reading state). Both hold for 1.15.3 and 1.18.1; a harness test is the guard against drift.

3.3 Historical-Version Compatibility

1.13/1.15-1.18 state and operator IDs are unchanged; 1.20 reads old state but writes a new forward-only format (Issue 4).

4. Issue Summary

Number Issue Location Severity
1 Restored EOI committables mixed with live ones fail the job on every restore FlinkGlobalCommitter.java:128-142; RestoredCommittableOperator.java:73-80 High
2 No real snapshot/restore test for the 1.15 global committer path RecoveryAwareSink.java:108-145; RecoveredCommitTracker.java:27-51 Medium
3 1.20 fails the job on leftovers while 1.13/1.15 retry FlinkSimpleAggregatedCommitter.java:168-181 Medium
4 1.20 savepoints become forward-only CheckpointCommitWrapperSerializer.java:41-60 Low
5 Fully qualified names in fields and bodies FlinkGlobalCommitter.java:51-80; RecoveryAwareSink.java:97-159 Low
6 Missing class Javadoc and why-comments on recovery classes RecoveredCommitTracker.java, RestoredCommittableOperatorFactory.java, CheckpointCommitWrapper*.java Low

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers - must be fixed
    • Issue 1: avoid the fail-closed throw for the legitimate restored-plus-live EOI shape.
    • Issue 2: add a real snapshot/restore harness test for the 1.15 global committer (it also proves Issue 1).
  2. Recommended - non-blocking
    • Issue 3 (align or document the 1.20 failure mode), Issue 4 (document forward-only 1.20 state), Issues 5 and 6 (style and comments).

CI on head 484f2190fdbd5b8476ba5683db915db732f6099d: Signal pull request update = SUCCESS; Build is pending on the apache side and the real fork run (Build 41574195259) is still in progress, so there is no execution result yet. Base dev: ahead 1 / behind 3, not a sync request.

Overall this is a valuable fix and most of it is careful; once the EOI case is handled and the restore path has one real harness test, I would be happy to re-check quickly.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

CI follow-up on the unchanged head 484f2190fdbd5b8476ba5683db915db732f6099d. My review above said the fork Build was still in progress; it has now failed, and this failure looks caused by this PR, so I want to flag it rather than suggest a rerun.

Failed jobs in fork Build 41574195259:

What the logs show: in LocalFileWithMultipleTableIT (the fake_to_local_file_with_multiple_table job writing to /tmp/fake_empty/text/${table_name}), the file commit fails with Parent directory does not exist: /tmp/fake_empty/text (via FileSinkAggregatedCommitter.commit -> FlinkGlobalCommitter.commit:163). On the Flink 1.13.6 container this error appears 6 times. On the Flink 1.15.3 container the same commit is retried in a tight loop from GlobalCommitterOperator.endInput -> CheckpointCommittableManagerImpl.commit: more than 62,000 identical errors in the first ten minutes of each JDK lane (the job logs are roughly 750 MB each). The runners then lose contact, which matches log/CPU starvation.

Why I attribute it to this PR: on dev, FlinkGlobalCommitter.commit logs a warning for returned re-committables and returns an empty list, so Flink stops retrying. In this head, commit returns the connector's failed infos as pending, and Flink 1.15's global committer keeps retrying pending committables at end of input with no bound or backoff. A commit that fails permanently therefore turns into an endless busy loop instead of a single failure. This matches what my previous review noted about retrying leftovers on 1.13/1.15. It is based on the job logs and source; I did not run it locally.

Suggested direction: retrying a recoverable commit is fine, but a commit that keeps failing must end in a bounded outcome. Either fail the job after a limited number of attempts, or keep the old "warn and drop" behavior for the end-of-input path, and log the failure once rather than per attempt. A focused test where commit always returns the same committable and the test asserts the operator ends (fails or finishes) would cover it. The underlying /tmp/fake_empty/text commit error in this IT is worth a look too, since dev currently hides it.

Previous blockers still stand: Issues 1 and 2 from my review. Together with this unbounded retry loop, I see it as not ready to merge yet. A rerun alone will not help, because the loop reproduced on both JDK lanes. Thanks for keeping at this; the provenance tracking itself is a valuable fix.

@goutamadwant

Copy link
Copy Markdown
Collaborator Author

Pushed 6829c0a90: bounded unresolved-commit failures, corrected aggregate-only recovery routing, and added topology regressions and LocalFile output checks. Java 11/17 passed 23/35 tests; direct Flink 1.13/1.15 runs passed. Earlier helper tests missed the actual adapter specialization and end-of-input retry loop. Merge after #13109; combined JDBC engine crash/recovery validation remains pending.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks a lot, @goutamadwant, for the fast and thorough follow-up. I re-reviewed the new head 6829c0a90e60 (commit 6829c0a90e on top of 484f2190fd, base dev 3244c9504c75) with the full diff, and traced the Flink 1.13, 1.15-1.18 and 1.20 commit/recovery paths again. The new harness tests are exactly what I was hoping for, and the unbounded end-of-input retry loop is fixed at the right place.

I owe you an apology first: while re-tracing the restored end-of-input path for this round, I found a connector interaction (Issue A below) that already applied to the restored-only end-of-input batches in the previous head, and I missed it last time. It is a carryover, not something your new commit introduced. I also need to correct my earlier Issue 6: RecoveredCommitTracker, RestoredCommittableOperatorFactory, CheckpointCommitWrapper and CheckpointCommitWrapperSerializer already had class Javadocs in the previous head; only the "why" comment on the tracker hand-off is still missing.

What Problem Does This PR Solve?

  • User pain point (#13106): after a Flink checkpoint/savepoint restore, restored committables went through the ordinary commit() path or were dropped, and leftovers returned by the aggregated committer were logged and treated as success.
  • Fix approach: mark restored committables and route them through SinkAggregatedCommitter.restoreCommit, keep fresh work on commit(), and stop acknowledging unresolved transactions.
  • What changed since my last review (6829c0a90e):
    • FlinkGlobalCommitter.combine routes a mixed restored + live aggregate through restoreCommit instead of throwing.
    • FlinkGlobalCommitter.commit / filterRecoveredCommittables now fail the task when the connector returns unresolved transactions, instead of returning them as pending (which made Flink 1.15 spin at end of input).
    • RecoveryAwareSink.wrap also decorates aggregate-only sinks (CommittingRecoveryAwareSink), which the first head left unwrapped.
    • Real OneInputStreamOperatorTestHarness restore tests, incompatible-changes.md en/zh, and stricter LocalFile E2E fixtures/assertions.

Status of previous findings

Previous item Status on 6829c0a90e60 Evidence
Issue 1: restored EOI + live EOI fail the job on every restore Fixed FlinkGlobalCommitter.java:129-144 (any recovered element marks the aggregate recovered); RecoveryTopologyTest.java:104-127
Issue 2: no real snapshot/restore test of the 1.15 global committer Fixed RecoveryTopologyTest.java:242-288 builds the factory from RecoveryAwareSink.wrap, clones it with InstantiationUtil.clone (line 278), snapshots and restores; five restore scenarios at lines 78-200
CI follow-up: endless end-of-input retry on Flink 1.15 Fixed FlinkGlobalCommitter.java:170-182 throws instead of returning pending; RecoveryTopologyTest.java:166-179 plus the guard at line 388 would turn the old busy loop into an AssertionError
Issue 3: 1.20 fails while 1.13/1.15 retry Resolved by alignment All three paths now fail on leftovers, which matches Zeta (SinkAggregatedCommitterTask.java:316-320 for commit, :274-278 for restore); documented in incompatible-changes.md
Issue 4: 1.20 savepoints become forward-only Fixed (documented) docs/en/introduction/concepts/incompatible-changes.md and the zh counterpart
Issue 5: fully qualified names in fields/bodies Still open (Low) see Issue C
Issue 6: missing why-comments Partly open (Low), corrected above see Issue C

1. Code Change Review

1.1 Core Logic Analysis

The normal path is hit: SinkExecuteProcessor.java:68 wraps every Flink 1.15-1.18 sink with RecoveryAwareSink.wrap(...), and every aggregated commit now goes through the new fail-on-leftover logic, even without a restore.

// FlinkGlobalCommitter (common, used by 1.13 and 1.15-1.18)
public GlobalCommT combine(List<CommitWrapper<CommT>> committables) throws IOException {
    boolean replay = committables.stream().anyMatch(CommitWrapper::isRecovered);
    GlobalCommT combined = aggregatedCommitter.combine(...);
    if (replay) markRecovered(combined);
    else if (isRecovered(combined)) throw new IOException("...reused a pending restored transaction");
    return combined;
}
private void failIfPending(List<GlobalCommT> pending) throws IOException {
    if (pending != null && !pending.isEmpty())
        throw new IOException("Aggregated commit has unresolved transactions; recovery is required");
}

Runtime flow on Flink 1.15-1.18 (bounded streaming job, restore after partial finish):

checkpoint k: subtask A already finished -> its EOI committable sits in the CommittableCollector EOI manager
restore from k
 -> GlobalCommitterOperator.initializeState: RecoveryCommitSerializer -> tracker.deserialized(A)
 -> FlinkGlobalCommitter.filterRecoveredCommittables: tracker.finishRestore() marks A recovered
      restoreCommit(sinkV1State); leftovers -> IOException (task fails, restart strategy applies)
 -> RestoredCommittableOperator.processElement: replays with checkpointId <= k marked recovered
 -> later checkpoints (> k): combine(live) -> commit(); leftovers -> IOException
 -> endInput: GlobalCommitterAdapter -> combine([A recovered, B live]) -> marked recovered
      -> commit() -> restoreCommit([A+B]) for the whole aggregate

This is now consistent and bounded on every Flink version, and it matches Zeta's behavior for both commit and restoreCommit. The new CommittingRecoveryAwareSink (RecoveryAwareSink.java:90-118) keeps the adapter's capability shape (testWrappingPreservesAdapterCapabilitiesAndOperatorIds, RecoveryTopologyTest.java:203-224).

The remaining correctness question is what each connector's restoreCommit does with an end-of-input aggregate on Flink (Issue A).

1.2 Compatibility Impact

  • Flink 1.13 / 1.15-1.18 committable bytes, serializer versions and operator IDs are unchanged; 1.20 writes v1 and reads v0, now documented as forward-only.
  • User-visible behavior: on Flink, an aggregated commit that returns unresolved transactions now fails the task instead of reporting success with missing output. This is the right fix and is documented in en/zh. Note it will also surface commit failures that dev silently hid in other Flink E2E suites (the LocalFile fixture was one of them), so the full fork CI result matters here.
  • No config option, default value or public API change.

1.3 Performance and Side Effects

Unchanged from my previous round: one weak reference per committable, no new threads or I/O. The busy loop is gone. Restart behavior now follows the user's Flink restart strategy.

1.4 Error Handling and Logging

Failing closed is correct. The exception is a bit thin for operators (Issue B).

Issue A: Iceberg's restoreCommit can skip a whole restored end-of-input aggregate on Flink (silent data loss)

  • Location: seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/sink/FlinkGlobalCommitter.java:129-144, :155-160; seatunnel-connectors-v2/connector-iceberg/src/main/java/org/apache/seatunnel/connectors/seatunnel/iceberg/sink/commit/IcebergAggregatedCommitter.java:64-77; seatunnel-connectors-v2/connector-iceberg/src/main/java/org/apache/seatunnel/connectors/seatunnel/iceberg/sink/commit/IcebergAggregatedCommitInfo.java:36-37; seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/sink/FlinkSink.java:78-92 and seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/sink/FlinkSinkWriter.java:216-230
  • Problem: IcebergAggregatedCommitter.restoreCommit skips an aggregate when isAlreadyCommitted(getCheckpointId(), ...) is true, and getCheckpointId() is the id of the first IcebergCommitInfo only. On Flink that id is not a global checkpoint id: it is a per-subtask counter in FlinkSinkWriter (starts at 1 or restored state + 1, incremented on each prepareCommit). Consider a bounded streaming job: subtask A finishes and emits its EOI committable with counter c; subtask B keeps running, prepares its next checkpoint with the same counter c, and that live checkpoint is committed to Iceberg with seatunnel.checkpoint-id = c. The job then restores from a checkpoint that holds A's EOI committable. At endInput, combine([A(c), B(...)]) is marked recovered and goes to restoreCommit; getCheckpointId() returns c, isCommittedById(c) finds B's earlier snapshot, and the whole aggregate (A's and B's final files) is skipped and acknowledged. Before this PR, Flink sent these through commit(), which does not deduplicate, so the data was committed. The same applies to a restored-only EOI aggregate, which the previous head already routed to restoreCommit (hence the carryover).
    This is derived from the sources above; I have not executed it. It depends on the restored EOI committable being first in the combined list, which matches how the 1.15 CommittableCollector keeps restored entries before new ones.
  • Potential risk: an Iceberg sink on Flink 1.15-1.18 can finish successfully while its final files are never committed. That is worse than the failover this PR is fixing, because nothing fails.
  • Best improvement: the root cause is in Iceberg's dedupe key, not in your routing, so I would not undo the routing. A small companion fix in the Iceberg connector (for example, use the existing file-based areFilesAlreadyCommitted check when the aggregate mixes checkpoint ids, or require every commit info's id to be committed instead of only the first) gated like #13109, plus one Iceberg restore test, would close it. If you prefer to keep that out of scope, please at least list it in the PR's integration gate and in incompatible-changes.md next to the JDBC XA note, and open an issue for it. A quick audit note of the other restoreCommit overrides would also help reviewers: today only JDBC (JdbcSinkAggregatedCommitter.java:97-107, already gated on #13109) and Iceberg override it; the rest fall back to commit.
  • Severity: High; blocking until it is either fixed in a companion PR or explicitly gated/documented.
  • Raised by another reviewer: No.

Issue B: The fail-closed exception carries no context

  • Location: seatunnel-translation/seatunnel-translation-flink/seatunnel-translation-flink-common/src/main/java/org/apache/seatunnel/translation/flink/sink/FlinkGlobalCommitter.java:174-182
  • Problem: the message does not say how many transactions are unresolved or whether the restore path or the live path produced them, and nothing is logged. Zeta logs aggregated committer error: {size} before throwing.
  • Potential risk: slower diagnosis when a production job starts failing over after upgrade.
  • Best improvement: include pending.size() and the path (restoreCommit / commit) in the message; do not log the committables themselves, since they can contain connection details.
  • Severity: Low; non-blocking.
  • Raised by another reviewer: No.

Issue C: Remaining style points (carryover of Issues 5 and 6)

  • Location: fully qualified names in FlinkGlobalCommitter.java:51-80, RecoveryAwareSink.java:133-174 (only the V1/V2 Sink clash really needs them), FlinkSimpleAggregatedCommitter.java:173-175, and the tests (FlinkGlobalCommitterTest.java:41-136 use java.io.IOException / org.mockito.Mockito inline). Missing @Override on the delegate methods in RecoveryAwareSink.java:63-87 and RestoredCommittableOperator.java:48-155. The tracker hand-off contract (serializer supplier and committer factory must share one RecoverableLegacySink, RecoveryAwareSink.java:143-182) still has no "why" comment, although the new clone-based test now guards it.
  • Potential risk: readability only.
  • Best improvement: import the types, add @Override, and one sentence on the shared-instance contract.
  • Severity: Low; non-blocking.
  • Raised by another reviewer: No.

2. Code Quality Assessment

2.1 Coding Standards

ASF headers present, no wildcard imports, the new comments in combine and failIfPending explain the why. Remaining points are in Issue C.

2.2 Test Coverage and Test Stability

  • RecoveryTopologyTest (1.15): real operator, cloned factory, snapshot/restore, parameterized with and without a local committer. Each case would fail on the bug it targets: the mixed EOI case throws on the previous head, the busy-loop case hits the AssertionError guard on the previous head, the partial-success case asserts restoreCommit receives first|second after restore.
  • FlinkGlobalCommitterTest: assertions changed from "pending returned" to "throws". This follows the intended semantic change inside an unmerged PR, not a weakening.
  • LocalFileIT / LocalFileWithMultipleTableIT: chmod 1777 addresses the real cause of Parent directory does not exist: /tmp/fake_empty/text (fixture created as root, Flink worker is a different user), and the new assertions require non-empty output for fake1 and fake2. This strengthens the IT; on dev it passed with missing output.
  • Test stability: Stable. RecoveryTopologyTest uses a static ledger but is @Isolated and resets it per test; no sleeps or network. The E2E assertions are deterministic once the job finishes.
  • Gap: harness tests run against Flink 1.15.3 only, while the module also serves 1.16-1.18; non-blocking given the operator APIs used are unchanged across those versions.

2.3 Documentation Updates

incompatible-changes.md en and zh are in sync and cover restore routing, fail-on-leftover, the #13109 gate and 1.20 forward-only state. Issue A should be added there if it is not fixed in a companion PR.

3. Architectural Soundness

Root-cause fix at the translation layer, and aligning Flink's leftover handling with Zeta is the right call. The mixed-aggregate routing is sound only if every connector's restoreCommit is safe for never-committed work identified by Flink's per-subtask ids; JDBC is gated on #13109 and Iceberg needs the same treatment (Issue A). The pom.xml change adds only test-scoped Flink test jars at the existing ${flink.1.15.3.version}.

4. Issue Summary

Number Issue Location Severity
A Iceberg restoreCommit can skip a restored EOI aggregate on Flink (carryover) FlinkGlobalCommitter.java:129-160; IcebergAggregatedCommitter.java:64-77; IcebergAggregatedCommitInfo.java:36-37 High
B Fail-closed exception has no context FlinkGlobalCommitter.java:174-182 Low
C FQNs, missing @Override, tracker hand-off comment (carryover) FlinkGlobalCommitter.java:51-80; RecoveryAwareSink.java:63-182; RestoredCommittableOperator.java:48-155 Low

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers - must be fixed
    • Issue A: fix Iceberg's restore dedupe in a companion PR (preferred) or explicitly gate and document it alongside #13109.
    • Merge order: this PR still depends on #13109, which is open.
  2. Recommended - non-blocking
    • Issue B and Issue C.

CI on head 6829c0a90e60b9430c48fd478ed727b8e30660d1: Signal pull request update passed; Build is pending on the apache side and the real fork run (Build 41792625123) is still queued, so there is no execution result yet. Because this head now fails on commit errors that dev used to hide, please check the full run, not only the LocalFile jobs. Base dev: ahead 2 / behind 3, mergeable, no sync needed.

All three previous blockers are resolved, and the harness tests make this much easier to trust. Once Issue A has a clear resolution and CI is green, I will be glad to re-check quickly.

@DanielLeens

Copy link
Copy Markdown
Contributor

Build has now failed, superseding the queued status in my review. The LocalFile JDK 11/17 lanes and JDBC part 7 JDK 11/17 lanes failed. The JDK 11 LocalFile log reports four failures in LocalFileIT.testLocalFileOrcParquetBinaryXml:458, reaching 'Aggregated commit has unresolved transactions; recovery is required' / 'Aggregated committer returned uncommitted transactions'. That reaches the commit behavior changed here, so I cannot dismiss it as infrastructure noise or recommend a blind sync. Please inspect which file committables remain after commit and why, retaining the fail-closed guard; verify the complete LocalFile matrix after correcting the contract. Separately, JDBC part 7 reports MetalakeIT.startUp:158 readiness timeouts before the job. That fixture is unchanged in latest dev, so a sync is not an established remedy for it; retry that lane separately and retain service logs if it repeats. The existing Iceberg restore blocker and #13109 merge prerequisite remain.

CI reference: Build 41792625123.

This updates CI/merge facts on the already-reviewed head; it is not another full source review. No local runtime testing was performed. Daniel has READ permission; effective maintainer approval/dismissal remains separate.

Document JDBC XA cleanup (apache#13109) and Iceberg payload replay (apache#12881) prerequisites. Composed connector recovery validation remains pending.
@goutamadwant

Copy link
Copy Markdown
Collaborator Author

Added pending-transaction counts and restore/commit diagnostics, cleaned up imports and overrides, and fixed the binary-output fixture permissions. The docs gate connector rollout on #13109 and #12881; composed crash/recovery validation remains pending.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-checked the new head 244897a9. Unlike a plain sync, the commit [Fix][Flink] Merge dev and validate worker binary output merges dev and also carries real PR changes, so I reviewed those against my last review (6829c0a9).

What changed in the PR's own files:

  • FlinkGlobalCommitter: the fail-closed IOException now reports the unresolved count and the path (restoreCommit vs restoreCommit=N, commit=M). This closes my Issue B. pending is non-null at that call site, so the new message cannot NPE.
  • Issue C (Low): fully qualified names in FlinkGlobalCommitter, RecoveryAwareSink, FlinkSimpleAggregatedCommitter and the unit test are replaced by imports, @Override is added, and a why-comment was added for the shared tracker hand-off. Pure cleanup, no behavior change.
  • FlinkGlobalCommitterTest: assertions got stricter (they now check the unresolved count and the restoreCommit=0, commit=1 message); nothing was weakened.
  • LocalFileIT: /seatunnel/read/binary2 is created and made writable for non-root workers, and the binary test now asserts that the committed copy exists and matches (cmp) instead of passing without output. This is a stricter check than before.
  • incompatible-changes.md (en and zh): documents the JDBC XA cleanup prerequisite (#13109, open) and the Iceberg replay prerequisite (#12881, open).

Status of my previous blocker, Issue A (Iceberg restoreCommit can skip a restored end-of-input aggregate because Flink writer checkpoint counters are not globally unique): I did not ask for the routing to be undone, only for a companion fix or an explicit gate. The docs now state the Iceberg limitation and gate recovery on #12881 and #13109, which meets the "explicitly gated/documented" alternative I offered. The underlying Iceberg dedupe defect itself is still fixed only by that separate PR, so please keep that dependency visible in the PR description.

CI: the apache-side Build is red (https://github.com/apache/seatunnel/runs/128491055919), but the real fork run (https://github.com/goutamadwant/seatunnel/actions/runs/42401801261) has 84 jobs green, 11 skipped and exactly one failure: Run / unit-test (17, windows-latest). It died in 33 seconds in the "run all modules unit test (Windows)" step because the Maven wrapper download from repo.maven.apache.org returned 403 (MavenWrapperMain not found). That is infrastructure, not this diff. The LocalFile and Flink suites that failed on the earlier head are green now. Minimum next step: re-run only that failed job (gh run rerun 42401801261 --job 128492562720 on the fork, or ask a maintainer to retrigger); no code change or dev sync is needed. Once it is green I will approve. The branch is 1 commit behind dev.

Conclusion: Ready to merge after fixes (only the CI re-run remains)

Blockers: None in the source review. CI: one infrastructure failure to re-run.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks @goutamadwant for re-running CI. CI was previously the only remaining blocker; CI is now passing, so I am changing my conclusion to approve.

The fork run https://github.com/goutamadwant/seatunnel/actions/runs/42401801261 (attempt 2) on head 244897a9 is fully green: 85 jobs passed, 11 skipped, none failed. That includes unit-test (17, windows-latest), which hit the Maven wrapper download error last time. The apache-side Build check is green as well.

My source review on this head is unchanged: no blocking findings. Please keep the dependency on #12881 and #13109 for Iceberg / JDBC XA recovery visible in the PR description, as noted earlier.

Conclusion: Approve

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-checked the new head 194b9460: the only change since my last review (244897a9) is a merge of the latest dev (the commit resolves the incompatible-changes.md migration-note overlap). The PR's own diff is unchanged: same 25 files, and the changed lines are identical to what I approved.

Previous points

  • My last review had no source blocker. Please keep the dependency on #12881 and #13109 for Iceberg / JDBC XA recovery visible in the PR description, as noted before.

CI

  • The fork Build for this head has started but most jobs are still queued (6 passed, 79 queued, none failed so far), and the apache-side Build check is pending. Because my approval was on 244897a9, I am leaving this as a comment and will approve again once this head is green. Nothing is needed from you for now.
  • One heads-up: this head is one commit behind dev, missing #13203. If SftpFileIT fails on the atmoz/sftp:alpine-3.7 image pull, that is the removed Docker Hub tag, unrelated to this PR, and a sync with dev clears it.

Conclusion: Ready to merge once CI is green

Blockers

  • None (CI pending only).

@DanielLeens

Copy link
Copy Markdown
Contributor

Quick CI follow-up on 194b9460: the fork Build has finished. In my last review I said nothing was needed from you, but that has now changed. None of the failures are related to this PR (the Flink translation tests and unit-test passed on all JDKs).

Smallest next step: merge the latest dev (3 commits, including #13203). The new push re-runs everything, which also covers the flaky jobs. I will approve again once it is green.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-checked the new head 853d45b4, @goutamadwant: compared with the head I last reviewed (194b9460), the only change is the Sync dev for current CI fixtures merge, and the PR's own net diff against dev is byte-identical (same files, same changed lines). Thanks for syncing.

Previous points: my earlier conclusion had no non-CI blocker, and the merge does not touch the PR's files, so nothing changes on the source side.

CI: the fork Build for this head has just started (no failures so far). Because the head moved, I am leaving this as a comment and will approve once that run is green.

Branch state: ahead, ahead 5 / behind 0 of dev; no conflicts reported.

Conclusion: Ready to merge

  • Blockers (non-CI): none.
  • Remaining gate: CI on this head.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for the earlier sync. The CI fact cited in my previous comment has changed: Build 42979519338 is now cancelled, rather than running without failures. My previous source-level conclusion remains clear; this is a CI clarification, not a new source review.

The unfinished lanes are all-connectors-part-3 on JDK 11 and 17. The JDK 11 log ends during the BigQuery streaming fixture submitted through the Flink 1.15 container, with "The operation was canceled" rather than a reported assertion failure. That is incomplete validation, not a passing lane or proof of a provenance regression.

I did not find a merged base-branch fix that establishes a remedy for this cancellation. Please first check for an active replacement run; if none exists, rerun the cancelled lanes and retain the last container/job logs if the BigQuery fixture stalls again. A simple base sync is not an established fix, and unrelated connector changes should not be added to this PR to chase the cancelled run.

Build and cancelled jobs. Upstream drift remains separate metadata. Passing exact-head CI and effective maintainer review are still required; no local tests were run.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug][Translation][Flink] Restored committables lose recovery commit handling

2 participants