Skip to content

[Fix][Zeta] Fix stop-with-savepoint hang in DOING_SAVEPOINT - #11489

Merged
davidzollo merged 29 commits into
apache:devfrom
agarwalrahul2702:fix-zeta-stop-with-savepoint-11473
Aug 23, 2026
Merged

davidzollo merged 29 commits into
apache:devfrom
agarwalrahul2702:fix-zeta-stop-with-savepoint-11473

Conversation

@agarwalrahul2702

@agarwalrahul2702 agarwalrahul2702 commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

[Fix][Zeta] Fix stop-with-savepoint hang in DOING_SAVEPOINT

Fixes #11473

Root cause

This failure path had three related problems:

  1. Savepoint barriers could be starved while a source emitted a large split.
    SourceFlowLifeCycle.triggerBarrier needs the checkpoint lock to inject the
    savepoint barrier. FakeSourceReader.pollNext emitted a whole split in one call
    while holding that lock, so a huge split could keep the barrier thread blocked until
    the savepoint timed out. The same risk existed for explicit user-configured rows,
    because the custom-row path ignored the requested row count and emitted the whole list.

  2. Failed stop-with-savepoint could leave the job in DOING_SAVEPOINT.
    The savepoint failure was reported through checkpoint failure handling, but the
    stop-with-savepoint job-state transition did not have a deterministic failure exit.

  3. Multi-pipeline partial savepoint failure was unsafe.
    One pipeline could complete its savepoint while another failed. The failure path must
    not report the global job as RUNNING, and it must not force-stop a pipeline before
    that pipeline's checkpoint coordinator has finished its savepoint finalization.

Solution

  • FakeSourceReader now emits large generated splits and large custom rows lists in
    bounded batches. This releases the checkpoint lock between batches so savepoint
    barriers can be injected.
  • Random generated splits requeue a new split containing the remaining row count.
  • Custom-row splits requeue a new split containing the next custom-row index to emit, so
    a checkpoint/savepoint taken between batches snapshots only the not-yet-emitted rows
    and does not duplicate already-emitted custom rows.
  • FakeSourceSplit identity now uses only tableId and splitId, not mutable progress
    (rowNum), and the reader no longer mutates the assigned split object when requeueing
    partial progress. This avoids rediscovering already-assigned splits after restore.
  • CheckpointManager#triggerSavePoints preserves the existing public API. A separate
    additive triggerSavePointsAndWaitComplete path returns futures that complete only
    after each checkpoint coordinator reaches its terminal savepoint state, not merely after
    the pending savepoint checkpoint is acknowledged.
  • JobMaster#savePoint now keeps the state transition, savepoint triggering, completion
    aggregation, and failure cleanup in one guarded operation. If any pipeline savepoint
    fails, the whole job leaves DOING_SAVEPOINT through PhysicalPlan#savepointFailed,
    which stops the job instead of reporting it as running again.

Regression coverage

  • Busy generated-source stop-with-savepoint completes and reaches SAVEPOINT_DONE.
  • Busy custom-rows stop-with-savepoint completes and reaches SAVEPOINT_DONE.
  • Normal stop while the source is busy still reaches CANCELED.
  • Single-pipeline savepoint timeout reports an error and leaves DOING_SAVEPOINT.
  • Multi-pipeline partial savepoint failure stops the whole job; pipeline states are
    terminal and the successful pipeline checkpoint coordinator reaches SUSPEND.
  • Fake source enumerator restore does not rediscover assigned splits when restored split
    progress has a different remaining row count.
  • Custom-row generation can emit a bounded slice of the configured rows list.

Verification

Local verification in this workspace:

Command Result
./mvnw spotless:check BUILD SUCCESS
./mvnw spotless:apply BUILD SUCCESS
git diff --check PASS

Targeted test execution is blocked in this cleaned workspace by repository dependency
setup before the changed modules are reached:

  • ./mvnw -pl seatunnel-connectors-v2/connector-fake -Dtest=FakeDataGeneratorTest#testCustomRowDataSlice -DfailIfNoTests=false test cannot resolve org.apache.seatunnel:seatunnel-shade:pom:3.0.0-SNAPSHOT.
  • ./mvnw -pl seatunnel-engine/seatunnel-engine-server -Dtest=SavePointBusySourceTest#testStopWithSavepointCompletesWhileSourceEmitsLargeCustomRows -DfailIfNoTests=false test hits the same unresolved local SNAPSHOT parent.
  • Re-running both with -am gets past SNAPSHOT resolution but fails earlier in the reactor at seatunnel-config-shade, where shaded Typesafe Config sources cannot find generated/shaded config classes.

These build blockers are outside this patch. Formatting and whitespace checks pass.

Checklist

  • Code changed follows the project code style
  • New files carry the ASF license header
  • Regression tests added
  • No user-facing config options changed
  • No new dependencies

The savepoint barrier is injected into the source under the checkpoint
lock, but FakeSourceReader emitted an entire split in a single pollNext
call while holding that lock. With a large split (e.g. row.num=100000000,
split.num=1) the lock is effectively never released, the barrier can
never be injected, every checkpoint/savepoint expires, and stop-job with
isStopWithSavePoint=true leaves the job stuck in DOING_SAVEPOINT forever
while its slots stay occupied.

Fix:
- FakeSourceReader emits at most 4096 rows per pollNext call and requeues
  the remainder of the split at the head of the split deque, releasing
  the checkpoint lock between batches so barriers can be injected. The
  requeued split carries the remaining row count, so snapshots taken
  between batches capture the not-yet-emitted rows.
- When a savepoint does not complete, JobMaster.savePoint now reverts the
  job state from DOING_SAVEPOINT back to RUNNING (the job keeps running
  after a failed savepoint), so the failure is surfaced to the caller
  instead of wedging the job in DOING_SAVEPOINT.

SavePointBusySourceTest covers: stop-with-savepoint completes under a
busy source, DOING_SAVEPOINT -> SAVEPOINT_DONE, the request returns,
slots are released, normal stop is unchanged, and a failed savepoint
reports an error while the job recovers.

Fixes apache#11473

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for working on this. I re-reviewed the complete current diff and traced both the FakeSource checkpoint-lock path and the engine savepoint lifecycle. The bounded FakeSource polling is a good fix for the original lock-starvation problem, but I found one multi-pipeline failure case that still needs to be addressed before merge.

Blocking finding

Issue 1: a partially successful multi-pipeline savepoint can leave the job reported as RUNNING while one pipeline is already suspended/stopped

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/master/JobMaster.java:1266-1297, .../checkpoint/CheckpointManager.java:158-161, and .../dag/physical/PhysicalPlan.java:217-243
  • Runtime path: JobMaster.savePoint() first moves the whole job to DOING_SAVEPOINT, then triggerSavePoints() starts one independent savepoint per checkpoint coordinator. Each successful coordinator transitions to SUSPEND. If another coordinator fails, the new finally block only calls physicalPlan.savepointFailed(), which unconditionally changes the global state back to RUNNING; it does not restore a coordinator/pipeline that already completed its savepoint.
  • Risk: a job with multiple pipelines can become globally RUNNING with only a subset of its pipelines still executing. The current regression coverage uses a single pipeline, so it cannot detect this split-brain lifecycle state.
  • Suggested fix: wait for and classify every pipeline savepoint result, and on any failure either restore every pipeline that already suspended or fail/stop the whole job deterministically. Please add a multi-pipeline test where one savepoint completes and another fails before asserting the final global and per-pipeline states.

Severity: High. Merge gate: blocking.

The current Build check is also failing, so CI remains a separate gate; a green rerun would not clear the lifecycle blocker above. Happy to re-review once this path is updated.

@nzw921rx nzw921rx left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for working on this. I re-reviewed the complete current diff at head 3a9067c9 and checked the existing review discussion to avoid repeating the previously reported multi-pipeline RUNNING/suspended-state issue.

What this PR fixes

  • FakeSourceReader no longer emits an entire large random-data split in one pollNext() call.
  • The remaining rows are requeued so that the checkpoint lock can be released between batches.
  • A failed multi-pipeline savepoint now stops the whole job deterministically instead of reverting the global state to RUNNING.

The overall direction is reasonable, but I found two new blocking regressions in the current implementation.

Runtime paths reviewed

FakeSource split assignment
  -> FakeSourceSplitEnumerator.assignedSplits
  -> ParallelEnumeratorContext.assignSplit()
  -> FakeSourceReader.pollNext()
  -> checkpoint / Spark micro-batch restore

Stop with savepoint
  -> JobMaster.savePoint()
  -> CheckpointCoordinator.startSavepoint()
  -> PendingCheckpoint task ACK completion
  -> asynchronous checkpoint finalization
  -> PhysicalPlan.savepointFailed()
  -> SubPlan.stopPipelineWithCheckpointFallback()

Blocking findings

1. [P1] Mutating an enumerator-owned split causes duplicate data after Spark restore

Location: FakeSourceReader.java:128-129

The new batching logic modifies and requeues the original split instance:

split.setRowNum(remainingRowNum);
splits.addFirst(split);

In the ParallelSource path, ParallelEnumeratorContext.assignSplit() passes the same split object directly to the reader after FakeSourceSplitEnumerator has retained it in its assignedSplits HashSet.

FakeSourceSplit uses Lombok @Data, so rowNum participates in equals() and hashCode(). Changing rowNum therefore:

  1. modifies the enumerator-owned checkpoint state;
  2. changes the hash of an object already stored in a HashSet;
  3. prevents the restored enumerator from matching that split against the originally discovered split.

For example:

row.num = 10000
split.num = 1
parallelism = 1

First poll:
  emit 4096
  mutate shared split: rowNum 10000 -> 5904

Checkpoint:
  enumerator state = split(rowNum=5904)
  reader state     = split(rowNum=5904)

Restore:
  discovery recreates split(rowNum=10000)
  assignedSplits cannot remove it because 5904 != 10000
  reader receives restored(5904) + rediscovered(10000)

After restore, the reader can emit 15,904 rows instead of the expected 5,904 remaining rows. Including the first batch, a source configured for 10,000 rows can emit 20,000 rows.

Although this PR targets Zeta, FakeSourceReader is shared connector code, so the Spark regression is introduced by this diff.

Suggested fix:

  • Do not mutate the assigned split instance.
  • Requeue a new FakeSourceSplit containing the remaining count.
  • Prefer immutable fields for split identity/hash semantics.
  • Add a ParallelSource checkpoint/restore test that checkpoints after the first batch and verifies that only the remainder is emitted.

2. [P1] The new whole-job fallback can force-stop a successfully ACKed pipeline before finalization

Locations:

  • JobMaster.java:1275-1325
  • CheckpointCoordinator.java:884-905
  • SubPlan.java:533-546

The future returned by CheckpointCoordinator.startSavepoint() completes when all tasks have ACKed the pending checkpoint. Checkpoint persistence, completion notification, and the transition to SUSPEND happen later in a separate whenCompleteAsync callback.

The new failure fallback introduces the following race:

  1. Pipeline A receives all task ACKs, so its returned future completes successfully.
  2. Pipeline A has not yet completed completePendingCheckpoint().
  3. Pipeline B fails its savepoint.
  4. JobMaster invokes the new savepointFailed() fallback.
  5. stopPipelineWithCheckpointFallback() calls isCompletedPipeline() for pipeline A.
  6. Because pipeline A has not yet updated latestCompletedCheckpoint or its coordinator status, it is classified as incomplete.
  7. Pipeline A is canceled and force-stopped.
  8. Its delayed finalization callback can subsequently persist checkpoint state or attempt to transition the canceled coordinator to SUSPEND.

This can leave the following states inconsistent:

  • pipeline/task terminal state;
  • checkpoint-coordinator future;
  • coordinator status stored in IMap;
  • persisted checkpoint state.

This is distinct from the existing review comment. The previous finding concerned reverting the global job to RUNNING after partial success. This finding concerns the new stop-all fallback acting before a successful pipeline has finished asynchronous finalization.

The current multi-pipeline test only checks:

  • the global job reaches FAILED or CANCELED;
  • assigned slots are released.

It does not inspect the final state of each pipeline or checkpoint coordinator, so this race can pass the test.

Suggested fix:

  • Make the result consumed by JobMaster represent full checkpoint-coordinator finalization rather than task ACK collection alone; or
  • serialize the failure fallback after every pipeline coordinator has reached a stable final outcome.

Please add a test that:

  1. lets pipeline A complete all task ACKs;
  2. blocks pipeline A during persistence/finalization;
  3. fails pipeline B;
  4. verifies pipeline A is not prematurely force-stopped;
  5. verifies no checkpoint write or SUSPEND transition occurs after cancellation.

PR description consistency

The PR description currently says that savepoint failure reverts the job to RUNNING and that no forced cancellation is introduced.

The current head instead calls stopJob() and force-stops incomplete pipelines. The verification section also reports three regression tests, while the current test class contains four.

Please update the description and verification results to reflect the behavior of the actual head.

Verification

  • Reviewed the complete diff at 3a9067c9.
  • Checked all current PR comments and avoided repeating the existing lifecycle finding.
  • Traced the Zeta savepoint lifecycle and Spark ParallelSource restore path.
  • git diff --check: passed.
  • spotless:check: passed.

Conclusion

The source batching direction and deterministic whole-job fallback address the reported symptoms, but the current implementation introduces a restore-time data-duplication regression and a savepoint-finalization race.

These are data-correctness and lifecycle-consistency issues, so I recommend addressing them before merge.

davidzollo

This comment was marked as duplicate.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for the update. I re-reviewed the complete diff at 3a9067c9f1765279d2a9f0cfe493df3f9aa1371f. The previous partial-savepoint issue is addressed: the job no longer returns to RUNNING after only some pipelines stop. However, I independently traced the current source/restore and savepoint paths and agree with the three blockers already reported by @nzw921rx and @davidzollo.

  1. Mutating the enumerator-owned FakeSourceSplit can duplicate rows after restore. FakeSourceReader.java:121-130 mutates rowNum on the same object retained in FakeSourceSplitEnumerator.assignedSplits. Because Lombok @Data includes rowNum in equals/hashCode, the mutation also corrupts the HashSet identity used by discoverySplits() to remove already-assigned splits. A restored reader can therefore receive both its remaining split and a rediscovered full split. Please keep split identity immutable, requeue a separate progress object/split, and add a ParallelSource checkpoint/restore regression test.

  2. A task-ACKed pipeline can still be force-stopped before savepoint finalization. The future consumed by JobMaster.waitSavepointCompleted() completes at pending-checkpoint ACK completion, while persistence, latestCompletedCheckpoint, notification, and the coordinator's SUSPEND transition happen later in CheckpointCoordinator's asynchronous finalization. If another pipeline fails in that window, savepointFailed() can classify the ACKed pipeline as incomplete and cancel it before the delayed callback runs. Please make the aggregated result represent a stable finalized outcome, and add a deterministic test that blocks finalization while another pipeline fails.

  3. A synchronous triggerSavePoints() exception still leaves the job in DOING_SAVEPOINT. In JobMaster.java:1272-1290, physicalPlan.savepointJob() and checkpointManager.triggerSavePoints() run before the guarded asynchronous try/finally. If triggering throws synchronously, no fallback future is created and savepointFailed() is never invoked. Please put both synchronous and asynchronous failure paths under the same operation-scoped cleanup and test the synchronous-throw case.

These are data-correctness and lifecycle-consistency blockers, so the technical verdict remains blocking. The required Build check is also still in progress. Once these paths and their focused tests are fixed, I will be happy to re-review the next head.

@agarwalrahul2702

Copy link
Copy Markdown
Contributor Author

Pushed follow-up commit e8985e3c to address the review blockers from the 3a9067c9 head:

  1. FakeSource restore correctness:

    • FakeSourceReader no longer mutates the assigned split object when batching.
    • Requeued progress uses a new FakeSourceSplit.
    • FakeSourceSplit identity/hash now uses tableId + splitId, excluding mutable remaining-row progress.
    • Added a restore regression test that verifies assigned splits are not rediscovered when restored progress has a different remaining row count.
  2. Multi-pipeline savepoint finalization:

    • CheckpointManager#triggerSavePoints() now consumes CheckpointCoordinator#startSavepointAndWaitComplete().
    • The future observed by JobMaster completes after the checkpoint coordinator reaches its terminal state (SUSPEND for a successful savepoint), not just after pending-checkpoint ACK.
    • The multi-pipeline regression now asserts terminal pipeline states and verifies that the successful pipeline coordinator reaches SUSPEND.
  3. Synchronous trigger failure cleanup:

    • JobMaster#savePoint() now puts savepointJob(), triggerSavePoints(), aggregation, and the savepointFailed() fallback inside the same guarded operation, so synchronous and asynchronous failures both leave DOING_SAVEPOINT through the same cleanup path.

I also updated the PR description so it no longer describes the old “revert to RUNNING / no forced cancellation” behavior.

@SEZ9 SEZ9 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for working on this. I re-reviewed the latest head e8985e3cdb23 from scratch.

Findings

Issue 1: Possible public API change in seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/checkpoint/CheckpointManager.java

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/checkpoint/CheckpointManager.java
  • Why it matters: A public/protected signature appears to be removed or changed. Verify backward compatibility for downstream connectors.
  • Severity: High

Issue 2: Config/option changes without doc updates

  • Why it matters: Consider updating docs/example configs for the new/changed options.
  • Severity: Low

Review conclusion

Conclusion: can merge after the blocking items are fixed

1. Blocking items

  • Issue 1: Possible public API change in seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/checkpoint/CheckpointManager.java

2. Suggested (non-blocking) follow-ups

  • Issue 2: Config/option changes without doc updates

Nice progress overall — once the blocking points above are addressed this should be in good shape. Happy to discuss.

@agarwalrahul2702

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I pushed 9e45d1415 to address the blocking API compatibility item.

  • Restored the existing public CheckpointManager#triggerSavePoints() signature to return PassiveCompletableFuture<CompletedCheckpoint>[].
  • Added a separate additive method, triggerSavePointsAndWaitComplete(), for the JobMaster stop-with-savepoint path that needs finalized checkpoint-coordinator state.
  • Updated JobMaster to call the new method, so downstream callers of the existing public API keep the prior return type/behavior.

For the low-severity config/docs note: this PR does not add or change any user-facing config option. The only config-like addition is a test resource used by the regression test, so I left user docs/examples unchanged.

Verification after this change:

  • ./mvnw spotless:check passes.
  • ./mvnw spotless:apply passes.
  • git diff --check passes.

@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 working on this! I re-reviewed the complete current-head diff and the relevant runtime path. The direction makes sense, but I found the following blocker that needs to be resolved before merge:

  1. Blocker 1 — The refreshed head restores the public savepoint API, but the explicit rows path still emits the entire configured list while holding the checkpoint lock. FakeDataGenerator deliberately ignores rowNum for custom rows, and the new busy-source test covers only random rows. A large custom-row config can therefore preserve the same savepoint-barrier starvation. Please make custom-row emission resumable and bounded per poll, persist the remaining position without duplicates, and add a stop-with-savepoint regression for this branch.

The current Build is still pending; CI remains a separate gate. Historical/requested-changes review state is still visible and requires an appropriate maintainer action after the source blockers are cleared.

Please address these together on the next head; I’ll re-review the full updated diff once it is ready.

@agarwalrahul2702

Copy link
Copy Markdown
Contributor Author

Thanks for the current-head review. I pushed 35823e758 to address the remaining custom rows blocker.

  • FakeDataGenerator now has a bounded custom-row slice path instead of only the old emit-every-configured-row path.
  • FakeSourceReader now applies the same per-pollNext upper bound to explicit rows as to generated rows.
  • Custom-row progress is persisted in a newly requeued FakeSourceSplit: the first custom split starts at row index 0, continuation splits encode the next custom-row index to emit, and snapshotState() therefore records only the not-yet-emitted portion. The reader does not mutate the assigned split object.
  • Added a large custom-rows stop-with-savepoint regression config/test so this branch exercises the actual savepoint path.
  • Added a custom-row slice unit test for bounded row generation.

No user-facing config option was added or changed; the new config file is a test resource only, so docs/examples are unchanged.

Verification after this commit:

  • ./mvnw spotless:check passes.
  • ./mvnw spotless:apply passes.
  • git diff --check passes.

Targeted test execution is still blocked by local SeaTunnel build setup before the changed modules are reached: direct module runs fail resolving the local seatunnel-shade SNAPSHOT, and -am runs fail earlier in seatunnel-config-shade because generated/shaded Typesafe Config classes are unavailable in this cleaned workspace.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for the update. I re-reviewed the complete current-head diff and the affected runtime path from scratch. The direction is useful, but the following items still block merge:

  1. Blocker 1: The new custom-row savepoint regression fails on the exact head (seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/checkpoint/SavePointBusySourceTest.java:112-134) — In the required JDK 11/Linux unit lane, testStopWithSavepointCompletesWhileSourceEmitsLargeCustomRows times out after 120 seconds with CANCELED instead of SAVEPOINT_DONE; the companion multi-pipeline test also fails. The finite custom-row job can finish before the savepoint assertion is stable, so the fixture does not deterministically exercise the batching window. Please keep the job alive with a latch/gated sink or a deterministic continuing source, wait until the source is inside the intended mid-batch window, and rerun the affected unit lane.

The required Build is failing; its unit lane directly fails the new SavePointBusySourceTest scenarios, while several other E2E failures appear unrelated.

Thanks again for working through this — happy to re-review the next head.

Queue note: this head is diverged against dev (ahead_by=7, behind_by=21). I am recording that fact separately; it is not by itself a request to sync unless the CI guidance above explicitly says so.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks for your contribution for Apache SeaTunnel.

To facilitate focused communication among contributors, we’ve created a brand-new dedicated #contributors channel in official Slack workspace.
Slack workspace link: https://s.apache.org/seatunnel-slack

This channel is designed for technical discussions, feature design brainstorming, roadmap sync and direct communication with project core Contributors. Everyone who contributes code, docs, test cases or community ideas is warmly invited to join, share thoughts and collaborate together under The Apache Way. Welcome to join us😄

@davidzollo

Copy link
Copy Markdown
Contributor

Thanks for your contribution! This is a solid addition to the project, and your attention to detail really shows. Contributors like you are what keep this community moving forward. Feel free to keep the PRs coming — we're always glad to have you here!

Please ignore the following message if you have joined in the Slack~

To facilitate focused communication among contributors, we’ve created a brand-new dedicated #contributors channel in official Slack workspace.
Slack workspace link: https://s.apache.org/seatunnel-slack

This channel is designed for technical discussions, feature design brainstorming, roadmap sync and direct communication with project core Contributors. Everyone who contributes code, docs, test cases or community ideas is warmly invited to join, share thoughts and collaborate together under The Apache Way. Welcome to join 😄

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What Problem Does This PR Solve?

This PR fixes a real production hazard: a job stopped with stop-with-savepoint could get permanently stuck reporting DOING_SAVEPOINT and never reach a terminal state, so the client RPC either hangs or the job silently stops making progress. The root reproduction is a source connector (the test/demo fake-source connector used as the reproduction harness) that emits an entire large split in a single poll call while holding the checkpoint lock. Because barrier injection for that pipeline needs the very same lock, a large/slow split starves checkpoint/savepoint barrier injection for as long as the split takes to finish.

The fix has two complementary layers: the fake-source connector now caps rows emitted per poll call, releases the checkpoint lock between batches, and requeues remaining progress as an immutable, checkpoint-safe split; and the Zeta engine's savepoint path no longer declares success once tasks merely ACK the pending checkpoint — it now waits for every pipeline's checkpoint coordinator to reach a stable terminal state, and if any pipeline fails to reach that state, it deterministically drives the whole job out of DOING_SAVEPOINT via a new failure path that reuses the existing stop-with-checkpoint-fallback machinery instead of leaving it dangling.

1. Code Change Review

1.1 Core Logic Analysis

Before: the savepoint trigger method's returned futures resolved as soon as all tasks ACK'd the barrier — well before the coordinator persisted the checkpoint or flipped its own internal status to a terminal state. Critically, the old code took no corrective action if a pipeline's checkpoint failed (e.g. via a checkpoint-timeout handler): the aggregate future completed exceptionally, failing the client RPC, but the job itself was left exactly where the savepoint-start call put it — DOING_SAVEPOINT — forever, since nothing else in that path called stop. Combined with a source connector that can hold the checkpoint lock long enough to make the task itself effectively uninterruptible for the duration of a very large split, this reproduces a genuine indefinite hang.

After: the savepoint trigger now chains the ACK-future onto a wait for the checkpoint coordinator's own terminal-state future — the same future the pipeline-completion path already blocks on for normal (non-savepoint-failure) completion. The savepoint-wait method then requires every pipeline's terminal coordinator status to be the savepoint-suspend state; any other terminal status or exception marks the savepoint as failed. Both the savepoint-start call and the trigger call are now inside a try whose finally calls the new failure handler, so a synchronous throw is covered too — closing a gap flagged in an earlier review round.

The new failure handler is a thin, well-reasoned wrapper: if the job is still DOING_SAVEPOINT, it calls the pre-existing stop-job method, whose DOING_SAVEPOINT branch (unchanged by this PR) calls the stop-with-checkpoint-fallback path on every pipeline — the same fallback a manual stop during DOING_SAVEPOINT already used. That fallback checks whether each pipeline's checkpoint already completed; for a pipeline that already reached the suspend state, it force-finishes (idempotent — a no-op on an already-end-state task), and for everything else it cancels the coordinator and force-stops. This correctly reuses proven machinery rather than reimplementing pipeline shutdown, the right minimal-footprint choice.

Normal successful savepoint runtime flow (traced against the real code): job status flips RUNNING → DOING_SAVEPOINT; the savepoint trigger creates a pending checkpoint; once the task ACKs the barrier, an async completion path persists state and flips the coordinator's status to the suspend state; the savepoint-wait method blocks until all coordinators resolve; once all resolve to the suspend state, the savepoint is marked complete and the failure handler is not called; the client RPC resolves true; pipeline tasks reach their end state independently, driven by checkpoint-completion notification, and the job status finally settles to SAVEPOINT_DONE.

Savepoint-fails-mid-flight runtime flow, multi-pipeline (traced against the real code): one pipeline's checkpoint completes and resolves to the suspend state; a second pipeline's checkpoint never fully ACKs and the coordinator's own timeout scheduler (running independently of any busy task thread) fires, flipping that coordinator to a failed status; the savepoint-wait method's aggregate future resolves once both resolve — one suspend, one failed — so the savepoint is marked failed; the failure handler runs, calling stop-job, which force-finishes the already-completed pipeline (idempotent) and cancels/force-stops the failed one; both pipelines eventually reach an end status; the job settles at FAILED or CANCELED, never stuck at DOING_SAVEPOINT. This is exactly what the new multi-pipeline regression test asserts, and I traced the assertions against the real code paths above — they hold.

Master failover mid-DOING_SAVEPOINT (pre-existing, unchanged by this PR): the coordinator's restore-from-persisted-state constructor, not touched by this diff, is the other place a coordinator's future gets resolved. On master failover, a new coordinator is constructed per pipeline; if the persisted status is not an end state (i.e. the savepoint was still mid-flight when the old master died), the constructor just resets to running and returns — it does not complete the coordinator future, and nothing automatically re-triggers a savepoint or calls the new failure handler. Meanwhile the client-facing savepoint future is purely in-memory on the master that received the original RPC, so it cannot survive the failover regardless of this PR. This is a pre-existing architectural gap, not a regression introduced here — the old code had the identical limitation. This PR does not claim to fix master-failover-during-savepoint, and I found no evidence this PR makes that scenario worse. It is, however, a real residual risk worth a follow-up ticket.

1.2 Compatibility Impact

No checkpoint/savepoint binary format change — the relevant state classes are all untouched by this diff. A savepoint created by an older version restores correctly under the new engine code: the fake-source split's row-count field remains an int, and the new negative-sentinel decoding treats any non-negative value (the only value the old code could ever have produced) as "start from index 0," exactly the old semantics. No new field was added to the split; only its existing field's value space was extended with a sentinel encoding for partial custom-row progress.

Genuine restore-correctness fix, not just a hang fix: the fake source's split gained a narrowed equality restricted to its table/split identity. Before this change, the default equality included the mutable row-count field. On restore, split re-discovery avoids re-assigning splits that are already assigned/in-progress by removing already-assigned splits from the rediscovered set. If a restored split's checkpointed row-count differed from the freshly re-discovered split's row-count (which it always would, once partial-progress checkpointing exists), the old identity-inclusive equality would fail to match them, causing duplicate split assignment and duplicate row emission after restore. Restricting identity to table/split id fixes this, and it is directly exercised by a new dedicated test.

Public API preserved: the original trigger-savepoints method keeps its exact signature and return type; the new behavior is exposed only through an additive method. I confirmed via a repo-wide search that the original method now has zero callers anywhere in the repository — kept purely as a compatibility shim for any external caller, per an earlier review round's feedback. That's the right call for a method this public, though it's worth noting the method is presently dead code internally.

No option/config surface was added or renamed; no doc update is required under this repo's config-change documentation rule.

1.3 Performance / Side-Effect Analysis

The new savepoint-wait introduces a new blocking wait inside the async savepoint task. This wait is bounded: I traced two independent mechanisms that guarantee every coordinator future eventually resolves — the checkpoint-timeout scheduler task, which runs on the coordinator's own thread pool independent of any busy task thread; and the pipeline-end-state resolution path's branches, every one of which unconditionally resolves the coordinator's future once a pipeline's tasks all reach an end state. So the worst-case bound on the savepoint call is the checkpoint timeout, not "forever" — a meaningful, general improvement independent of the fake-source batching fix.

The row-batching cap in the fake source trades a small amount of extra lock acquire/release overhead for releasing the checkpoint lock periodically. For a test/demo connector this is a reasonable, low-risk trade-off; no production connector throughput is affected since this file is test-only. No new unbounded buffers, no new persistent threads, no change to thread pool sizing anywhere in the diff.

Concurrency review of concurrent stop-with-savepoint requests: the savepoint-start method already de-duplicates via an existing "return the in-flight future if one exists" guard, so two concurrent savepoint calls observe the same underlying futures and compute the same result; both may then independently call the new failure handler, which is safe because every downstream primitive it touches is idempotent by design. No new race introduced; safety is inherited from pre-existing idempotent primitives, but the composition holds up under inspection.

1.4 Error Handling and Logging

Issue 1: The custom-rows stop-with-savepoint regression test lacks a saturation margin and can race with natural completion

  • Location: the new test exercising the fake source's custom-rows path and its accompanying config resource.
  • Problem description: the config defines exactly 5,000 custom rows, and the new per-poll cap means the whole custom-row split finishes in just two poll batches. Unlike the sibling test for the large-random-split scenario (which explicitly sleeps to let the source saturate the pipeline mid-split before requesting the savepoint), this test requests the savepoint immediately after observing the job running, with no equivalent settle time. Given the very short natural completion window for an in-memory console sink, the test does not reliably land the savepoint request while the source is still mid-batch — it can just as easily race with the source's natural bounded completion.
  • Potential risk: this is exactly what was independently observed and reported in an earlier review round on a commit that remains this PR's latest substantive code commit: the test intermittently completing with CANCELED instead of SAVEPOINT_DONE in a required CI lane. I could not re-confirm this from the current CI run because that run's relevant unit-test job died earlier in the build on an unrelated out-of-memory failure before ever reaching this module's test phase — so current CI is inconclusive on this specific point, not passing. The code-level analysis stands independently and is sufficient to conclude the test is not deterministically exercising the code path it exists to regression-test.
  • Best improvement: give this test the same explicit saturation window as its sibling (a short sleep, a latch on the sink, or a gated/streaming custom-row source), and/or increase the custom-row count so the batching window is comfortably wider than the time needed to issue the savepoint RPC.
  • Severity: Medium-High (does not affect production correctness, but is a flaky/non-deterministic regression test for the exact scenario this PR is meant to lock down — per this repo's zero-tolerance policy on tests that can't reliably catch the regression they exist for)
  • Raised by another reviewer: Yes — flagged in an earlier review round against the commit that remains this PR's latest code commit, unaddressed.

Issue 2: Silent catch on the aggregate future in the savepoint-wait method

  • Location: the savepoint-wait method's join-and-catch block.
  • Problem description: the exception from the aggregate join is caught and silently discarded at that point — only a code comment explains the rationale, nothing is logged.
  • Potential risk: low in practice, since the same underlying exception is re-derived per-future in the loop immediately below and eventually rethrown. But it does make log-only diagnosis (without a debugger) slightly harder, since there's a silent gap between "aggregation observed a failure" and "here's which future failed."
  • Best improvement: add a debug-level log inside the catch block noting that per-pipeline resolution follows below.
  • Severity: Low
  • Raised by another reviewer: No

No other error-handling or logging issues found. Exception messages throughout the changed code carry sufficient context, and no sensitive information is logged anywhere in the diff.

2. Code Quality Assessment

2.1 Coding Standards

License headers present and correct on all new/modified files inspected. Javadoc is present and meaningful on all new public/protected methods, explaining why, not just what — consistent with this repo's stated commenting standard for lifecycle/checkpoint-adjacent code. No wildcard imports, no System.out.println, no special symbols in comments/logs.

Issue 3 (minor, non-blocking): the savepoint-wait method uses a fully-qualified JDK completable-future reference instead of a plain one, because the containing class already imports a custom completable-future subclass under the bare name. Verified this compiles and behaves correctly — array covariance and the subclass relationship make the aggregate call operate on genuine JDK completion state regardless of subclassing. Correct, just a minor readability wart worth a local import alias in a future cleanup. Severity: Low.

The original public trigger-savepoints method, kept unchanged for API compatibility per an earlier review round, now has no callers anywhere in the repository. This is the right trade-off for a public API, but worth a one-line class-Javadoc note that it's retained for compatibility, to prevent a future contributor from "cleaning it up" and reintroducing the API break flagged earlier. Severity: Low, informational.

2.2 Test Coverage and Test Stability

Coverage is genuinely strong and targeted at the actual hang mechanism, not just the surface symptom: a large-random-split test reproduces the original lock-starvation hang with an explicit saturation delay before the savepoint request and asserts the job reaches SAVEPOINT_DONE with slots released; a plain-cancel test confirms cancel still works while the source is busy, a good regression guard against over-fixing; single- and multi-pipeline savepoint-failure tests directly exercise the exact failure runtime flow analyzed above, asserting both global job status and per-pipeline terminal states plus slot release; a dedicated enumerator test covers the restore-correctness fix; and a unit test covers the new bounded custom-row slicing directly.

Flaky-pattern check (mandatory, since test code changed): Risk present. The custom-rows savepoint test is timing-dependent without an adequate saturation margin, as detailed in Issue 1 — it is the one test in this PR's new suite I cannot certify as deterministic. All other new/changed tests are event-driven (condition-based polling on persisted status, not sleep-based polling with a fixed assumption about job progress) or use a config that deterministically forces a timeout, the right pattern, and I don't see any weakening of existing test strictness anywhere in the diff.

2.3 Documentation Updates

No docs updates were made, and none are required: no option/config surface was added, changed, or renamed; the new config files are test resources only, not documented examples.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix, not a workaround. The engine-level change correctly identifies that the previous design conflated "ACK-complete" with "savepoint-complete," and fixes that at its source by waiting for the coordinator's own terminal-state future, which the codebase already used for the equivalent non-savepoint-failure pipeline-completion path. The failure-recovery path is a minimal, one-method addition that deliberately reuses the existing stop-job DOING_SAVEPOINT fallback rather than inventing new pipeline-shutdown logic. The fake-source batching fix addresses the actual lock-starvation root cause with a resumable, checkpoint-safe design (requeued split carries remaining progress, not just "restart from zero"), rather than papering over it with a longer timeout.

3.2 Maintainability

High. The new methods are small, single-purpose, and well-commented on why. The public-API-compatibility shim (old method kept, new method added) is a maintainability-conscious choice that avoids breaking downstream callers while still fixing the internal behavior.

3.3 Extensibility

The new savepoint-and-wait pattern generalizes cleanly: any future caller that needs "wait for a fully-finalized checkpoint coordinator state" (not just an ACK) now has a reusable building block, rather than every caller having to reimplement the ACK-vs-finalization distinction this bug turned on.

3.4 Historical-Version Compatibility

Covered in depth above. Restoring an in-flight (or completed) savepoint created by an older version works correctly under the new code — no format change, and the split-progress sentinel is backward-interpretable. The public API surface is unchanged. No option/config compatibility concern exists. The one open architectural question — master failover mid-DOING_SAVEPOINT — is a pre-existing gap this PR neither fixes nor worsens, explicitly out of this PR's stated scope.

4. Issue Summary

# Issue Location Severity Blocking
1 Custom-row regression test lacks a saturation margin; can race with natural job completion and non-deterministically observe CANCELED instead of SAVEPOINT_DONE New custom-rows savepoint test and its config resource Medium-High Yes
2 Empty catch on the aggregate future with no log statement Savepoint-wait method Low No
3 Fully-qualified JDK future reference instead of an import alias, due to a pre-existing custom future subclass shadowing the name Savepoint-wait method Low No
4 The checkpoint-lock-starvation pattern this PR fixes for the test connector is a general connector-authoring hazard; not audited/documented for production connectors here Informational Informational No
5 Master failover mid-DOING_SAVEPOINT is not covered by this fix; the client-visible request cannot survive failover, and the restored coordinator resets to running without re-triggering the savepoint or the new fallback. Pre-existing gap, not a new regression Informational Informational No

5. Merge Recommendation

Conclusion: Ready to merge after fixes

Blockers (non-CI):

  • Issue 1 — the custom-rows stop-with-savepoint regression test is not deterministic and, per an earlier still-unaddressed finding against this PR's latest code commit, has been observed to fail exactly this way in CI. A state-machine fix of this severity needs its regression suite to reliably catch what it claims to catch; this must be fixed (or the test made deterministic) before merge.

Non-blocking follow-ups: Issues 2-5 above (logging quality, a style nit, and two informational/architectural notes worth tracking separately — connector-authoring guidance for checkpoint-lock hygiene, and a follow-up issue for master-failover-during-savepoint).

Overall assessment: the core engine-level fix (waiting for the suspend state instead of ACK, and deterministically driving a failed savepoint out of DOING_SAVEPOINT via the existing stop-with-checkpoint-fallback machinery) is architecturally sound, minimal, correctly reuses proven primitives, preserves the public API, and does not change the checkpoint/savepoint binary format or break restore of savepoints created by older versions. The fake-source split-batching fix is a genuine root-cause fix, and the accompanying equality restriction on the fake source's split fixes a real duplicate-row-on-restore bug that an earlier review round correctly caught and this head correctly addresses. I independently traced the normal, partial-failure, and concurrent-request runtime paths against the real source and found the design sound; I could not fully verify the failover path is newly safe, but I also found no evidence it is newly broken — it inherits a pre-existing limitation outside this PR's stated scope. The one thing standing between this PR and merge is closing the gap in its own regression coverage (Issue 1), which is squarely inside the PR's stated scope and has already been flagged once without a follow-up fix.

@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 pushing the update! I re-reviewed the latest head (83191ada) from scratch against my previous round.

What Problem Does This PR Solve?

User pain point: calling stop-with-savepoint on a Zeta job whose source is busy (e.g. mid-split, holding the checkpoint lock) could hang forever — the client-facing future never completed, and if the savepoint itself failed, the job got stuck in DOING_SAVEPOINT with no way out except a hard cancel.

Fix approach: the coordinator now waits for the pipeline's own terminal-state future (the same primitive already used for normal completion) instead of resolving on checkpoint ACK; a new failure path deterministically drives a failed savepoint out of DOING_SAVEPOINT by reusing the existing stop-with-checkpoint-fallback machinery; and the test-only FakeSource connector gained bounded row-batching so it periodically releases the checkpoint lock instead of holding it for an entire large split.

One-sentence summary: stop-with-savepoint on a busy job now reliably completes or reliably fails instead of hanging indefinitely.

1. Code Change Review

1.1 Core Logic Analysis — carried forward from my last review, unchanged conclusions

Everything I verified last round (the engine-level wait-for-suspend-state fix, the new failure-recovery path reusing existing stop machinery, the FakeSource split-batching root-cause fix, and the split-equality restriction that also fixes a real duplicate-row-on-restore bug) is untouched by this commit and still holds. I re-traced the normal, partial-failure, and concurrent-savepoint-request paths against the current head and found no regression introduced by this round's changes.

What changed since my last review

My last review's sole blocker (Issue 1) was: testStopWithSavepointCompletesWhileSourceEmitsLargeCustomRows used a config with exactly 5,000 rows and no settle window, so the whole split could finish in two poll batches — the savepoint request could race the source's own natural completion and non-deterministically observe CANCELED instead of SAVEPOINT_DONE.

This commit fixes it. The config was replaced with split.num = 64, split.read-interval = 3000 (stream_fakesource_custom_rows_busy_to_console_savepoint.conf), and the test now does:

// Let the custom rows source enter its paced split loop before requesting the savepoint.
// The config uses many small splits with a read interval, so this settle window avoids
// racing the savepoint request against natural job completion.
Thread.sleep(2000L);

PassiveCompletableFuture<Void> savepointFuture =
        server.getCoordinatorService().savePoint(jobId);

This mirrors the sibling testStopWithSavepointCompletesWhileSourceEmitsLargeSplit test's pattern exactly — 64 splits at a 3s read interval gives a multi-second natural completion window, comfortably wider than the 2s settle sleep plus the time to issue the savepoint RPC. I don't see a way this can still race natural completion; this is a correctly-fixed deterministic regression test now, not a rewrite that just moves the flakiness elsewhere.

Key Findings

  • The normal execution path (a running job on a busy source, client calls stop-with-savepoint) directly reaches every line changed in this diff — this is not a narrow race-window-only fix, it's the primary path for the feature it's fixing.
  • The fix is a precise root-cause fix (waiting for the correct terminal-state future, using an existing primitive) plus a genuine connector-level fix (bounded batching), not a timeout-widening workaround.
  • My one previously-open blocker (the non-deterministic regression test) is now fixed and verified deterministic against the current source and config.
  • No new issues found in this round's diff itself.

1.2 Compatibility Impact

Fully compatible. No checkpoint/savepoint binary format change, no option/config surface added or renamed, and the original public trigger-savepoints method signature is preserved unchanged as a compatibility shim. Savepoints created by older versions restore correctly under the new code (confirmed in my last round by tracing the split's row-count sentinel decoding, which treats any old non-negative value as "start from index 0" — unchanged this round).

1.3 Performance / Side-Effect Analysis

Unchanged from last round: the new savepoint-wait is bounded (checkpoint-timeout scheduler and the pipeline-end-state resolution path both guarantee eventual resolution), the row-batching cap only affects the test-only FakeSource connector (no production connector throughput impact), and concurrent stop-with-savepoint requests remain safe via the existing in-flight-future de-duplication guard.

1.4 Error Handling and Logging

No changes in this commit touch the error-handling/logging surface I reviewed last round. My two previously-flagged Low-severity, non-blocking items (silent catch with no debug log on the aggregate future join; a fully-qualified JDK future reference due to a local name shadow) remain open but were never blockers and don't need to hold up this merge.

CI Diagnosis

The Build check on the current head is failing, but I traced it to the actual fork run (agarwalrahul2702/seatunnel run 31235845087, job unit-test (8, ubuntu-latest)) and it is not related to this PR's diff: the shard dies with java.lang.OutOfMemoryError: GC overhead limit exceeded inside seatunnel-ci-tools module tests (SpotlessImportReplacementTest, SerialVersionUIDCheckerTest, etc. — generic repo-wide tooling checks), before the run ever reaches the Zeta engine module where this PR's actual changes and new tests live. This is a CI-runner resource flake, not a defect this PR introduced — I'd recommend simply re-running the failed job rather than changing anything in the PR.

2. Code Quality Assessment

2.1 Coding Standards

Unchanged and still good: license headers present, Javadoc present and meaningful on new public/protected methods, no wildcard imports, no System.out.println, no special symbols in logs/comments.

2.2 Test Coverage and Test Stability

Stability rating: Stable (upgraded from "Risk present" last round). The one test I flagged as timing-risky is now deterministic per the analysis above — it uses the same saturation-window pattern as its already-stable sibling test, backed by a config change that widens the natural-completion window well past the settle delay. All other new/changed tests remain event-driven (await().untilAsserted(...) on persisted status) rather than sleep-and-hope, and I see no weakening of any existing test's strictness in this diff.

2.3 Documentation Updates

None required — no option/config surface was added, changed, or renamed.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix — reuses existing, already-proven primitives (the pipeline terminal-state future, the existing stop-with-checkpoint fallback) rather than inventing new machinery or widening a timeout.

3.2 Maintainability

High — small, single-purpose, well-commented additions; the compatibility shim is a deliberate, documented trade-off rather than an oversight.

3.3 Extensibility

The new "wait for fully-finalized coordinator state, not just ACK" pattern is a reusable building block for any future caller with the same requirement.

3.4 Historical-Version Compatibility

Fully compatible — covered above. No format, API, or config compatibility concerns.

4. Issue Summary

# Issue Location Severity Blocking
1 (carryover, now fixed) Custom-row regression test lacked a saturation margin — fixed this round via Thread.sleep(2000L) + redesigned 64-split/3s-interval config testStopWithSavepointCompletesWhileSourceEmitsLargeCustomRows + its .conf resource — No (resolved)
2 Empty catch on the aggregate future with no log statement savepoint-wait method Low No
3 Fully-qualified JDK future reference instead of an import alias savepoint-wait method Low No
4 Master failover mid-DOING_SAVEPOINT is not covered by this fix (pre-existing gap, not a regression) Informational Informational No

5. Merge Recommendation

Conclusion: Ready to merge

Blockers (non-CI): none remaining. My sole blocker from the last round (the non-deterministic regression test) is fixed and verified.

Recommended fixes — non-blocking: Issues 2–3 above (a missing debug log, a style nit) are worth a follow-up but don't need to hold up this merge. Issue 4 is worth its own tracking ticket, out of this PR's scope.

Overall assessment: the core fix is architecturally sound, minimal, and correctly reuses existing primitives; I traced the normal, failure, and concurrent-request paths against the current source and found no issues. The only thing that was standing between this PR and merge — the regression test's own determinism — is now fixed. The current Build failure is a CI-infra OOM flake in an unrelated module (seatunnel-ci-tools) that never reaches this PR's actual test suite; I'd suggest re-running that job rather than changing anything here.

@agarwalrahul2702

Copy link
Copy Markdown
Contributor Author

Pushed ac936f844 for the latest CI/review feedback.

What changed:

  • Removed the newly-added retry-success integration fixture/test that failed in CI by racing SAVEPOINT_DONE against the busy-source checkpoint timeout.
  • Deleted stream_fakesource_retryable_to_console_savepoint.conf, since that fixture existed only for the unstable retry assertion.
  • Kept SavePointBusySourceTest.testSavepointStartPreconditionFailureKeepsJobRunning focused on the deterministic requirement from [Bug] [Zeta] stop-job with savepoint hangs in DOING_SAVEPOINT #11473: an early savepoint precondition failure must fail the request but leave the job RUNNING, with cleanup verified by explicit cancel.
  • Kept the deterministic JobMasterTest coverage for multi-pipeline classification and mixed-failure reporting.
  • Synced the branch with current upstream/dev (4a65e98ad).

This also addresses the two non-blocking notes from the latest review that were already present on the prior head:

  • isSavepointStartPreconditionException() has a dedicated comment explaining the pre-checkpoint boundary.
  • mixed failures prefer a non-precondition exception when surfacing the failure to the caller.

Local validation on the pushed head:

  • ./mvnw -pl seatunnel-engine/seatunnel-engine-server spotless:apply passes.
  • git diff --check passes.
  • ./mvnw -pl seatunnel-ci-tools -Dtest=ImportClassCheckTest#javaUtilCompletableFutureCheck test passes.

I also re-attempted ./mvnw -pl seatunnel-engine/seatunnel-engine-server -Dtest=JobMasterTest test; this local workspace still fails during engine-server compile before tests because direct module resolution uses stale/missing intra-repo SNAPSHOT classes (RestoreMode, API metadata/signal/error classes, metric constants). The new fork Build is queued here: https://github.com/agarwalrahul2702/seatunnel/actions/runs/32100814768

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What Problem Does This PR Solve?

User pain point: calling stop-with-savepoint on a Zeta job whose source is busy (mid-split, holding the checkpoint lock) could hang forever in DOING_SAVEPOINT, and a mixed-outcome multi-pipeline savepoint attempt could be misclassified, either wrongly restoring RUNNING when a pipeline genuinely failed or leaving the job stuck.

This round's three new commits since my last review (eb8fa4cb2 merge, 8e4364915 "Stabilize savepoint retry regression", 2232478f1 "Remove unstable savepoint retry fixture", plus the trailing ac936f844 merge that is the current head) are a direct response to the single High-severity blocker I raised last round: SavePointBusySourceTest.testSavepointStartPreconditionFailureKeepsJobRunning's retry-succeeds assertion was racing a real 60-second checkpoint timeout on CI and failing for real. I re-verified this round's own fork CI run end to end. The flakiness is genuinely fixed and CI-proven green this time — but the way it was fixed quietly deleted the only test that proved "a retried savepoint after readiness actually completes," and that deletion is a new, real regression in test coverage that must be closed before merge.

1. Code Change Review

1.1 Core Logic Analysis

Scope confirmed: the only production-code file this round's commits touch is JobMaster.java (+22/-3, confirmed via git diff 93a7a6672..ac936f844 -- '.../src/main/*' — every other file in that diff traces to the routine merge of upstream/dev, e.g. the unrelated Dead-Letter-Queue feature #10306). Everything else I reviewed last round (multi-pipeline exception classification via allMatch, CHECKPOINT_COORDINATOR_SHUTDOWN recognition, SavepointCompletionResult) is untouched and stands as previously verified.

Before (head 93a7a6672, what I flagged as non-blocking Issue 3 last round):

if (savepointCompletionResult.getFirstException().isPresent()) {
    throw new SeaTunnelEngineException(savepointCompletionResult.getFirstException().get());
}

In a mixed-failure scenario (one pipeline hits the benign TASK_NOT_ALL_READY_WHEN_SAVEPOINT, another genuinely fails with e.g. CHECKPOINT_EXPIRED), the caller-facing exception was whichever pipeline's future happened to be first in iteration order — potentially reporting the benign "not ready" reason to an operator even though the job actually stopped because of a real failure elsewhere.

After (JobMaster.java:1299-1305, 1329-1338):

Optional<Exception> failureException = getSavepointFailureException(savepointCompletionResult);
if (failureException.isPresent()) {
    throw new SeaTunnelEngineException(failureException.get());
}
...
private Optional<Exception> getSavepointFailureException(
        SavepointCompletionResult savepointCompletionResult) {
    Optional<Exception> nonPreconditionFailure =
            savepointCompletionResult.getExceptions().stream()
                    .filter(exception -> !isSavepointStartPreconditionException(exception))
                    .findFirst();
    return nonPreconditionFailure.isPresent()
            ? nonPreconditionFailure
            : savepointCompletionResult.getFirstException();
}

This now prefers surfacing a genuine (non-precondition) failure over a benign precondition failure when both are present, falling back to the first exception only when every failure is a precondition failure. This is correct, minimal, and matches exactly what I asked for. It is proven by a new deterministic unit test, JobMasterTest#testSavepointFailureExceptionPrefersNonPreconditionFailure (constructs one TASK_NOT_ALL_READY_WHEN_SAVEPOINT + one CHECKPOINT_EXPIRED failure via ReflectionUtils/synthetic futures, asserts the surfaced exception's root CheckpointCloseReason is CHECKPOINT_EXPIRED) — no timing dependency, no shared state.

Also added: a Javadoc block on isSavepointStartPreconditionException() (JobMaster.java:1414-1417) explaining it recognizes "checkpoint coordinator failures that happen before a savepoint checkpoint is created" — this closes the one remaining documentation gap from my last round's Issue 2.

Full runtime path, this exact scenario (busy source mid-split, savepoint requested before checkpoint coordinators are ready):

Client: stop-job --with-savepoint
  -> CoordinatorServiceImpl.savePoint(jobId)
  -> JobMaster.savePoint()
       physicalPlan.savepointJob()                          [state: RUNNING -> DOING_SAVEPOINT]
       checkpointManager.triggerSavePoints()
       CheckpointCoordinator.startSavepoint()
         -> not all tasks ACKed readiness
         -> PendingCheckpoint aborted, future completed exceptionally
              with CheckpointException(TASK_NOT_ALL_READY_WHEN_SAVEPOINT)
       waitSavepointCompleted(passiveCompletableFutures)
         -> collects ALL pipeline exceptions into SavepointCompletionResult.exceptions (fixed last round)
       getSavepointFailureException(result)                 [NEW this round]
         -> no non-precondition failure present -> falls back to first exception
         -> thrown to caller as SeaTunnelEngineException wrapping TASK_NOT_ALL_READY_WHEN_SAVEPOINT
       isSavepointStartPreconditionFailure(result)
         -> allMatch(isSavepointStartPreconditionException) == true
         -> restoreRunningAfterSavepointStartFailure()       [state: DOING_SAVEPOINT -> RUNNING, no hang]
Caller: sees ExecutionException, job status == RUNNING -> free to retry savePoint() later
  -> once checkpoint coordinators report ready, a subsequent savePoint() call
     follows the normal DOING_SAVEPOINT -> SAVEPOINT_DONE path
     (this final "retry actually succeeds" leg is the part that lost its test coverage this round — see 2.2)

The old-hang / new-unblocked contrast for the primary #11473 scenario (source saturating the pipeline mid-split, savepoint requested once coordinators ARE ready) is unchanged from prior rounds and remains covered by testStopWithSavepointCompletesWhileSourceEmitsLargeSplit — traced and still green this round (see 2.2).

New finding this round: the CI-blocking flakiness is genuinely fixed — verified against this exact head's real CI run

I checked the fork's CI run for the current head (agarwalrahul2702/seatunnel run 32100814768, head ac936f844) directly, not a historical/superseded run:

  • unit-test (8, ubuntu-latest): SUCCESS. Log confirms JobMasterTest: Tests run: 10, Failures: 0, Errors: 0 and SavePointBusySourceTest: Tests run: 6, Failures: 0, Errors: 0, Time elapsed: 17.678 s.
  • unit-test (11, ubuntu-latest), unit-test (8/11, windows-latest): all SUCCESS.

The change that made this pass: SavePointBusySourceTest.testSavepointStartPreconditionFailureKeepsJobRunning (SavePointBusySourceTest.java:229-278) no longer attempts to prove a retried savepoint reaches SAVEPOINT_DONE against the busy 100M-row/60s-timeout config. It now stops at proving the not-ready failure keeps the job RUNNING, then calls cancelJob() and asserts CANCELED + zero assigned slots for cleanup. This is exactly the deterministic, timing-safe shape I asked for last round — the retry-timing race is gone, and it is proven gone by a real, non-cancelled CI run.

New finding this round (blocking): the retry-succeeds guarantee lost all test coverage, not just its flaky proof

Tracing the two commits in order:

  • 8e4364915 ("Stabilize savepoint retry regression") did this correctly at first: it split the flaky assertion out of the busy-config test (as above) and added a brand-new, properly decoupled test, testSavepointStartPreconditionFailureCanBeRetriedAfterReady, against a genuinely lightweight config (stream_fakesource_retryable_to_console_savepoint.conf: row.num = 100000, split.num = 100, split.read-interval = 1, checkpoint.interval = 1000, checkpoint.timeout = 30000 — nothing like the busy config's 100M rows / single split / 60s timeout that caused the original race). This is precisely "Option A" I suggested last round.
  • 2232478f1 ("Remove unstable savepoint retry fixture"), pushed ~78 minutes later, deleted that entire test and its conf file, with no replacement. The author's own commit message says it was removed because it "failed in CI by racing SAVEPOINT_DONE against the busy-source checkpoint timeout" — but I checked the actual CI run for the intermediate head 8e4364915 (fork run 32095999604): its conclusion is cancelled, not failure — it never got a chance to report a pass/fail result, it was superseded by the next push before it finished. So there is no CI evidence the new lightweight test was ever actually flaky; it was removed pre-emptively.

Net effect on this exact head: grepping the whole PR for SAVEPOINT_DONE in test code turns up only the unrelated pre-existing testStopWithSavepointCompletesWhileSourceEmitsLargeSplit (primary hang scenario) and an unrelated pre-existing testCloseIdleTask in JobMasterTest. No test anywhere in this PR proves that a caller who retries savePoint() after a TASK_NOT_ALL_READY_WHEN_SAVEPOINT failure, once checkpoint coordinators become ready, actually reaches SAVEPOINT_DONE. That is the second half of this PR's own stated contract — the in-code comment right above the assertion explicitly says "The job must stay RUNNING so the caller can retry after the checkpoint coordinators report all tasks ready" — and the "retry" half of that promise is now completely unverified by automated tests. This is a genuine reduction in regression-detection capability compared to what existed in the PR's own test suite as of my last review (where the retry-succeeds assertion, while racy, was present and had been reviewed/passing in earlier rounds before this round's flakiness surfaced), so per this repository's zero-tolerance rule on weakening test coverage, this must be treated as a blocker — not because the underlying savePoint() retry code path was itself touched this round (it wasn't), but because the very claim this PR makes about retryability is now unproven.

1.2 Compatibility Impact

Fully compatible, unchanged conclusion from last round. No checkpoint/savepoint binary format change, no Option/config surface touched. This round's sole production change (getSavepointFailureException()) is pure internal control-flow for selecting which already-collected exception to surface to the caller — no public signature changed, no serialization format touched. CheckpointCoordinator.java and CheckpointManager.java are unchanged since my last review (confirmed via git diff 93a7a6672..HEAD --stat).

1.3 Performance / Side-Effect Analysis

No new blocking waits, threads, retries, or buffers. getSavepointFailureException() is a single bounded stream scan over the already-materialized exception list (bounded by pipeline count) — negligible. No busy-loops, no new timeouts introduced. No concerns here.

1.4 Error Handling and Logging

Issue 1 (new this round, blocking): the retry-succeeds behavior for a TASK_NOT_ALL_READY_WHEN_SAVEPOINT precondition failure has zero test coverage on this head, despite a correct, properly-decoupled test for exactly this having been written and then deleted within the same round without CI evidence it was actually broken. Location: SavePointBusySourceTest.java (deleted test testSavepointStartPreconditionFailureCanBeRetriedAfterReady, deleted conf stream_fakesource_retryable_to_console_savepoint.conf). Severity: High. Blocking. Raised by another reviewer: No.

Issue 2 (resolved this round): my prior round's Issue 1 (CI-confirmed timing race in the busy-config retry assertion) is fixed and CI-proven — SavePointBusySourceTest and JobMasterTest both pass cleanly on this exact head's own CI run (see 1.1/2.2 for the run IDs and test counts).

Issue 3 (resolved this round): my prior round's Issue 2 (missing Javadoc on isSavepointStartPreconditionException()) is fixed — see JobMaster.java:1414-1417.

Issue 4 (resolved this round): my prior round's Issue 3 (getFirstException() could surface a misleading benign exception in a mixed-failure case) is fixed via getSavepointFailureException(), with dedicated deterministic unit coverage.

No sensitive information logged; no swallowed exceptions.

2. Code Quality Assessment

2.1 Coding Standards

Clean. No wildcard imports, no System.out.println, no special symbols in logs/comments, license headers unaffected (existing files). The new Javadoc on isSavepointStartPreconditionException() closes the one remaining style gap from last round.

2.2 Test Coverage and Test Stability

Is there a test that reproduces the original #11473 hang and proves it no longer hangs with a bounded-time assertion? Yes, unchanged from prior rounds: SavePointBusySourceTest#testStopWithSavepointCompletesWhileSourceEmitsLargeSplit starts the busy 100M-row/single-split job, lets it saturate the pipeline for 5 seconds, requests a savepoint, and asserts via await().atMost(120, TimeUnit.SECONDS) that the job reaches DOING_SAVEPOINT then SAVEPOINT_DONE — a bounded-time assertion, not an indefinite wait. This test is untouched by this round's commits and passed on the exact CI run I checked.

Flaky-pattern check (mandatory, since test code changed this round):

  • JobMasterTest's new test (testSavepointFailureExceptionPrefersNonPreconditionFailure): Stable. Deterministic, reflection-based, synthetic futures, no timing dependency. Confirmed green: Tests run: 10, Failures: 0, Errors: 0.
  • SavePointBusySourceTest.testSavepointStartPreconditionFailureKeepsJobRunning: Now stable, confirmed by real CI (not a historical run) — Tests run: 6, Failures: 0, Errors: 0, 17.678 s. The prior round's High-severity blocker is resolved and proven.
  • But: coverage regression. As detailed in Issue 1 (1.4), the retry-succeeds half of the original scenario is no longer tested by anything. This is a High-severity, blocking gap — see 1.1 for the full trace of how it disappeared.

2.3 Documentation Updates

None required — no Option/config surface changed.

3. Architectural Soundness

3.1 Elegance of the Solution

The exception-selection fix (getSavepointFailureException) is small, correct, and well-targeted. The test-stabilization approach (decoupling the flaky assertion from the busy-source config) was the right call and is now proven working — the regret is that the decoupled replacement test was deleted along with the flaky one, instead of being kept.

3.2 Maintainability

getSavepointFailureException() reads clearly and is well-named. The now-missing retry-succeeds test means a future regression in the retry path (e.g., if some future change to JobMaster/CheckpointCoordinator state cleanup accidentally left stale state that broke a subsequent savePoint() call) would go undetected by this PR's own test suite.

3.3 Extensibility

Unchanged from prior rounds' assessment.

3.4 Historical-Version Compatibility

Fully compatible, no format/API/config break, re-confirmed for this round's sole changed production file.

4. Issue Summary

# Issue Location Severity Blocking Raised by another reviewer
1 (new this round) Retry-succeeds behavior (not-ready failure -> job stays RUNNING -> retried savePoint() reaches SAVEPOINT_DONE) has zero test coverage; a correct, properly-decoupled test for this was written and then deleted in the same round without CI evidence it was actually flaky (its own CI run was cancelled/superseded, not failed) SavePointBusySourceTest.java (deleted testSavepointStartPreconditionFailureCanBeRetriedAfterReady + deleted stream_fakesource_retryable_to_console_savepoint.conf) High Yes No
2 (resolved this round) testSavepointStartPreconditionFailureKeepsJobRunning's retry-succeeds assertion raced the busy-source config's own 60s checkpoint timeout — fixed by decoupling; CI-confirmed green on this exact head (unit-test (8, ubuntu-latest), run 32100814768) SavePointBusySourceTest.java:229-278 — No (resolved)
3 (resolved this round) isSavepointStartPreconditionException() lacked its own Javadoc — fixed JobMaster.java:1414-1417 — No (resolved)
4 (resolved this round) getFirstException() surfaced only the first exception in iteration order, potentially misreporting a mixed-failure cause — fixed via getSavepointFailureException(), unit-tested JobMaster.java:1299-1305, 1329-1338 — No (resolved)
5 (carryover, resolved) Multi-pipeline classification only inspected the first exception found JobMaster.java:1342-1410 — No (resolved)
6 (carryover, resolved) CHECKPOINT_COORDINATOR_SHUTDOWN not recognized as a benign precondition JobMaster.java — No (resolved)
7 (carryover, resolved) Earlier-round findings (import-rule violation, restore-time duplicate rows, partial multi-pipeline savepoint failure, non-deterministic custom-rows test, CheckpointManager API preservation, nzw921rx/davidzollo's FakeSourceReader split-mutation and premature-force-stop findings) various — No (resolved)
8 (carryover, unchanged) Master failover mid-DOING_SAVEPOINT not covered by this fix (pre-existing gap, not a regression) Informational Informational No —

5. Merge Recommendation

Conclusion: Not ready to merge — one new, narrowly-scoped test-coverage regression remains

Blockers — must be fixed:

  1. Issue 1 — restore automated coverage that a retried savePoint() call succeeds once checkpoint coordinators become ready. The simplest, lowest-risk path: re-apply the test and conf file that commit 8e4364915 already wrote (testSavepointStartPreconditionFailureCanBeRetriedAfterReady + stream_fakesource_retryable_to_console_savepoint.conf) without re-applying the later deletion — that test was never actually observed to fail on real CI (its only CI run was cancelled/superseded, not failed), and its lightweight config (100K rows, 100 splits, 30s timeout) is nothing like the checkpoint-hostile busy config that caused the original race. Push it and get a real, completed (not cancelled) green CI run before merge.

Recommended fixes — none outstanding. All prior non-blocking asks (Javadoc on isSavepointStartPreconditionException(), preferring a non-precondition exception when surfacing mixed failures to the caller) are resolved this round.

Reacting to the existing CHANGES_REQUESTED decision and other reviewers: this remains the right call for one narrow reason. The classification bug and the CI-blocking test flakiness that I, @nzw921rx, and @davidzollo collectively spent many rounds chasing down are now genuinely fixed, unit/integration-tested, and CI-green on this exact head — real, verifiable progress, and the production-code fix itself is solid. @SEZ9's outstanding review references a CheckpointManager API-change concern against an older head (e8985e3cdb23); that was already resolved via commit 9e45d1415 in an earlier round and remains unaffected by this round's diff, so nothing new to reconcile there. The gate that remains is narrowly the deleted retry-success test, not the production logic.

CI diagnosis: the apache-side Build check mirrors the fork's real run (32100814768) and is FAILURE, but I traced both failing jobs and neither is caused by this PR's diff:

  • all-connectors-it-6 (11, ubuntu-latest): PostgresCDCIT.testPostgresCdcSnapshotOnlyAndCommittedOffsetStartupModes — ConditionTimeout in the unrelated Postgres CDC connector E2E module, not touched by this diff.
  • paimon-connector-it (11, ubuntu-latest): PaimonSinkCDCIT.testSinkWithIncompatibleSchema — ConditionTimeout in the unrelated Paimon connector E2E module, not touched by this diff.
  • All unit-test jobs (8/11 x ubuntu/windows) are SUCCESS, including the Zeta JobMasterTest (10/10) and SavePointBusySourceTest (6/6) this PR's own diff is responsible for.

So while these two connector-IT failures are unrelated infra/env flakes worth a rerun, they are not blockers from this review's perspective; the one blocker is the missing retry-success test coverage described above.

Overall assessment: this round closes out the CI-blocking flakiness cleanly and with real evidence, and both of last round's non-blocking documentation/error-reporting asks are done. The production JobMaster.java change is minimal, correct, and unit-proven. The only remaining gate is restoring the retry-success test that was written correctly and then removed without cause — a small, mechanical fix. Once that's back in and shows a real (non-cancelled) green CI run, I would expect this to be ready to merge.

@agarwalrahul2702

Copy link
Copy Markdown
Contributor Author

Pushed 8f5d15cd3 for the latest review blocker and the latest failed Build run.

What changed:

  • Restored automated coverage for the retry contract requested in the latest review: SavePointBusySourceTest#testSavepointStartPreconditionFailureCanBeRetriedAfterReady now verifies that a savepoint rejected before coordinator readiness leaves the job RUNNING, and that a later retry after readiness reaches SAVEPOINT_DONE.
  • Re-added the retry fixture as stream_fakesource_retryable_to_console_savepoint.conf, but made it long-running with many small splits (500000 rows / 500 splits) instead of using the checkpoint-hostile busy-source fixture. This keeps the job alive for retry without starving savepoint barrier injection.
  • Fixed the Paimon E2E thread-leak failure exposed by the last Build run. In cooperative execution, failed/abandoned tasks were marked done without calling Task.close(), unlike the blocking worker path. That can leave sink-owned executors such as st-multi-table-sink-writer-* parked after a failing sink test. The cooperative worker now closes failed tasks with the task connector classloader before marking them done, so sink close can shut down its internal executor.

Validation run locally:

  • ./mvnw -pl seatunnel-engine/seatunnel-engine-server spotless:apply passes.
  • git diff --check passes.
  • ./mvnw -pl seatunnel-ci-tools -Dtest=ImportClassCheckTest#javaUtilCompletableFutureCheck test passes.

I also retried direct seatunnel-engine-server compile locally; it is still blocked before useful module verification by this workspace resolving stale/mismatched local reactor artifacts (JobRestoreInProgressException, API metadata/signal classes, RestoreMode, metric constants, etc.). The full GitHub Build run on 8f5d15cd3 is now the authoritative verification: https://github.com/agarwalrahul2702/seatunnel/actions/runs/32128491990

@DanielLeens

Copy link
Copy Markdown
Contributor

结论:当前头暂不可交付。

源码正确性:重试用例在任务刚进入 RUNNING 后就直接伪造 checkpoint coordinator 已就绪,随后第一次请求被拒绝、第二次请求在真实 task-ready 握手尚未完成时启动,最终在 60 秒 checkpoint timeout 后将作业置为 FAILED。应先等待真实 coordinator ready,再注入一次 false 的前置条件失败,之后恢复 ready 并重试。最小补丁已推送到维护者 fork:DanielLeens@fb8618f。

CI 归因:当前头 8f5d15c 的 unit-test 作业 95686043072 确认失败于 SavePointBusySourceTest.testSavepointStartPreconditionFailureCanBeRetriedAfterReady;断言等待 SAVEPOINT_DONE,实际为 FAILED,并非外部基础设施失败。

范围风险:当前头同时加入了 TaskExecutionService 的 cooperative task close 生产逻辑,但该路径不由上述 savepoint precondition rejection 触发,且没有针对该新行为的回归测试。请将其拆分为独立 PR,或补充与本问题的因果关系和完整测试证明。

审查与合并门禁:未发现未解决的 review thread,但 reviewDecision 仍为 CHANGES_REQUESTED,mergeStateStatus 为 BLOCKED。尽管 PR 标示 maintainer 可修改,GitHub 拒绝 DanielLeens 直接推送到作者分支(403),因此请作者 cherry-pick 上述提交并移除或拆分无关生产改动;新当前头 CI 通过后再复核。

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What Problem Does This PR Solve?

User pain point: calling stop-with-savepoint on a Zeta job whose source is busy mid-split (holding the checkpoint lock) could hang forever in DOING_SAVEPOINT, and a mixed-outcome multi-pipeline savepoint attempt could be misclassified — either wrongly restoring RUNNING when a pipeline genuinely failed, or leaving the job stuck.

Fix approach: JobMaster now distinguishes a benign "checkpoint coordinator not ready yet" precondition failure from a genuine checkpoint failure, restores the job to RUNNING (instead of hanging or force-stopping) when every pipeline's savepoint failure is a pre-start precondition rejection, and surfaces a real failure to the caller in preference to a benign one when both occur in the same multi-pipeline attempt.

One-sentence summary: this closes out a real Zeta hang/misclassification bug in the savepoint state machine with a small, well-targeted production fix, but the last two commits on top of it (pushed since my previous review) introduce a new, unrelated engine-wide risk that needs to be closed before merge.

Thanks for pushing 037ea4335 — I did a complete, from-scratch re-review of the current head (not just the incremental diff) per our process. Good news first: the CI-blocking flakiness I flagged last round is fixed, and for a real, traceable reason (see 1.1-A below) — I re-verified it against source, not just against the commit message. But tracing the two commits pushed since my last review (8f5d15cd3, 037ea4335) turned up a new, unrelated blocker in TaskExecutionService.java, on top of the scope-separation concern I already raised in my 2026-08-18 follow-up comment that is still open on this exact head.

1. Code Change Review

1.1 Core Logic Analysis

Scope since my last full review (head ac936f844, review id 4960060606), confirmed via git diff ac936f844..037ea4335 --stat: exactly 3 files touched, +136/-0:

  • TaskExecutionService.java (+27) — brand new file for this PR, not covered by my last review.
  • SavePointBusySourceTest.java (+57) — restores the retry-succeeds test I asked to keep.
  • stream_fakesource_retryable_to_console_savepoint.conf (+52 net; deleted, recreated, then tuned once more in 037ea4335).

Everything else — JobMaster.java, CheckpointCoordinator.java, CheckpointManager.java, PhysicalPlan.java, the FakeSource* classes, SeaTunnelClientTest.java, JobMasterTest.java, and the other .conf fixtures — is byte-for-byte unchanged since my last review (git diff ac936f844..037ea4335 shows zero lines for all of them) and stands as previously verified; see the resolved rows in Section 4.

A) The retry-succeeds test is back, and this time the real root cause is fixed

My last round's blocker was that testSavepointStartPreconditionFailureCanBeRetriedAfterReady had been written correctly in 8e4364915 and then deleted in 2232478f1 without real CI evidence it was flaky. This round, 8f5d15cd3 restored the test, but the fork's own CI run for that exact head (unit-test, job 95686043072) failed for real: SavePointBusySourceTest.testSavepointStartPreconditionFailureCanBeRetriedAfterReady timed out waiting for SAVEPOINT_DONE and the job ended FAILED.

I traced why. CheckpointCoordinator.allTaskReady() (CheckpointCoordinator.java:438-459) is invoked asynchronously off a real READY_START task report:

private void allTaskReady() {
    ...
    if (!isAllTaskReady.compareAndSet(false, true)) {
        LOG.info("all task already ready, skip notify task start");
        return;
    }
    ...
    if (coordinatorConfig.isCheckpointEnable()) {
        LOG.info("checkpoint is enabled, start schedule trigger pending checkpoint.");
        scheduleTriggerPendingCheckpoint(coordinatorConfig.getCheckpointInterval());
    }

The first time the real handshake completes, this schedules a self-repeating periodic checkpoint at checkpoint.interval. The old retry fixture set checkpoint.interval = 1000, so from the moment the job's real readiness handshake landed, an automatic checkpoint fired roughly every second for the rest of the test — including through the deliberate "force not-ready / assert rejection / force ready / retry" sequence the test drives manually via reflection on the very same isAllTaskReady field (SavePointBusySourceTest.java:439-444, ReflectionUtils.getField(..., "isAllTaskReady")). A periodic checkpoint racing the manual retry can occupy the coordinator's single-pending-checkpoint slot (tryTriggerPendingCheckpoint, CheckpointCoordinator.java:801-803: if (pendingCounter.get() > 0) { ...skip...}) or otherwise perturb barrier scheduling right when the test's savePoint() retry needs a clean run at the 60s checkpoint.timeout — a very plausible explanation for the observed FAILED-after-timeout.

037ea4335's actual fix is exactly the right lever for that: checkpoint.interval in the retry conf is raised from 1000 to 600000 (10 minutes, comfortably outside the test's 120s await() budget), with a clear comment explaining why:

- checkpoint.interval = 1000
+ # Keep periodic checkpoints out of this retry regression. The test drives savepoints manually
+ # and needs the coordinator state to be controlled only by those explicit savepoint requests.
+ checkpoint.interval = 600000

This is a sound, source-grounded fix — better than my own suggested fork patch (which only reordered the readiness wait and would not have touched the periodic-checkpoint interference). I did not find that the earlier fork patch I proposed (awaitCheckpointCoordinatorsReady() before the first setCheckpointCoordinatorsReady(false)) was adopted, and I still see a residual, lower-probability timing gap there — see Issue 4, non-blocking.

Caveat: CI for this exact head (037ea4335) is still in progress at review time (fork run 32230792734, in_progress since 08:04Z) — I do not yet have a completed, real CI result to independently confirm the fix holds. I'm not blocking on this since the fix is well-grounded in source, but please make sure a real (non-cancelled) green run lands on this head before merge, same as last round.

B) New finding (blocking): closeTaskAfterFailedCooperativeExecution() can silently starve TaskGroup completion

8f5d15cd3 also added production logic in TaskExecutionService.java to close a cooperative task's FlowLifeCycles when it fails, fixing a real thread leak (the commit message cites st-multi-table-sink-writer-* executors leaking after a Paimon E2E sink failure). The new helper:

// TaskExecutionService.java:1267-1287
private void closeTaskAfterFailedCooperativeExecution(TaskTracker taskTracker) {
    ClassLoader oldClassLoader = myThread.getContextClassLoader();
    try {
        ...
        taskTracker.task.close();
    } catch (IOException e) {
        logger.severe("Close task error", e);
    } finally {
        myThread.setContextClassLoader(oldClassLoader);
    }
}

is invoked from three places, and in every one of them it runs before taskGroupExecutionTracker.taskDone(...):

// TaskExecutionService.java:1190-1192 (sibling task already failed)
if (taskGroupExecutionTracker.executionCompletedExceptionally()) {
    closeTaskAfterFailedCooperativeExecution(taskTracker);
    taskGroupExecutionTracker.taskDone(taskTracker.task);
    ...
// TaskExecutionService.java:1224-1226 (InterruptedException)
    timer.timerStop();
    closeTaskAfterFailedCooperativeExecution(taskTracker);
    taskGroupExecutionTracker.taskDone(taskTracker.task);
    ...
// TaskExecutionService.java:1234-1236 (Throwable)
    timer.timerStop();
    closeTaskAfterFailedCooperativeExecution(taskTracker);
    taskGroupExecutionTracker.taskDone(taskTracker.task);

taskDone() decrements a per-group AtomicInteger completionLatch (TaskExecutionService.java:1415-1422), and only when it reaches zero does the TaskGroup finalize (classloader recycle, async-function/timer-flush cancellation, metrics update, and — the real point — whatever completes the future the SubPlan/pipeline is waiting on). closeTaskAfterFailedCooperativeExecution() only catches IOException; Task.close() (SeaTunnelTask.java:453-475) fans out to every FlowLifeCycle.close() for that task (source/sink/transform internals), and nothing in that interface guarantees an implementation only ever throws IOException. If any close() in that fan-out throws an unchecked exception, it propagates out of closeTaskAfterFailedCooperativeExecution() and out of the enclosing catch block before taskDone() runs — the completion latch for that task never decrements, and if it was the last outstanding task in the group, the TaskGroup never finalizes.

That is structurally the same class of bug this PR sets out to fix — a hang — just relocated from the savepoint-specific precondition path into the general cooperative-task failure path, which every cooperative task in every job goes through, not just savepoint-related ones.

The existing blocking-worker path in the very same file gets this ordering right, and is a useful reference for the fix:

// TaskExecutionService.java:1100-1106 (blocking worker, existing code, unchanged by this PR)
} finally {
    taskGroupExecutionTracker.taskDone(t);      // <-- runs first
    if (result == null || !result.isDone()) {
        try {
            tracker.task.close();               // <-- close() failure can't block completion
        } catch (IOException e) {
            logger.severe("Close task error", e);
        }
    }
}

There, taskDone() always runs before close() is even attempted, so a close() failure — checked or unchecked — can never prevent the group from completing. The new cooperative-path code inverts that order.

C) Carryover (still blocking): TaskExecutionService.java remains unrelated production logic, still with zero dedicated tests

I flagged this in my 2026-08-18 follow-up comment on this PR: the cooperative-close change is not triggered by, or dependent on, the savepoint precondition-rejection path this PR is about — it fixes a general cooperative-task-failure resource leak, exposed by an unrelated Paimon E2E test. That has not changed in 037ea4335; the only commit since then touches the retry .conf file. There is still no unit test anywhere in this diff that exercises closeTaskAfterFailedCooperativeExecution() directly (e.g., asserting a failed cooperative task's FlowLifeCycle.close() is actually invoked, and that a TaskGroup with a failed cooperative task still reaches completion). The only evidence offered is an informal E2E observation described in a commit message, which is not a substitute for a deterministic regression test given the correctness issue in Section B above.

Complete runtime path — new hang scenario introduced by Section B

Cooperative task T (member of TaskGroup G, e.g. one writer in a
SupportMultiTableSinkWriter fan-out) throws inside task.call()
  -> CooperativeTaskWorker.run() catch (Throwable e)          [TaskExecutionService.java:1231-1236]
       taskGroupExecutionTracker.exception(e)
       timer.timerStop()
       closeTaskAfterFailedCooperativeExecution(taskTracker)   [runs FIRST]
         -> taskTracker.task.close()
              -> SeaTunnelTask.close() fans out to every FlowLifeCycle.close()
                   -- IF any FlowLifeCycle.close() throws a RuntimeException/Error --
                   -> propagates out of closeTaskAfterFailedCooperativeExecution()
                      (only `catch (IOException e)` present)
                   -> propagates out of the enclosing `catch (Throwable e)` block
                      BEFORE reaching the next line
       taskGroupExecutionTracker.taskDone(taskTracker.task)    [NEVER REACHED for task T]
         -> completionLatch.decrementAndGet() never happens for T
         -> if T was the last outstanding task in G, completionLatch never hits 0
         -> TaskGroup G's completion callback (classloader recycle / async-function
            cancel / timer-flush cancel / metrics update / SubPlan future) never fires
         -> pipeline waiting on G's completion hangs indefinitely

This is not the DOING_SAVEPOINT hang the PR title targets, but it is a hang, introduced by this PR's own new code, in a shared engine path every cooperative task goes through — which is exactly the class of regression this repository's review standard treats as blocking regardless of which specific state machine it affects.

1.2 Compatibility Impact

Fully compatible, unchanged from last round for the savepoint-classification logic (no config/serialization/API surface touched there). The TaskExecutionService.java change is new internal behavior (a cooperative task now gets close()'d on failure where it previously did not) — it doesn't change any public API or config, but it does change internal resource-lifecycle behavior for every cooperative task failure, which is exactly why Section C above asks for it to carry its own dedicated test rather than ride through on this PR's savepoint-focused test suite.

1.3 Performance / Side-Effect Analysis

  • The savepoint-classification code (JobMaster.java) is unchanged and remains a bounded, single-pass stream scan — negligible cost, as verified last round.
  • closeTaskAfterFailedCooperativeExecution() runs synchronously, inline, on the shared CooperativeTaskWorker thread (TaskExecutionService.java:1178, the same thread that round-robins every other cooperative TaskTracker in taskQueue). If any FlowLifeCycle.close() in the fan-out is slow (flushing a sink's in-flight batch, waiting out a network client's shutdown, joining an internal executor), that blocks this worker thread from servicing every other cooperative task sharing it for the duration — a head-of-line-blocking risk for the whole cooperative pool triggered by one task's failure. This is worth at least a design comment; whether it needs an async/bounded-timeout close is a judgment call for the author and maintainers, but it should be an explicit decision, not an implicit one.
  • The ordering bug in Section B is itself a resource/liveness risk (a stuck TaskGroup holds its slot, classloader, and any related resources indefinitely).

1.4 Error Handling and Logging

Issue 1 (new this round, blocking): closeTaskAfterFailedCooperativeExecution() runs before taskGroupExecutionTracker.taskDone(...) on all three cooperative-failure paths and only catches IOException; an unchecked exception from Task.close()'s FlowLifeCycle fan-out would skip taskDone() and can stall TaskGroup completion indefinitely. Location: TaskExecutionService.java:1190-1192, 1224-1226, 1234-1236, 1267-1287. Severity: High. Raised by another reviewer: No.

Issue 2 (carryover, still open, blocking): the cooperative-task-close production change is unrelated to this PR's stated savepoint-hang scope, is not exercised by any dedicated regression test, and its only justification is an informal E2E observation in a commit message. Location: TaskExecutionService.java (whole diff, +27 lines). Severity: High. Raised by another reviewer: No (first raised by me as a PR comment on 2026-08-18, still unresolved on this head).

Issue 3 (new this round, non-blocking): closeTaskAfterFailedCooperativeExecution() has no doc comment explaining why it exists, when it runs relative to taskDone(), or its ordering assumptions — exactly the kind of non-trivial lifecycle method this repo's documentation rule requires a comment on. Location: TaskExecutionService.java:1267. Severity: Medium. Raised by another reviewer: No.

Issue 4 (new this round, non-blocking): testSavepointStartPreconditionFailureCanBeRetriedAfterReady's first setCheckpointCoordinatorsReady(jobMaster, false) call is not preceded by awaitCheckpointCoordinatorsReady(jobMaster), unlike the other three tests in this file (SavePointBusySourceTest.java:78, 130, 205) that all wait for the real handshake before touching the flag. Since the real allTaskReady() handshake runs asynchronously off READY_START (CheckpointCoordinator.java:308-319) and mutates the exact same isAllTaskReady field the test overrides via reflection, there's a residual, lower-probability TOCTOU window where the real handshake's compareAndSet(false, true) could land after the test's forced override. Location: SavePointBusySourceTest.java:296-298. Severity: Medium (non-blocking — the primary, CI-confirmed cause of last round's failure is fixed by the checkpoint.interval change, and this is a secondary, unconfirmed residual risk). Recommend adding awaitCheckpointCoordinatorsReady(jobMaster) before line 298 for defense-in-depth, matching the file's own established pattern.

Resolved, unchanged since last round (re-confirmed via git diff ac936f844..037ea4335, zero lines changed in these files):

  • Mixed multi-pipeline failure classification now prefers a genuine failure over a benign precondition failure (JobMaster.java, getSavepointFailureException()), unit-tested by JobMasterTest#testSavepointFailureExceptionPrefersNonPreconditionFailure.
  • isSavepointStartPreconditionException() has its Javadoc.
  • CHECKPOINT_COORDINATOR_SHUTDOWN recognized as a benign precondition alongside TASK_NOT_ALL_READY_WHEN_SAVEPOINT.
  • FakeSourceReader/FakeSourceSplit restore-correctness fixes (split identity/hash, no mutation of assigned splits) from earlier rounds.
  • CheckpointManager#triggerSavePoints()'s public signature preserved; the new finalized-completion path lives in an additive triggerSavePointsAndWaitComplete().

No sensitive information logged; no exceptions silently swallowed beyond the IOException-only catch discussed in Issue 1.

2. Code Quality Assessment

2.1 Coding Standards

No wildcard imports, no System.out.println, no special symbols in logs/comments, license headers unaffected. See Issue 3 for the one missing-documentation gap this round.

2.2 Test Coverage and Test Stability

  • Does a test reproduce the original #11473 hang with a bounded-time assertion? Yes, unchanged: testStopWithSavepointCompletesWhileSourceEmitsLargeSplit (untouched by this round, previously verified).
  • Does a test now prove the retry-succeeds contract? Yes again, restored by testSavepointStartPreconditionFailureCanBeRetriedAfterReady (SavePointBusySourceTest.java:285-336).
  • Does any test exercise closeTaskAfterFailedCooperativeExecution() or the completion-latch ordering it can affect? No — this is the coverage gap behind Issue 1/Issue 2.

Flaky-pattern check (mandatory, test code changed this round):

  • testSavepointStartPreconditionFailureCanBeRetriedAfterReady: uses await().atMost(...).untilAsserted(...) throughout, no Thread.sleep, no hard-coded ports/hostnames. Risk present — see Issue 4 for the residual TOCTOU window on the first readiness override; the dominant, CI-observed failure cause (periodic-checkpoint interference) is soundly fixed by the checkpoint.interval change, so this is a secondary, non-blocking risk rather than a High-risk flaky pattern.
  • No other test files changed this round.

2.3 Documentation Updates

None required for user-facing docs — no Option/config surface changed. Issue 3 covers the internal code-comment gap.

3. Architectural Soundness

3.1 Elegance of the Solution

The savepoint-classification fix itself remains a precise, minimal, well-targeted fix. The TaskExecutionService.java addition is a reasonable idea (closing failed cooperative tasks to stop resource leaks is the right instinct) but its current shape is a workaround bolted onto this PR rather than a reviewed, tested change in its own right — see 3.2.

3.2 Maintainability

The ordering inversion in Section B is exactly the kind of subtle bug that's easy to introduce and hard to catch without a dedicated test, because it only manifests when close() itself misbehaves — which is disproportionately likely to happen right when a task has already failed and its internal state may be inconsistent. I'd strongly encourage splitting this into its own PR with its own focused review and tests; it would get more scrutiny there than as a rider on a savepoint-hang fix, and it's independently valuable regardless of what happens to the savepoint work.

3.3 Extensibility

Unchanged from prior rounds' assessment for the savepoint-classification code.

3.4 Historical-Version Compatibility

Fully compatible; no format/API/config break. The TaskExecutionService.java behavior change affects only in-process cooperative-task failure handling, not any persisted or wire format.

4. Issue Summary

# Issue Location Severity Blocking Raised by another reviewer
1 (new) closeTaskAfterFailedCooperativeExecution() runs before taskGroupExecutionTracker.taskDone(...) and only catches IOException; an unchecked close() failure can stall TaskGroup completion indefinitely TaskExecutionService.java:1190-1192, 1224-1226, 1234-1236, 1267-1287 High Yes No
2 (carryover, still open) Cooperative-task-close production change is unrelated to this PR's savepoint-hang scope and has zero dedicated regression test TaskExecutionService.java (+27 lines) High Yes No (first raised by me, 2026-08-18 PR comment)
3 (new) closeTaskAfterFailedCooperativeExecution() has no doc comment TaskExecutionService.java:1267 Medium No No
4 (new) Retry test's first readiness override isn't preceded by awaitCheckpointCoordinatorsReady(), unlike its siblings — residual, unconfirmed TOCTOU risk SavePointBusySourceTest.java:296-298 Medium No No
5 (resolved, carryover) Mixed-failure classification, isSavepointStartPreconditionException() docs, CHECKPOINT_COORDINATOR_SHUTDOWN recognition, FakeSource* restore correctness, CheckpointManager API preservation various, all unchanged since ac936f844 — No No (resolved)

5. Merge Recommendation

Conclusion: Not ready to merge — one confirmed-fixed issue, but this round's own new commits introduce a fresh blocker

Blockers — must be fixed:

  1. Issue 1 — fix the ordering so a close() failure (of any kind, not just IOException) can never prevent taskGroupExecutionTracker.taskDone(...) from running. The lowest-risk option, matching the existing blocking-worker pattern in the same file: call taskDone() first, then attempt close() in a try { ... } catch (Throwable t) { logger.severe(...); } afterward (matching TaskExecutionService.java:1100-1106's proven-safe ordering). Please also add a unit test that forces close() to throw and asserts the TaskGroup/pipeline still completes.
  2. Issue 2 — either split the cooperative-close change into its own PR (my preference — it's independently valuable and deserves its own focused review and CI cycle rather than riding through as a rider on the savepoint fix), or, if it stays here, add a dedicated unit test that reproduces the original Paimon-style leak (a cooperative task failing while holding an internal executor) and asserts it's actually released, plus the completion test from Issue 1.

Recommended fixes — non-blocking:

  • Issue 3 — add a short doc comment on closeTaskAfterFailedCooperativeExecution().
  • Issue 4 — add awaitCheckpointCoordinatorsReady(jobMaster) before the first setCheckpointCoordinatorsReady(jobMaster, false) in the retry test, matching the file's own established pattern, for defense-in-depth even though it isn't the confirmed cause of last round's failure.

Reacting to the existing CHANGES_REQUESTED decision and other reviewers: this remains the right call, now for a different reason than last round. The savepoint-classification logic itself (what @nzw921rx, @davidzollo, @SEZ9, and I spent many rounds on) is done, correct, and unit-tested — nothing new to add there. The gate has shifted entirely to the two commits added this round in TaskExecutionService.java, which is new ground none of us has reviewed before.

CI diagnosis: the apache-side Build check is currently pending/in_progress, mirroring the fork's own run (32230792734, started 2026-08-19T08:04Z, still in_progress as of this review) — no completed result yet for this exact head, so I can't independently confirm the retry-test fix is stable on real CI. Please make sure a real, completed (not cancelled) green run lands on 037ea4335 (or whatever head carries the Issue 1/2 fixes) before merge.

Upstream sync: this branch is currently diverged from dev (ahead_by=26, behind_by=11), but mergeable=true with no reported conflicts, and the current CI failure signal (still pending) hasn't been shown to be caused by upstream drift — no sync action is needed on that basis right now.

Overall assessment: genuinely good progress this round on the flakiness front, and I want to be clear that catching Issue 1 doesn't take anything away from that — the periodic-checkpoint fix is a real, well-reasoned root-cause fix, not a band-aid. The remaining work is entirely contained in the new TaskExecutionService.java code, and I think either path in Issue 2 (split it out, or add the two tests) gets this the rest of the way. This has been a long review cycle and the savepoint-specific logic has held up well through it — really solid work getting the core state-machine fix right; let's get this last piece closed out and I'd expect this to be ready.

@agarwalrahul2702

Copy link
Copy Markdown
Contributor Author

Pushed 2b840e976 to address Daniel’s latest review.

Changes:

  • Removed the cooperative-task-close production change from this PR. That takes TaskExecutionService.java back out of the net PR diff, so the unrelated lifecycle/test-coverage blocker is no longer part of this savepoint fix.
  • Added awaitCheckpointCoordinatorsReady(jobMaster) before forcing isAllTaskReady=false in the retry-precondition tests. The retry test now waits for the real coordinator-ready handshake first, injects exactly one precondition rejection, restores readiness, and then retries the savepoint.

The retry fixture already has the periodic-checkpoint isolation from 037ea4335 (checkpoint.interval = 600000, checkpoint.timeout = 60000), so the test is driven by the explicit savepoint calls rather than an overlapping periodic checkpoint.

Local validation:

  • ./mvnw -pl seatunnel-engine/seatunnel-engine-server spotless:apply passes.
  • git diff --check passes.
  • ./mvnw -pl seatunnel-ci-tools -Dtest=ImportClassCheckTest#javaUtilCompletableFutureCheck test passes.

New Build run for this head: https://github.com/agarwalrahul2702/seatunnel/actions/runs/32271489557

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What Problem Does This PR Solve?

User pain point: calling stop-with-savepoint on a Zeta job whose source is busy mid-split (holding the checkpoint lock) could hang forever in DOING_SAVEPOINT, and a mixed-outcome multi-pipeline savepoint attempt could be misclassified — either wrongly restoring RUNNING when a pipeline genuinely failed, or leaving the job stuck.

Fix approach: JobMaster now waits for each pipeline's checkpoint coordinator to reach its own terminal-state future instead of resolving as soon as tasks merely ACK the barrier; distinguishes a benign "checkpoint coordinator not ready yet" precondition rejection from a genuine checkpoint failure across all pipelines (not just the first exception seen); restores the job to RUNNING only when every failure is such a precondition rejection; and otherwise deterministically drives the job out of DOING_SAVEPOINT via the existing stop-with-checkpoint-fallback machinery. A companion fix bounds FakeSource row emission per poll so the checkpoint lock is periodically released instead of held for an entire large split.

One-sentence summary: this closes a real Zeta savepoint-hang/misclassification bug with a precise, minimal state-machine fix, and the two commits pushed since my last review resolve both blockers I raised then without introducing anything new.

Thanks for pushing 2b840e976 so quickly. I did a complete, from-scratch re-review of the current head (not just the incremental diff) per our process, including re-fetching every review/comment on this PR and re-tracing the savepoint state machine against the checked-out source. Good news up front: both High-severity blockers from my 037ea4335 review are resolved, cleanly, and I could not find anything new to add.

1. Code Change Review

1.1 Core Logic Analysis

Scope confirmed independently. git diff 037ea43357f03827622196d26f85e1bff2680568..2b840e97663480e10bef169ac963a0ae6580dccb --stat (plus one no-op [Chore][CI] commit in between) shows exactly two files changed:

  • TaskExecutionService.java: -27/+0 — a complete removal.
  • SavePointBusySourceTest.java: +2/-0.

Every other file in the PR — JobMaster.java, CheckpointCoordinator.java, CheckpointManager.java, PhysicalPlan.java, the FakeSource* classes, SeaTunnelClientTest.java, JobMasterTest.java, and all .conf fixtures — is byte-identical to what I already fully reviewed at 037ea4335, so my prior Compatibility/Performance/Architecture conclusions for that code stand as re-verified, not re-derived. I independently re-read the full savePoint() / waitSavepointCompleted() / isSavepointStartPreconditionFailure() / getSavepointFailureException() chain in JobMaster.java:1284-1427 and CheckpointCoordinator.startSavepointAndWaitComplete() / waitCheckpointCoordinatorComplete() in the checked-out source, and it matches the design I traced last round exactly — no drift.

Issue 1 (last round, High) — resolved by complete removal, not by fixing in place

Last round's Issue 1 was that closeTaskAfterFailedCooperativeExecution() ran before taskGroupExecutionTracker.taskDone(...) on all three cooperative-failure paths in TaskExecutionService.java, and only caught IOException — so an unchecked exception from Task.close()'s FlowLifeCycle fan-out could skip taskDone() and stall TaskGroup completion indefinitely, a new hang in a shared engine path.

2b840e976 removes the method and all three call sites verbatim:

 if (taskGroupExecutionTracker.executionCompletedExceptionally()) {
-    closeTaskAfterFailedCooperativeExecution(taskTracker);
     taskGroupExecutionTracker.taskDone(taskTracker.task);
...
-    timer.timerStop();
-    closeTaskAfterFailedCooperativeExecution(taskTracker);
     taskGroupExecutionTracker.taskDone(taskTracker.task);
...
-    private void closeTaskAfterFailedCooperativeExecution(TaskTracker taskTracker) { ... }

I verified this is a clean, complete revert, not a partial one: git diff ac936f84438cec81717d7eadd42ae121d573d8f8..2b840e97663480e10bef169ac963a0ae6580dccb -- .../TaskExecutionService.java (comparing against the last head before the cooperative-close change was ever introduced) returns zero lines. timer.timerStop() was added by the same original commit (8f5d15cd3) that added closeTaskAfterFailedCooperativeExecution(), so removing both together doesn't strip any pre-existing cleanup — the file is now byte-identical to both its own pre-8f5d15cd3 state and to current dev (git compare dev...2b840e976 shows this file is no longer in the diff at all). Issue 1 is fully resolved.

Issue 2 (last round, High) — resolved the way I preferred

Last round I flagged that the cooperative-close change was unrelated to this PR's savepoint-hang scope, had zero dedicated regression test, and offered two options: split it into its own PR, or add dedicated tests here. The author took my stated preference — full removal from this PR — which is the cleanest resolution: the unrelated, untested change is no longer part of this diff at all, so there's nothing here to test or scope-audit. (The original Paimon-style cooperative-task-close leak this was meant to fix is, correspondingly, no longer addressed by this PR — see 3.2 for a follow-up note, non-blocking.)

Issue 3 (last round, Medium, non-blocking) — moot

Was "no doc comment on closeTaskAfterFailedCooperativeExecution()." The method no longer exists in this diff, so this is moot.

Issue 4 (last round, Medium, non-blocking) — fixed exactly as suggested

Was: the retry-precondition test's first setCheckpointCoordinatorsReady(jobMaster, false) wasn't preceded by awaitCheckpointCoordinatorsReady(jobMaster), unlike its three sibling tests, leaving a residual TOCTOU window against the real async allTaskReady() handshake.

 JobMaster jobMaster = server.getCoordinatorService().getJobMaster(jobId);
+awaitCheckpointCoordinatorsReady(jobMaster);
 setCheckpointCoordinatorsReady(jobMaster, false);

Applied to both testSavepointStartPreconditionFailureKeepsJobRunning (:244-247) and testSavepointStartPreconditionFailureCanBeRetriedAfterReady (:296-299), matching the pattern already used at lines 78 and 130. This now defends against the exact race I described, and — see 2.2 below — is CI-confirmed to pass.

Complete runtime path (re-traced against the current head)

Client: stop-job(isStopWithSavePoint=true)
   |
   v
JobMaster.savePoint()                                    [JobMaster.java:1284-1327]
   |  physicalPlan.savepointJob()          -> RUNNING -> DOING_SAVEPOINT (no-op if already end-state)
   |  checkpointManager.triggerSavePointsAndWaitComplete()
   v
CheckpointCoordinator.startSavepointAndWaitComplete()     [CheckpointCoordinator.java:868-899]
   |  startSavepoint() -> creates a savepoint-flagged pending checkpoint,
   |        OR throws synchronously (e.g. TASK_NOT_ALL_READY_WHEN_SAVEPOINT,
   |        CHECKPOINT_COORDINATOR_SHUTDOWN) before any PendingCheckpoint exists
   |  task(s) ACK the barrier -> async completion persists state, calls
   |        updateStatus(SUSPEND) and completes the SAME checkpointCoordinatorFuture
   |        already used by the non-savepoint completion path [:1379-1390]
   |  waitCheckpointCoordinatorComplete() resolves once that shared future resolves
   v
JobMaster.waitSavepointCompleted(futures[])               [JobMaster.java:1354-1390]
   |  allOf(futures).join() (best-effort; real result inspected per-future below)
   |  for every future: SUSPEND -> anyPipelineSuspended=true, else savepointCompleted=false;
   |        every exception collected (not just the first)
   v
   ,---------------------------------------------------------------------------.
   | all SUSPEND, no exceptions        | >=1 exception, NONE suspended, EVERY  | otherwise (any
   | -> savepointCompleted=true        |  exception is a precondition-reject   |  suspended pipeline
   | -> client RPC resolves true       |  (TASK_NOT_ALL_READY / SHUTDOWN)      |  + any real failure,
   |                                   |  -> isSavepointStartPreconditionFailure|  or a non-exceptional
   |                                   |     = true                            |  non-SUSPEND state)
   '---------------------------------------------------------------------------'
                    |                              |                     |
                    | (finally, always runs)        v                     v
                    |                    restoreRunningAfterSavepointStartFailure()
                    |                    only if job still DOING_SAVEPOINT -> RUNNING
                    |                    (guarded against a concurrent cancel)
                    v (else branch)
          physicalPlan.savepointFailed()  [PhysicalPlan.java:238-244]
                    |  only acts if job is still DOING_SAVEPOINT
                    v
          PhysicalPlan.stopJob()  (pre-existing, unchanged by this PR)
                    |  per-pipeline stop-with-checkpoint fallback:
                    |    already-SUSPEND pipeline -> force-finish (idempotent no-op)
                    |    everything else -> cancel coordinator, force-stop
                    v
          job settles at RUNNING (retry path) or FAILED/CANCELED, never stuck DOING_SAVEPOINT

Key Findings

  • The normal path (a running job on a busy source, client calls stop-with-savepoint) directly reaches every line changed by this PR — this is the primary execution path for the feature being fixed, not a narrow race-window-only patch.
  • The savepoint-classification logic (mixed-failure handling via allMatch over all collected exceptions, not just the first) is unchanged since my last full review and remains correct — I re-derived it from source rather than trusting the prior write-up, and it holds.
  • This round's only functional change is a subtraction: removing 27 lines of unrelated, under-tested production code from TaskExecutionService.java. Subtracting an out-of-scope change cannot introduce a savepoint-path regression, and I confirmed via diff that it restores the file to its exact pre-existing state rather than leaving a partial/inconsistent removal.
  • The 2-line test change is a precise, minimal fix matching an established sibling pattern in the same file, and is independently confirmed by real (not simulated) CI.
  • I found no new issue in this round's diff, and no previously-open item remains open.

1.2 Compatibility Impact

Fully compatible, unchanged from all prior rounds: no checkpoint/savepoint binary format change, no config/Option surface added or renamed, no public API signature change. TaskExecutionService.java's removal returns internal cooperative-task-failure behavior to exactly what it was before this PR touched it — a compatibility non-event, since it's a pure subtraction back to the pre-PR baseline.

1.3 Performance / Side-Effect Analysis

Unchanged from prior rounds for the savepoint-classification code: the new wait is bounded by the checkpoint-timeout scheduler (independent of any busy task thread) and by every pipeline-end-state resolution branch, so the worst case is the checkpoint timeout, not indefinite. Removing the cooperative-close code also removes the head-of-line-blocking risk I'd have flagged for it (a slow FlowLifeCycle.close() blocking the shared CooperativeTaskWorker thread) — that concern is now moot along with the code that created it.

1.4 Error Handling and Logging

No blocking issues found in this round's diff. waitSavepointCompleted()'s catch block around allOf(...).join() logs at FINE with an explanatory message before falling through to per-future inspection — adequate, and every per-future exception is preserved in the returned SavepointCompletionResult rather than swallowed. No sensitive information logged anywhere in the diff.

2. Code Quality Assessment

2.1 Coding Standards

No wildcard imports, no System.out.println, no special symbols in logs/comments, license headers unaffected. Every method touched by the savepoint-classification logic (isSavepointStartPreconditionFailure, isSavepointStartPreconditionException, getSavepointFailureException, restoreRunningAfterSavepointStartFailure, waitSavepointCompleted) carries a Javadoc explaining why, not just what — I confirmed this directly against the checked-out source, not from memory of prior rounds.

2.2 Test Coverage and Test Stability

  • Does a test reproduce the original #11473 hang with a bounded-time assertion? Yes, unchanged: testStopWithSavepointCompletesWhileSourceEmitsLargeSplit.
  • Does the retry-succeeds contract have real coverage? Yes: testSavepointStartPreconditionFailureCanBeRetriedAfterReady, now with the readiness-await fix applied.
  • Does the mixed multi-pipeline classification have unit coverage? Yes, unchanged: JobMasterTest#testSavepointFailureExceptionPrefersNonPreconditionFailure.
  • Is there any coverage gap left behind by the TaskExecutionService.java removal? No — removing unreviewed, untested production code closes a coverage gap rather than opening one.

Flaky-pattern check (mandatory, test code changed this round): SavePointBusySourceTest.java's 2-line change adds awaitCheckpointCoordinatorsReady(jobMaster) before the existing setCheckpointCoordinatorsReady(jobMaster, false) calls, matching the file's own await().atMost(...).untilAsserted(...) condition-based pattern used elsewhere in the same file — no Thread.sleep, no hard-coded ports/hostnames, no order dependency introduced. Stable. I did not stop at reading the diff: I pulled the author's own fork CI run for this exact head (agarwalrahul2702/seatunnel run 32271489557, head 2b840e976) and confirmed JobMasterTest (10/10 passed) and SavePointBusySourceTest (7/7 passed, including the previously-flaky retry test) both passed for real. This closes out the flakiness concern with actual evidence, not just code inspection.

CI diagnosis (verified against real logs, not just the check name): the apache-side Build check and the author's own fork run both show FAILURE for this head, but I traced every failing job in the fork run and none of them touch this PR's diff:

  • unit-test (8, ubuntu-latest): the only real test failure is EngineStateStoreLogicalMetricExportsTest.collectShouldExportLogicalMetricsForSpecialStateStores (expected: <2.0> but was: <1.0>) — a telemetry-metrics assertion in a file untouched by this PR. SavePointBusySourceTest and JobMasterTest in the same job both passed cleanly (see above).
  • doris-connector-it (11, ubuntu-latest): fails in DorisSchemaChangeIT.testDorisWithSchemaEvolutionCase with a ConditionTimeout — an unrelated Doris E2E connector test.
  • elasticsearch-connector-it (8, ubuntu-latest): the Elasticsearch testcontainer repeatedly restarts and the Hazelcast client can't connect across a wide port range — an infra/container-startup instability, again unrelated to this PR's Zeta savepoint changes.

So the current CI redness is real but not caused by this PR. I'd suggest rerunning just those three failed jobs (they look like classic CI-environment noise for this repo) rather than treating them as a merge blocker; I don't see anything in this PR's diff that would explain any of the three.

2.3 Documentation Updates

None required — no user-facing Option/config surface was added, changed, or renamed by this round's changes (or by the PR as a whole).

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix. The savepoint-classification logic correctly separates "ACK-complete" from "savepoint-complete" by reusing the coordinator's own pre-existing terminal-state future, and separately distinguishes "never started" precondition rejections from genuine mid-flight failures across the whole multi-pipeline result set rather than the first exception seen. This round's change is architecturally a pure subtraction (removing an unrelated rider) plus a minimal, pattern-matching test fix — it doesn't add any new mechanism, so there's nothing new to critique on elegance grounds.

3.2 Maintainability

High, and improved by this round: the diff is now scoped entirely to the savepoint state machine and its regression tests, with no unrelated cross-cutting change riding along. One non-blocking note carried forward from last round: the original Paimon-style cooperative-task-close leak that 8f5d15cd3 was trying to fix is, once again, unaddressed now that the fix is removed — I'd still encourage the author to open a dedicated follow-up PR for that (with its own tests, per my last round's Issue 1/2 analysis), since it's a real, separate resource-leak concern that deserves its own focused review rather than riding through here.

3.3 Extensibility

Unchanged from prior rounds' assessment — the "wait for a fully-finalized checkpoint coordinator state" pattern generalizes cleanly for any future caller with the same ACK-vs-finalization distinction.

3.4 Historical-Version Compatibility

Fully compatible; no format/API/config break. Restoring a savepoint created by an older version, or upgrading a running cluster mid-flight, is unaffected by this round's changes (a test-file tweak and a production-code subtraction back to the pre-PR baseline).

4. Issue Summary

# Issue Location Severity Blocking Status
1 closeTaskAfterFailedCooperativeExecution() ordering bug could stall TaskGroup completion TaskExecutionService.java High — Resolved — code removed entirely in 2b840e976
2 Cooperative-task-close change was unrelated to this PR's scope with zero dedicated test TaskExecutionService.java High — Resolved — code removed entirely in 2b840e976
3 Missing doc comment on closeTaskAfterFailedCooperativeExecution() TaskExecutionService.java:1267 Medium No Moot — method removed
4 Retry test missing awaitCheckpointCoordinatorsReady() before first readiness override SavePointBusySourceTest.java:296-298 Medium No Resolved — added in 2b840e976, CI-confirmed passing

No new issues found in this round. No blocking issues found as of head 2b840e97663480e10bef169ac963a0ae6580dccb.

5. Merge Recommendation

Conclusion: Ready to merge

Blockers — must be fixed: none. Both High-severity blockers from my previous round are resolved with direct diff evidence, not just the author's description of the fix.

Recommended fixes — non-blocking:

  • Consider opening a dedicated follow-up PR for the original Paimon-style cooperative-task-close leak that TaskExecutionService.java's removed code was trying to address (3.2) — genuinely valuable, but deserves its own scoped review and tests rather than riding along with the savepoint fix.

CI: currently red on this exact head, but I traced all three failing jobs to root cause and none touch this PR's diff (an unrelated telemetry-metrics assertion, an unrelated Doris E2E test, and Elasticsearch testcontainer instability). I'd ask for a rerun of those three jobs before the actual merge, but I don't consider this a code-side blocker.

Reacting to the existing CHANGES_REQUESTED decision: that decision was correct when I posted it against 037ea4335, for the TaskExecutionService.java regression it flagged. That regression is now gone from the diff, so I'm updating my own conclusion to reflect the current head rather than leaving stale guidance on the PR.

Upstream sync: this branch remains diverged from dev (ahead_by=28, behind_by=15 as of this review), but mergeable=true with no reported conflicts, and none of the three CI failures I diagnosed above look attributable to being behind dev — no sync action is required on that basis.

Overall assessment: this has been a long, genuinely hard review cycle — three interacting root causes across a connector and the engine's checkpoint/savepoint lifecycle, worked through adversarial re-review from four different reviewers across many rounds. The core engine fix (wait for finalized coordinator state instead of ACK, classify precondition-vs-genuine failure across all pipelines, deterministically resolve DOING_SAVEPOINT either way) is sound, minimal, well-tested, and I could not find a hole in it after tracing it independently against the current source. Nice work getting this fully closed out.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What Problem Does This PR Solve?

User pain point: calling stop-with-savepoint on a Zeta job whose source is busy mid-split (holding the checkpoint lock) could hang forever in DOING_SAVEPOINT, and a mixed-outcome multi-pipeline savepoint attempt could be misclassified — either wrongly restoring RUNNING when a pipeline genuinely failed, or leaving the job stuck.

Thanks for pushing 2b840e976 — this is a complete, from-scratch re-review of the current head per our process, not a diff against my last round. Good news up front: both of my last round's blockers are resolved, cleanly and in the simplest possible way — the unrelated TaskExecutionService.java production change is removed entirely rather than patched, and the residual test TOCTOU risk is closed. I traced the full diff from the merge-base and independently re-verified the parts I'd already signed off on in earlier rounds are still byte-for-byte unchanged.

1. Code Change Review

1.1 Core Logic Analysis

Scope of this round's single commit (2b840e976, "[Test][Zeta] Address savepoint retry review"), confirmed via git diff 037ea4335..2b840e976 --stat: exactly 2 files touched, +2/-27:

  • TaskExecutionService.java (-27) — entire removal of the closeTaskAfterFailedCooperativeExecution() helper and its three call sites.
  • SavePointBusySourceTest.java (+2) — one awaitCheckpointCoordinatorsReady(jobMaster) call added before each of the two setCheckpointCoordinatorsReady(jobMaster, false) calls that didn't already have one.

Everything else — JobMaster.java, CheckpointCoordinator.java, CheckpointManager.java, PhysicalPlan.java, the FakeSource* classes, SeaTunnelClientTest.java, JobMasterTest.java, and the .conf fixtures — is byte-for-byte unchanged since my last full review (re-confirmed independently via git diff 037ea4335..2b840e976 for those paths: zero lines). I re-verified JobMaster.java's getSavepointFailureException() / isSavepointStartPreconditionFailure() / SavepointCompletionResult and PhysicalPlan.savepointFailed() / CheckpointCoordinator.startSavepointAndWaitComplete() / CheckpointManager.triggerSavePointsAndWaitComplete() directly against this head's source and they match exactly what I described and approved-in-substance in prior rounds. No new re-derivation needed there beyond confirming the bytes didn't move.

A) Issue 1 (previously blocking, now resolved): the ordering/exception-handling bug is gone because the code it lived in is gone

Last round I found that closeTaskAfterFailedCooperativeExecution() ran before taskGroupExecutionTracker.taskDone(...) on all three cooperative-failure paths, and only caught IOException — so an unchecked exception from Task.close()'s FlowLifeCycle fan-out could skip taskDone() and stall TaskGroup completion indefinitely.

This round's commit removes the method and all three call sites outright:

 if (taskGroupExecutionTracker.executionCompletedExceptionally()) {
-    closeTaskAfterFailedCooperativeExecution(taskTracker);
     taskGroupExecutionTracker.taskDone(taskTracker.task);
...
-    timer.timerStop();
-    closeTaskAfterFailedCooperativeExecution(taskTracker);
     taskGroupExecutionTracker.taskDone(taskTracker.task);
...
-    timer.timerStop();
-    closeTaskAfterFailedCooperativeExecution(taskTracker);
     taskGroupExecutionTracker.taskDone(taskTracker.task);
...
-        private void closeTaskAfterFailedCooperativeExecution(TaskTracker taskTracker) { ... }

I confirmed TaskExecutionService.java is now identical to dev (git diff dev 2b840e976 -- .../TaskExecutionService.java returns empty). There is no ordering bug to find because the file carries none of this PR's changes any more — the class of hang I flagged is gone by construction, not by a patched fix that still needs proving.

B) Issue 2 (previously blocking, now resolved): the unrelated production change is out of this PR's diff

My 2026-08-18 comment and last round's review both asked for this cooperative-close change to either be split into its own PR or backed by dedicated tests, because it was an unrelated Paimon-leak fix riding through a savepoint-hang PR. The author took the cleanest available option: it's removed from this PR entirely rather than kept and re-justified. I don't see it re-appearing anywhere else in this diff (grepped the full 2b840e976 diff for closeTaskAfterFailedCooperativeExecution — zero hits). This is exactly what "split it out" ultimately achieves for this PR's review scope — the savepoint-hang fix no longer carries an unrelated, untested engine-wide behavior change. (If the author still wants the Paimon-leak fix, it belongs in its own PR with its own tests and CI cycle, per my earlier recommendation — but that's now out of scope for this PR, not a blocker on it.)

C) Issue 4 (previously non-blocking, now resolved): retry test readiness ordering matches the file's established pattern

Last round's residual, non-blocking concern was that testSavepointStartPreconditionFailureCanBeRetriedAfterReady's first setCheckpointCoordinatorsReady(jobMaster, false) wasn't preceded by awaitCheckpointCoordinatorsReady(jobMaster), unlike the file's other tests — a low-probability TOCTOU window against the real async allTaskReady() handshake. I checked every test method in the file on this head:

testStopWithSavepointCompletesWhileSourceEmitsLargeSplit:      awaitCheckpointCoordinatorsReady() at :78
testStopWithSavepointCompletesWhileSourceEmitsLargeCustomRows: awaitCheckpointCoordinatorsReady() at :130
testSavepointFailureReportsErrorAndStopsJob:                   awaitCheckpointCoordinatorsReady() at :205
testSavepointStartPreconditionFailureKeepsJobRunning:          awaitCheckpointCoordinatorsReady() at :247 (added this round)
testSavepointStartPreconditionFailureCanBeRetriedAfterReady:   awaitCheckpointCoordinatorsReady() at :299 (added this round)
testSavepointFailureStopsWholeMultiPipelineJob:                awaitCheckpointCoordinatorsReady() at :353

Every test that forces isAllTaskReady=false via reflection now waits for the real handshake first, consistently. Closed.

Complete runtime path (unchanged from prior rounds, re-verified against this exact head)

Client: stop-job --with-savepoint
  -> CoordinatorServiceImpl.savePoint(jobId)
  -> JobMaster.savePoint()
       physicalPlan.savepointJob()                          [state: RUNNING -> DOING_SAVEPOINT]
       checkpointManager.triggerSavePointsAndWaitComplete()
       CheckpointCoordinator.startSavepointAndWaitComplete()
         -> not all tasks ACKed readiness
         -> CheckpointException(TASK_NOT_ALL_READY_WHEN_SAVEPOINT)
       waitSavepointCompleted(passiveCompletableFutures)      [collects ALL pipeline exceptions]
       getSavepointFailureException(result)                  [prefers a genuine failure over a benign one]
       isSavepointStartPreconditionFailure(result)
         -> allMatch(isSavepointStartPreconditionException) == true
         -> restoreRunningAfterSavepointStartFailure()        [state: DOING_SAVEPOINT -> RUNNING, no hang]
Caller: sees ExecutionException, job status == RUNNING -> free to retry savePoint() later
  -> once checkpoint coordinators report ready, retried savePoint() reaches SAVEPOINT_DONE
     (proven end-to-end by testSavepointStartPreconditionFailureCanBeRetriedAfterReady)

The primary #11473 hang scenario (busy source saturating the pipeline, savepoint requested once coordinators are ready) remains covered by testStopWithSavepointCompletesWhileSourceEmitsLargeSplit, untouched this round.

1.2 Compatibility Impact

Fully compatible. This round's only production change is a pure deletion of code that was itself new to this PR (never released, never merged to dev) — no config/Option/API/serialization surface is touched, and removing it can't regress anything already shipped. JobMaster.java, CheckpointCoordinator.java, CheckpointManager.java, PhysicalPlan.java are unchanged since my last review and remain fully compatible as previously verified (no checkpoint/savepoint binary format change, no public signature changed).

1.3 Performance / Side-Effect Analysis

Removing closeTaskAfterFailedCooperativeExecution() also removes the head-of-line-blocking risk I flagged last round (a slow synchronous close() running inline on the shared CooperativeTaskWorker thread). No new waits, threads, retries, or buffers introduced this round. getSavepointFailureException() etc. remain a bounded, single-pass stream scan — negligible, as verified previously.

1.4 Error Handling and Logging

Issue 1 (resolved this round): closeTaskAfterFailedCooperativeExecution() ran before taskDone() and only caught IOException — the method and all call sites are removed. TaskExecutionService.java is byte-identical to dev.

Issue 2 (resolved this round): cooperative-task-close change was unrelated to this PR's scope with zero dedicated test — removed from this PR's diff entirely.

Issue 3 (moot, was non-blocking): missing doc comment on closeTaskAfterFailedCooperativeExecution() — the method no longer exists, so there's nothing to document.

Issue 4 (resolved this round): retry test's first readiness override wasn't preceded by awaitCheckpointCoordinatorsReady() — added, matches the file's established pattern in all six test methods.

No sensitive information logged; no exceptions silently swallowed.

2. Code Quality Assessment

2.1 Coding Standards

Clean. No wildcard imports, no System.out.println, no special symbols in logs/comments, license headers unaffected (no new files this round). Nothing new to comment on — this round is a pure deletion plus two one-line test additions.

2.2 Test Coverage and Test Stability

I checked this round's actual, non-cancelled CI run for the current head against the fork (agarwalrahul2702/seatunnel run 32271489557, head 2b840e976) directly, not a historical/superseded run:

  • unit-test (8, ubuntu-latest): failure, but the only failing test in the entire 449-test module run is EngineStateStoreLogicalMetricExportsTest.collectShouldExportLogicalMetricsForSpecialStateStores (expected: <2.0> but was: <1.0>) — a pre-existing metrics/telemetry test with no relationship to savepoints, checkpoints, or task execution, and not touched anywhere in this PR's diff. Within the same job run, JobMasterTest: Tests run: 10, Failures: 0, Errors: 0, and SavePointBusySourceTest: Tests run: 7, Failures: 0, Errors: 0, Time elapsed: 17.693 s (7 tests, matching all six pre-existing methods plus the restored retry test) — both fully green.
  • unit-test (11, ubuntu-latest), unit-test (8/11, windows-latest): cancelled (fail-fast cancellation after the unrelated ubuntu-8 failure above, not independent failures).
  • elasticsearch-connector-it (8, ubuntu-latest): failure, but this is the connector-elasticsearch-e2e module — Testcontainers repeatedly starting/stopping an Elasticsearch 8.9.0 container — with nothing in its log tying it to the Zeta engine or this diff.

So the retry-succeeds contract (testSavepointStartPreconditionFailureCanBeRetriedAfterReady, restored last round) and the original hang-fix contract (testStopWithSavepointCompletesWhileSourceEmitsLargeSplit) are both proven on this exact head's own tests, and the two CI failures present are in modules this PR doesn't touch.

Flaky-pattern check (mandatory, test code changed this round): the two added lines are just awaitCheckpointCoordinatorsReady(jobMaster) calls into the file's existing await().atMost(...).untilAsserted(...)-based helper — no Thread.sleep, no new nondeterminism. Stable.

2.3 Documentation Updates

None required — no Option/config surface changed.

3. Architectural Soundness

3.1 Elegance of the Solution

Removing the unrelated cooperative-close change instead of trying to patch its ordering bug in place is the right call for this PR's scope — it's a precise, minimal way to close both of last round's blockers at once, and it leaves the actual savepoint-classification fix (getSavepointFailureException, isSavepointStartPreconditionFailure) as the clean, well-targeted, unit-tested change it's been since earlier rounds.

3.2 Maintainability

Smaller net diff than last round, with no new lifecycle-ordering surface to reason about. The retry test now consistently follows the file's own established "wait for real readiness, then force the flag" idiom across all six test methods, which will make the next person's diff against this file easier to reason about too.

3.3 Extensibility

Unchanged from prior rounds' assessment.

3.4 Historical-Version Compatibility

Fully compatible; no format/API/config break — re-confirmed for this round's sole change (a deletion of PR-local code).

4. Issue Summary

# Issue Location Severity Blocking Raised by another reviewer
1 (resolved this round) closeTaskAfterFailedCooperativeExecution() ran before taskDone() and only caught IOException, risking a stalled TaskGroup — method and all call sites removed TaskExecutionService.java — No (resolved) No
2 (resolved this round) cooperative-task-close production change unrelated to this PR's savepoint-hang scope, no dedicated test — removed from this PR's diff TaskExecutionService.java — No (resolved) No (first raised by me, 2026-08-18)
3 (moot) missing doc comment on closeTaskAfterFailedCooperativeExecution() — method no longer exists — — No No
4 (resolved this round) retry test's first readiness override not preceded by awaitCheckpointCoordinatorsReady() — added, all six test methods now consistent SavePointBusySourceTest.java — No (resolved) No
5 (carryover, resolved) Savepoint-classification logic, isSavepointStartPreconditionException() docs, CHECKPOINT_COORDINATOR_SHUTDOWN recognition, retry-succeeds test coverage, FakeSource* restore correctness, CheckpointManager API preservation various, all unchanged since 037ea4335 — No No (resolved)

5. Merge Recommendation

Conclusion: Ready to merge

Blockers — none remaining. Both High-severity blockers from my last round (the cooperative-close ordering bug and its unrelated, untested scope) are resolved by removing that change from this PR entirely — the cleanest possible fix, since it makes the concern moot rather than requiring new code to get right. The retry-succeeds test's residual TOCTOU risk is also closed.

Recommended fixes — none outstanding.

Reacting to the existing CHANGES_REQUESTED decision: I'm updating my own review state to reflect that both of my blockers are closed. The savepoint-classification logic that @nzw921rx, @davidzollo, @SEZ9, and I spent many rounds validating is unchanged and stands; this round only removed out-of-scope code and hardened one test. I don't see any other reviewer's open blocker on this exact head.

CI diagnosis: the fork's real run for this head (32271489557) shows unit-test (8, ubuntu-latest) and elasticsearch-connector-it (8, ubuntu-latest) as failure, and the other unit-test matrix legs as cancelled (fail-fast after the ubuntu-8 failure, not independent results). I traced both failures: the unit-test failure is a single unrelated telemetry/metrics assertion (EngineStateStoreLogicalMetricExportsTest, expected <2.0> but was <1.0>) in a class this PR never touches, and JobMasterTest/SavePointBusySourceTest — the classes this PR actually owns — both passed cleanly (10/10 and 7/7) within that same job run. The elasticsearch failure is in an unrelated E2E connector module. Neither is caused by this PR's diff. I'd still ask for a rerun to get one clean, complete, non-cancelled matrix before the final merge click, but I'm not holding the review on it given the traced root causes.

Overall assessment: this has been a long review cycle, and this round closes it out well — removing the unrelated production change instead of trying to salvage it in place was the right instinct, and it leaves a minimal, well-tested, backward-compatible fix for the original DOING_SAVEPOINT hang. Nice work getting this the rest of the way; from my side this is ready to merge once a full green CI run lands.

@SEZ9

SEZ9 commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator

Thanks @DanielLeens for the thorough from-scratch re-review of 2b840e976, and for confirming the retry-test ordering issue from your 037ea4335 review is now resolved.

To recap on that single point: the problem was that the retry case faked the checkpoint coordinator as ready immediately after the task entered RUNNING, so the second savepoint request could start before the real task-ready handshake completed, eventually failing the job on the 60s checkpoint timeout. The fix in 2b840e976 follows exactly the approach you suggested — SavePointBusySourceTest.java now calls awaitCheckpointCoordinatorsReady(jobMaster) to wait for the real coordinator to be ready before each setCheckpointCoordinatorsReady(jobMaster, false) injection, so the precondition failure is injected deterministically rather than racing the handshake. Glad your verification confirms both setCheckpointCoordinatorsReady(jobMaster, false) call sites are now guarded and that nothing else moved between 037ea43357f03827622196d26f85e1bff2680568 and 2b840e97663480e10bef169ac963a0ae6580dccb (+2/-27, with the TaskExecutionService.java change removed outright).

Given both of your approvals on the current head, I have no remaining code asks on this point. Only two housekeeping items before merge: please confirm the APPROVED state stands on 2b840e976 as the final head, and flag here if you'd like the two-commit history squashed on merge or kept as-is. Otherwise I'll proceed once you confirm.

Thanks again for the careful, byte-level re-verification — it made this round easy to close out.

@DanielLeens

Copy link
Copy Markdown
Contributor

Confirmed on both points:

  1. APPROVED stands on 2b840e97663480e10bef169ac963a0ae6580dccb. That is still the current head (I re-checked before writing this), no commit has landed since my second from-scratch re-review, and nothing in that review needs revisiting on this head. My approval is not conditional on anything further from the author's side.

  2. Squash vs. keep-as-is is not mine to call. Daniel's permission on this repository is read-only, so I don't have merge authority here regardless of preference. That decision belongs to whichever maintainer with write access performs the actual merge — happy to leave it to their judgment (or the project's usual convention) rather than expressing one myself.

One process note for whoever merges: reviewDecision on the PR is still showing CHANGES_REQUESTED overall, not because of anything outstanding on my side, but because it aggregates the latest state from every reviewer — @nzw921rx, @davidzollo, and your own 2026-07-20 review are still recorded as CHANGES_REQUESTED from earlier rounds and haven't been re-submitted as approvals against this head. Worth those reviewers doing a quick re-affirm (or a maintainer dismissing the stale ones) before this clears the actual merge gate, since my approval alone won't flip that flag.

@dybyte dybyte left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

+1 if CI passes. Thanks for the contribution.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks for the +1, @dybyte!

Quick status note since your approval was conditional on CI: as of right now, the Build check on the current head 2b840e97663480e10bef169ac963a0ae6580dccb is still failure (https://github.com/apache/seatunnel/runs/96156779577). No new commit has landed since my two APPROVED reviews on this head, so nothing has changed on my side — this is just a live-status update.

I'm not re-deriving the failing jobs from scratch in this note; my permission on this repository is read-only, so I can't trigger a rerun myself. The concrete next step is for @agarwalrahul2702 to rerun the failed jobs on the fork's Build run and confirm it goes green.

One more thing worth flagging so nobody is confused by the review summary: reviewDecision on this PR is still showing CHANGES_REQUESTED overall, but that's aggregating the earlier-round CHANGES_REQUESTED states from @nzw921rx, @davidzollo, and an early round from @SEZ9 that haven't been re-submitted as approvals against this head — it's not a new blocker from any of them on the current diff as far as I can tell. My own APPROVED conclusion isn't conditional on anything further from the source side.

@SEZ9

SEZ9 commented Aug 22, 2026

Copy link
Copy Markdown
Collaborator

Thanks @DanielLeens for the thorough from-scratch re-review on 2b840e97663480e10bef169ac963a0ae6580dccb — great to see both of your previous blockers confirmed resolved, with the TaskExecutionService.java change removed entirely and the test TOCTOU risk closed via the added awaitCheckpointCoordinatorsReady(jobMaster) calls in SavePointBusySourceTest.java. Your confirmation that the rest of the diff is byte-for-byte unchanged since your last round is much appreciated.

Thanks also @dybyte for the +1.

Remaining asks before merge:

  1. Per @DanielLeens's process note, the overall reviewDecision is still CHANGES_REQUESTED due to stale reviews from earlier rounds. I'll ask those reviewers to re-affirm against the current head, or a maintainer with write access can dismiss the stale reviews so this clears the merge gate.
  2. Per @dybyte's condition, we need CI to pass on the current head before merging.

Once those two are done, this should be good to go. Thanks all for the careful work on the stop-with-savepoint hang fix.

@nzw921rx nzw921rx left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

+1 LGTM good job🚀

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

+1
LGTM
Thanks for your contribution! This is a solid addition to the project, and your attention to detail really shows. Contributors like you are what keep this community moving forward. Feel free to keep the PRs coming — we're always glad to have you here!

Please ignore the following message if you have joined in the Slack~

To facilitate focused communication among contributors, we’ve created a brand-new dedicated #contributors channel in official Slack workspace.
Slack workspace link: https://s.apache.org/seatunnel-slack

This channel is designed for technical discussions, feature design brainstorming, roadmap sync and direct communication with project core Contributors. Everyone who contributes code, docs, test cases or community ideas is warmly invited to join, share thoughts and collaborate together under The Apache Way. Welcome to join 😄

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] [Zeta] stop-job with savepoint hangs in DOING_SAVEPOINT

7 participants