Skip to content

[Fix][Zeta] Stop checkpoint scheduler after terminal cleanup - #12149

Merged
davidzollo merged 7 commits into
apache:devfrom
CryoThrust:codex/seatunnel-12147
Nov 24, 2026
Merged

davidzollo merged 7 commits into
apache:devfrom
CryoThrust:codex/seatunnel-12147

Conversation

@CryoThrust

@CryoThrust CryoThrust commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

When a streaming job is canceled, checkpoint cleanup shuts down its scheduler and immediately creates a replacement. A late checkpoint callback can start a thread on that replacement after terminal cleanup, leaving a checkpoint-coordinator-* thread alive. This contribution to Apache SeaTunnel keeps non-reset cleanup shut down while preserving scheduler recreation through restoreCoordinator() for both ordinary pipeline restore and master failover.

Scheduler construction is shared so reset preserves tracing and remove-on-cancel behavior. Workers start lazily when tasks are scheduled. Late trigger/timeout scheduling tolerates rejection after shutdown, while any failure inside a scheduled trigger still fails the coordinator. Unit tests cover cancellation and reset separately; the streaming master-failover IT requires the recovered coordinator's scheduler to be both shut down and terminated after cancellation and before member shutdown.

Fixes #12147. No public API, configuration, state format or dependency changes. Synced with current dev (37309e1a8), including upstream SFTP fixture #13203 and TiDB readiness #13269; the PR diff remains the three checkpoint-related files.

Validation on JDK 11:

mvn -B -T1C -pl seatunnel-engine/seatunnel-engine-server -am -DskipTests install
mvn -B -pl seatunnel-engine/seatunnel-engine-server -Dtest=CheckpointCoordinatorTest test
mvn -B -pl seatunnel-engine/seatunnel-engine-server,seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base -DskipTests spotless:check verify
mvn -B -pl seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base \
  -DskipUT=true -DskipIT=false \
  '-Dit.test=CheckpointCoordinatorFailoverIT#testStreamJobContinuesAfterMasterFailover' verify

The dependency install and scoped Spotless/Checkstyle/packaging checks pass. All 19 CheckpointCoordinatorTest cases and the selected streaming failover IT pass without failures/errors/skips. The latter starts two real in-process members, recovers the streaming job after master shutdown and checks scheduler shutdown and worker termination after cancellation. The full integration matrix is not a local validation claim.

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

When a streaming job is cancelled or otherwise reaches a terminal state, CheckpointCoordinator.cleanPendingCheckpoint() shuts down its 2-thread checkpoint-coordinator-<pipelineId>/<jobId> ScheduledExecutorService via shutdownNow(), but then unconditionally created a brand-new, live replacement scheduler right afterward - even when the coordinator has truly finished and nothing will ever schedule work on it again. Those two freshly spawned, non-daemon threads then sit idle forever, since nothing calls shutdownNow() on this second instance for a terminal job - exactly what the e2e thread-leak check flagged in #12147: every job cancellation/completion permanently adds two more idle threads to the master JVM.

The fix centralizes scheduler creation into a createScheduler() helper and makes the post-shutdown recreation conditional: it now only recreates the scheduler when the close reason is CHECKPOINT_COORDINATOR_RESET (the master-failover-restart path, where restoreCoordinator() genuinely needs a live scheduler to keep running afterward); every other close reason (pipeline end, coordinator completed/shutdown, checkpoint-inside-error, aggregate-commit-error, etc.) now correctly leaves the scheduler shut down, matching the coordinator's own terminal state.

In one sentence: this stops leaking two non-daemon threads per pipeline on every job cancellation/completion, by making scheduler recreation conditional on the one close reason that actually still needs a live scheduler afterward.

1. Code Change Review

1.1 Core Logic Analysis

Before (inside cleanPendingCheckpoint):

scheduler.shutdownNow();
scheduler =
        Executors.newScheduledThreadPool(
                2,
                runnable -> {
                    Thread thread = new Thread(runnable);
                    thread.setName(
                            String.format("checkpoint-coordinator-%s/%s", pipelineId, jobId));
                    return thread;
                });

After:

scheduler.shutdownNow();
// A terminal coordinator must not create a replacement executor. Recreating it here
// leaves an idle checkpoint-coordinator thread alive after the job is cancelled or
// completed. A replacement is only needed when a master-failover reset restarts the
// coordinator.
if (closedReason == CheckpointCloseReason.CHECKPOINT_COORDINATOR_RESET) {
    scheduler = createScheduler();
}

with the identical thread-pool-construction logic extracted into a new createScheduler() helper also used by the constructor.

I traced every caller of cleanPendingCheckpoint to verify the conditional is correctly scoped:

  • cancelCheckpoint() (CheckpointCoordinator.java:1456) uses CheckpointCloseReason.PIPELINE_END - genuinely terminal, scheduler must stay down. Exercised by the new test.
  • restoreCoordinator(boolean alreadyStarted) (CheckpointCoordinator.java:684) uses CheckpointCloseReason.CHECKPOINT_COORDINATOR_RESET - this method explicitly sets shutdown = false right after calling cleanPendingCheckpoint and goes on to potentially call notifyCompleted/schedule further checkpoint work, so it genuinely needs a live scheduler afterward. This path is not left unguarded by tests even though this PR doesn't add a dedicated one: several pre-existing tests (e.g. CheckpointCoordinatorTest.java:566-567) call spy.restoreCoordinator(true) twice in a row wrapped in assertDoesNotThrow - if the scheduler were not correctly recreated on CHECKPOINT_COORDINATOR_RESET, the second call's downstream scheduling would throw RejectedExecutionException on the already-shutdown scheduler.
  • Every other CheckpointCloseReason (CHECKPOINT_COORDINATOR_COMPLETED, CHECKPOINT_COORDINATOR_SHUTDOWN, CHECKPOINT_INSIDE_ERROR, AGGREGATE_COMMIT_ERROR, TASK_NOT_ALL_READY_WHEN_SAVEPOINT, CHECKPOINT_NOTIFY_COMPLETE_FAILED, CHECKPOINT_EXPIRED) represents the coordinator genuinely ending - the fix correctly leaves the scheduler shut down for all of them.

Key Findings:

  1. Root cause is real and precisely identified: the old code always recreated a live ScheduledThreadPoolExecutor after shutdownNow(), regardless of whether the coordinator would ever use it again - a guaranteed 2-thread-per-terminal-coordinator leak, not a maybe.
  2. The fix's conditional is exhaustively correct against every CheckpointCloseReason value and every call site of cleanPendingCheckpoint - I did not find a reason that needs the scheduler back other than CHECKPOINT_COORDINATOR_RESET, nor a call site outside the two named above.
  3. createScheduler() extraction is a clean, behavior-preserving DRY refactor - I diffed the extracted body against the original constructor code line-by-line (same thread-name format, same setRemoveOnCancelPolicy(true), same MDCTracer.tracing(...) wrapping) and confirm no incidental behavior change.
  4. The scheduler = createScheduler() reassignment remains inside the same synchronized (lock) block that both the constructor's original assignment and the old code used - this PR does not change or weaken the existing synchronization discipline around the scheduler field.
  5. The new createScheduler() private method has no explanatory comment - see Issue 1 below.

Runtime path (job cancellation is the everyday case this hits, not a rare recovery branch):

Client cancel request -> JobMaster.cancelJob() -> PhysicalPlan.cancelJob()/stopJob()
    -> SubPlan cancellation -> eventually CheckpointCoordinator.cancelCheckpoint()   [CheckpointCoordinator.java:1451]
        -> cleanPendingCheckpoint(PIPELINE_END)                                     [CheckpointCoordinator.java:1456, 1165]
            synchronized(lock) {
                ... abort pending checkpoints, clear tracking structures ...
                scheduler.shutdownNow()                                             [CheckpointCoordinator.java:1206]
                closedReason != CHECKPOINT_COORDINATOR_RESET -> scheduler stays shut down (NEW)
            }
        -> updateStatus(CANCELED), checkpointCoordinatorFuture.complete(...)

Master-failover path (needs a live scheduler afterward):
Master failover -> JobMaster re-init -> CheckpointCoordinator.restoreCoordinator(true)  [CheckpointCoordinator.java:675]
    -> cleanPendingCheckpoint(CHECKPOINT_COORDINATOR_RESET)
        -> scheduler.shutdownNow(); scheduler = createScheduler()  [RESET branch: live scheduler restored]
    -> shutdown = false; ... continues scheduling checkpoints normally

1.2 Compatibility Impact

Fully compatible. No config option, public API, RPC/serialization format, or checkpoint/savepoint file format is touched. The only observable difference is that a terminated coordinator's internal thread pool now actually stays terminated - the bug being fixed, not a behavior any external caller could have depended on.

1.3 Performance / Side-Effect Analysis

This is a direct fix for a genuine, unconditional resource leak: 2 non-daemon threads leaked per pipeline, on every single job cancellation or completion, forever, for the life of the master JVM. At "trillion-record-per-day, hundred-billion-record-per-pipeline" scale with any meaningful job churn (recurring batch jobs, restarts, CI-style pipelines), this is a slow, monotonic thread-count/memory leak on the master node that would eventually degrade or crash the JVM (OutOfMemoryError: unable to create new native thread) under sustained job turnover - exactly the class of stability issue the strictest production lens calls for flagging, and the fix directly and completely closes it for every path I traced. One narrow residual note below (Issue 2) around a benign race window; it does not reintroduce any leak and is not itself a stability risk of comparable severity.

1.4 Error Handling and Logging

No change to log levels or messages for the primary fix. See Issue 2 below for a narrow, low-severity exception-surfacing nuance introduced by no longer keeping an always-live fallback scheduler around.

Issue 1: New createScheduler() helper has no explanatory comment

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/checkpoint/CheckpointCoordinator.java:275-286
  • Problem description: The extracted private ScheduledExecutorService createScheduler() method has no Javadoc/comment. It is a straightforward extraction of previously inline, also-uncommented code, so the bar is lower than for genuinely new logic, but this class otherwise carries detailed Javadoc on neighboring methods (e.g. cleanPendingCheckpoint's own Javadoc right above it), and a one-line comment here would make the RESET-only-recreation invariant this PR introduces easier to spot for a reader who only looks at this method in isolation.
  • Potential risk: Low - a readability/consistency nit.
  • Best improvement: Add a short comment, e.g. "Builds a new 2-thread checkpoint-coordinator scheduler; only ever called from the constructor or a CHECKPOINT_COORDINATOR_RESET cleanup."
  • Severity: Medium
  • Raised by another reviewer: No

Issue 2: Narrow race window can now surface a RejectedExecutionException where the old code silently no-op'd

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/checkpoint/CheckpointCoordinator.java:753-754 (and similarly :780), versus the shutdown/conditional-recreate at :1206/:1212.
  • Problem description: tryTriggerPendingCheckpoint() has two scheduleTriggerPendingCheckpoint(...) reschedule calls (around lines 753-754 and 780) that execute before the method's own synchronized (lock) { if (isCompleted() || isShutdown()) return; ... } guard (around lines 783-793). If cleanPendingCheckpoint runs concurrently on another thread between the time this method reads its pre-lock state and the time it reaches one of those two early scheduleTriggerPendingCheckpoint calls, it will now call .schedule() on a scheduler that cleanPendingCheckpoint has just shutdownNow()'d and (for a terminal reason) not replaced. Before this PR, that exact race silently succeeded, because the field was always reassigned to a fresh, running executor regardless of reason - so the old code masked this race by always keeping a live (if leaked) scheduler around.
  • Potential risk: Low. ScheduledThreadPoolExecutor.schedule() on a shutdown executor throws RejectedExecutionException (default AbortPolicy), which would propagate out of tryTriggerPendingCheckpoint() uncaught. Since this can only happen in the narrow window where the coordinator is concurrently transitioning to terminal anyway, the practical effect is an extra stack trace in the logs during an already-happening cancellation/completion, not a data-correctness or availability issue. The two calls that already sit inside synchronized (lock) (around lines 780 and 804) are fully race-free against cleanPendingCheckpoint, since they share the same lock; only the two calls that execute before entering the lock are exposed.
  • Best improvement: Option A (minimal): wrap the pre-lock scheduleTriggerPendingCheckpoint call sites' underlying scheduler.schedule(...) in a try/catch for RejectedExecutionException and log at DEBUG/INFO ("coordinator already shutting down, skip reschedule") instead of letting it propagate. Option B (larger refactor, not required for this PR): move the interval/min-pause early-return checks inside the same synchronized (lock) block used later in the method, eliminating the pre-lock window entirely - a bigger diff than necessary for the thread-leak fix this PR targets.
  • Severity: Low
  • Raised by another reviewer: No

2. Code Quality Assessment

2.1 Coding Standards

The refactor is a faithful, line-for-line extraction with no incidental changes, and the now-unused java.util.concurrent.Executors import is correctly removed. See Issue 1 above for the one missing-comment gap on the new helper method.

2.2 Test Coverage and Test Stability

CheckpointCoordinatorTest.testCancelDoesNotRecreateScheduler (CheckpointCoordinatorTest.java:980-1000) directly targets the fixed regression: it calls coordinator.cancelCheckpoint().join() (a PIPELINE_END close reason, genuinely terminal) and asserts scheduler.isShutdown() via reflection. cancelCheckpoint() completes checkpointCoordinatorFuture synchronously before returning, so .join() is non-blocking and deterministic - no sleeps, no timing assumptions, no shared static state.

Test stability rating: Stable.

Coverage gap: there is no new, dedicated test asserting the opposite branch - that CHECKPOINT_COORDINATOR_RESET still leaves a live, schedulable executor behind. As Key Finding 2 above notes, this is indirectly covered by several pre-existing tests that call restoreCoordinator(true) twice in a row under assertDoesNotThrow, which would fail if the RESET branch stopped recreating the scheduler - so this is a Low-severity, non-blocking gap, but an explicit assertion (e.g. assertFalse(scheduler.isShutdown()) after a restoreCoordinator(true) call) would make the "RESET still needs a live scheduler" half of this PR's invariant self-evidently tested rather than only incidentally covered.

2.3 Documentation Updates

Not applicable - internal-only fix, no user-visible behavior or config change.

3. Architectural Soundness

3.1 Elegance of the Solution

Clean, minimal, and correctly scoped to the one enum value (CHECKPOINT_COORDINATOR_RESET) that actually needs the old unconditional-recreate behavior. The createScheduler() extraction is a nice side benefit, removing duplicated thread-pool-construction code between the constructor and cleanPendingCheckpoint.

3.2 Maintainability

Improves maintainability: the "when do we need a live scheduler" decision is now a single, explicit if condition instead of an implicit "we always did it, so it must be fine" pattern. Issue 1's comment would make this even clearer.

3.3 Extensibility

If a future CheckpointCloseReason is ever added that also needs the scheduler kept alive, the if condition is the one obvious place to extend (e.g. to a small EnumSet, mirroring the pattern used elsewhere in this same review batch for a similar problem, if a second such reason ever appears).

3.4 Historical-Version Compatibility

No impact - this is a pure resource-lifecycle fix internal to a single JVM process; it does not touch checkpoint/savepoint file formats, serialized job state, or any cross-version wire protocol. A job restored/upgraded from an older version behaves identically from the outside; only the leaked-thread accounting on the master node improves.

4. Issue Summary

Number Issue Location Severity
1 New createScheduler() helper has no explanatory comment CheckpointCoordinator.java:275 Medium
2 Narrow race can surface RejectedExecutionException on concurrent terminal cleanup vs. in-flight reschedule (previously silently absorbed by the always-live fallback scheduler) CheckpointCoordinator.java:753-754, :780 Low

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers - must be fixed (sorted by severity)
    • None. Both issues above are non-blocking nits.
  2. Recommended fixes - non-blocking
    • Issue 1: add a short comment to createScheduler().
    • Issue 2: optionally guard the two pre-lock scheduleTriggerPendingCheckpoint calls against RejectedExecutionException for cleaner logs during concurrent cancellation (does not affect correctness of the leak fix).
    • Optional: add an explicit assertion that CHECKPOINT_COORDINATOR_RESET leaves a live scheduler, to make that half of the invariant self-evidently tested rather than only incidentally covered by existing restoreCoordinator tests.

CI diagnosis: The Build check shows fail; dereferencing the apache-side pointer to the fork's actual run (CryoThrust/seatunnel run 34036117776), three jobs failed: unit-test (8, ubuntu-latest) failed on a Maven Central network flake resolving connector-pulsar's netty-handler:4.1.73.Final (Connection reset - it never even got to running a test), doris-connector-it failed 1 of 49 tests in DorisIT, and rocketmq-connector-it failed with the same RocketMqIT container-timing flake seen across this PR batch. None of these relate to the changed file (CheckpointCoordinator.java, seatunnel-engine-server only). Recommend the author sync with dev (17 commits behind) and re-run.

Overall assessment: This closes a real, unconditional, per-cancellation thread leak that the project's own e2e thread-leak check caught (#12147) - I verified the leak is genuine, not a false positive, by tracing every CheckpointCloseReason and every call site of cleanPendingCheckpoint, and confirmed the one legitimate exception (CHECKPOINT_COORDINATOR_RESET, the master-failover-restart path) is still correctly handled. The two issues raised are minor: a documentation nit and a narrow, low-severity race window that the fix incidentally exposes as an exception instead of a silent leak, rather than introduces as a new problem. Good fix, safe to merge once CI is green on an unrelated-failure rerun.

@CryoThrust

Copy link
Copy Markdown
Contributor Author

Rebased onto current dev. The only conflict was in CheckpointCoordinatorTest: an unrelated test (testDuplicateSchemaChangeAfterCheckpointCompletionIsIgnored) landed in the same spot, so I kept both it and this PR's testCancelDoesNotRecreateScheduler. The fix is unchanged.

CheckpointCoordinatorTest: 16 run, 0 failures.

@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, @CryoThrust — I re-reviewed from scratch against the current head (8fea514).

Quick note on process: this is not a new fix, it's a rebase. I diffed the current head against the version I reviewed on 2026-09-07 and the CheckpointCoordinator.java/CheckpointCoordinatorTest.java changes are line-for-line identical in logic to what I reviewed before — only the git history changed (rebased onto current dev, with the merge conflict in CheckpointCoordinatorTest resolved by keeping both testDuplicateSchemaChangeAfterCheckpointCompletionIsIgnored and this PR's testCancelDoesNotRecreateScheduler, exactly as your comment above describes). So this consolidated review re-confirms my prior findings against the current line numbers and adds some additional call-chain verification I did this pass.

What Problem Does This PR Solve?

  • User pain point: CheckpointCoordinator.cleanPendingCheckpoint() always spun up a brand-new, live 2-thread checkpoint-coordinator-<pipelineId>/<jobId> scheduler right after shutdownNow(), even for genuinely terminal close reasons (job cancel/complete/error). Nothing ever shuts that replacement down for a terminal coordinator, so every job cancellation/completion permanently leaks 2 non-daemon threads on the master — exactly what the e2e thread-leak check in #12147 caught.
  • Fix approach: Extract the thread-pool construction into a createScheduler() helper, and only call it again post-shutdown when closedReason == CheckpointCloseReason.CHECKPOINT_COORDINATOR_RESET (the master-failover-restart path via restoreCoordinator(), which explicitly un-shuts-down afterward and keeps scheduling).
  • One-sentence summary: Stops leaking two idle threads per pipeline on every job cancel/complete by only recreating the checkpoint scheduler for the one close reason that still needs a live one.

1. Code Change Review

1.1 Core Logic Analysis

CheckpointCoordinator.java:1206-1212 (inside cleanPendingCheckpoint, still inside the same synchronized (lock) block as before — no change to locking discipline):

scheduler.shutdownNow();
// A terminal coordinator must not create a replacement executor. Recreating it here
// leaves an idle checkpoint-coordinator thread alive after the job is cancelled or
// completed. A replacement is only needed when a master-failover reset restarts the
// coordinator.
if (closedReason == CheckpointCloseReason.CHECKPOINT_COORDINATOR_RESET) {
    scheduler = createScheduler();
}

createScheduler() at CheckpointCoordinator.java:275-286 is a faithful, byte-for-byte extraction of the previously-inline constructor logic (same ScheduledThreadPoolExecutor(2, ThreadFactory), same thread naming, same setRemoveOnCancelPolicy(true), same MDCTracer.tracing(...) wrap) — used both by the constructor (:229) and by the RESET branch above.

I independently re-traced every path that can reach cleanPendingCheckpoint on this head (not just the two named in my last review), to make sure the RESET-only condition is exhaustively correct:

  • cancelCheckpoint() → PIPELINE_END (:1456) — terminal, scheduler correctly stays down. Directly covered by the new test.
  • restoreCoordinator(boolean) → CHECKPOINT_COORDINATOR_RESET (:684) — sets shutdown = false right after and continues scheduling; correctly recreates.
  • notifyCompleted(...) completion path → CHECKPOINT_COORDINATOR_COMPLETED (:1380) — terminal, correctly stays down.
  • handleCoordinatorError(CheckpointCloseReason, Throwable) (:344), reached from 8 call sites (:330, :486, :522, :925, :933, :963, :969, :1023) plus the dynamic-reason overload at :339/:359 — I checked every one of these 8+1 call sites individually and every single one passes a hard-coded terminal reason: CHECKPOINT_INSIDE_ERROR, CHECKPOINT_NOTIFY_COMPLETE_FAILED, or CHECKPOINT_EXPIRED. None ever passes CHECKPOINT_COORDINATOR_RESET, so the error-handling fan-in is safe under the new conditional too — this closes a gap my last review left implicit ("I did not find a reason that needs the scheduler back other than RESET") with an actual enumerated trace.
  • Every remaining CheckpointCloseReason value (CHECKPOINT_COORDINATOR_SHUTDOWN, AGGREGATE_COMMIT_ERROR, TASK_NOT_ALL_READY_WHEN_SAVEPOINT) is either unused as a direct cleanPendingCheckpoint argument or falls through the same terminal path — none require the scheduler back.

Runtime path (job cancellation — the everyday case, not a rare recovery branch):

Client cancel -> JobMaster.cancelJob() -> ... -> CheckpointCoordinator.cancelCheckpoint()  [:1450]
    -> cleanPendingCheckpoint(PIPELINE_END)                                                [:1456 -> :1166]
        synchronized(lock) {
            ... abort pending checkpoints, clear tracking maps ...
            scheduler.shutdownNow()                                                        [:1206]
            closedReason != CHECKPOINT_COORDINATOR_RESET -> scheduler left shut down (fix)  [:1211-1212]
        }
    -> updateStatus(CANCELED), checkpointCoordinatorFuture.complete(...)

Master-failover path (needs a live scheduler afterward):
Master failover -> JobMaster re-init -> CheckpointCoordinator.restoreCoordinator(true)      [:675]
    -> cleanPendingCheckpoint(CHECKPOINT_COORDINATOR_RESET)
        -> scheduler.shutdownNow(); scheduler = createScheduler()   [RESET branch: replacement restored]
    -> shutdown = false; ... resumes normal checkpoint scheduling

Key Findings (all reconfirmed against the current head, plus one new item):

  1. Root cause is real and precisely identified — this was a guaranteed, unconditional 2-thread leak per terminal coordinator, not a maybe.
  2. The RESET-only conditional is exhaustively correct against every CheckpointCloseReason and every direct/indirect call site of cleanPendingCheckpoint, including the handleCoordinatorError fan-in I traced this round.
  3. createScheduler() extraction is behavior-preserving; no incidental changes.
  4. The reassignment stays inside the pre-existing synchronized (lock) block — no weakening of synchronization.
  5. createScheduler() still has no explanatory comment (Issue 1, unaddressed since last review).
  6. New this round: the pre-lock race described in my last review's Issue 2 (scheduleTriggerPendingCheckpoint calling scheduler.schedule(...) before entering synchronized (lock) in tryTriggerPendingCheckpoint) is not the only instance — startTriggerPendingCheckpoint's checkpoint-timeout scheduling at :985 (scheduler.schedule(() -> ... handleCoordinatorError(CHECKPOINT_EXPIRED, null) ...)) also runs with no lock held. Same class of pre-existing, PR-exposed-not-introduced race; see Issue 2 below.

1.2 Compatibility Impact

Fully compatible. No config, public API, RPC/serialization format, or checkpoint/savepoint file format is touched. The only observable difference is that a terminated coordinator's thread pool now actually stays terminated.

1.3 Performance / Side-Effect Analysis

Direct fix for a genuine, unconditional resource leak — 2 non-daemon threads leaked per pipeline on every job cancellation/completion, forever, for the life of the master JVM. At sustained job-churn scale this is exactly the kind of slow monotonic thread/memory leak that can eventually produce OutOfMemoryError: unable to create new native thread on the master. The fix closes it completely for every path traced above.

1.4 Error Handling and Logging

No log-level/message changes for the core fix. See Issue 2 for the narrow exception-surfacing nuance.

Issue 1: createScheduler() helper still has no explanatory comment

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/checkpoint/CheckpointCoordinator.java:275-286
  • Problem description: The extracted private ScheduledExecutorService createScheduler() has no Javadoc/comment, unlike neighboring methods in this class (e.g. cleanPendingCheckpoint's own Javadoc). It's a faithful extraction of previously-uncommented inline code, so the bar is lower than for new logic, but a one-line comment would make the "only called from the constructor or a RESET cleanup" invariant self-evident to a reader looking at this method in isolation.
  • Potential risk: Low — readability/consistency nit only.
  • Best improvement: e.g. // Builds a fresh 2-thread checkpoint-coordinator scheduler; only called from the constructor or a CHECKPOINT_COORDINATOR_RESET cleanup.
  • Severity: Medium
  • Raised by another reviewer: No (carried forward from my 2026-09-07 review; unaddressed, still valid on current head)

Issue 2: Pre-lock scheduler.schedule(...) calls can now surface RejectedExecutionException instead of silently no-op'ing, on concurrent terminal cleanup

  • Location: CheckpointCoordinator.java:760, :780 (both inside tryTriggerPendingCheckpoint, before the synchronized (lock) block starting at :785), and additionally CheckpointCoordinator.java:985 (startTriggerPendingCheckpoint's checkpoint-timeout scheduler.schedule(...), also called with no lock held) — versus the shutdown/conditional-recreate at :1206/:1211.
  • Problem description: If cleanPendingCheckpoint runs concurrently on another thread and reaches scheduler.shutdownNow() between the time one of these three call sites reads pre-lock state and the time it actually invokes scheduler.schedule(...), that call now hits an already-shutdown, not-replaced (for a terminal reason) executor. Before this PR, the old unconditional recreate meant this exact race always silently succeeded on a fresh live executor — so the old code masked the race entirely; this PR doesn't introduce the race, it removes the accidental mask.
  • Potential risk: Low. ScheduledThreadPoolExecutor.schedule() on a shutdown executor throws RejectedExecutionException (default AbortPolicy) synchronously at the call site. For the two tryTriggerPendingCheckpoint call sites (:760, :780), that call runs inside a Runnable previously submitted via scheduler.schedule(...) itself and never joined — with the default ScheduledThreadPoolExecutor and no custom afterExecute/UncaughtExceptionHandler here, an exception thrown from a non-periodic scheduled Runnable whose Future nobody calls .get() on is swallowed silently (no stack trace logged at all) rather than producing "an extra stack trace in the logs" as I described in my last review — I want to correct that detail now that I traced it more carefully; it doesn't change the severity, if anything it's slightly better (no log noise) but slightly worse for debuggability (the skipped reschedule is invisible). The :985 call site is invoked synchronously from startTriggerPendingCheckpoint, itself called from a whenCompleteAsync continuation on executorService (not scheduler), so a RejectedExecutionException there would propagate out of that continuation and similarly be swallowed by the async-completion machinery unless something upstream logs it. Either way: no data-correctness or availability impact, only a possible silently-dropped reschedule/timeout-arm during an already-in-flight cancellation, which is harmless since the coordinator is terminating anyway.
  • Best improvement: Option A (minimal, matches the scope of this PR): wrap the three scheduler.schedule(...) call sites in a try/catch (RejectedExecutionException) and log at DEBUG ("coordinator already shutting down, skip reschedule/timeout-arm"). Option B (larger, not required here): move the interval/min-pause early-return checks in tryTriggerPendingCheckpoint inside the same synchronized (lock) block used later in the method, eliminating the pre-lock window entirely.
  • Severity: Low
  • Raised by another reviewer: No (carried forward and extended from my 2026-09-07 review — same underlying race, one additional call site identified this round)

2. Code Quality Assessment

2.1 Coding Standards

Faithful, line-for-line extraction; the now-unused java.util.concurrent.Executors import is correctly removed from the main file. See Issue 1 for the one missing-comment gap.

2.2 Test Coverage and Test Stability

CheckpointCoordinatorTest.testCancelDoesNotRecreateScheduler (CheckpointCoordinatorTest.java:1021-1041 on current head) calls coordinator.cancelCheckpoint().join() (a PIPELINE_END/terminal close reason) and asserts scheduler.isShutdown() via the same ReflectionUtils.getField pattern already used elsewhere in this test class (e.g. :576, :868). cancelCheckpoint() completes checkpointCoordinatorFuture synchronously before returning, so .join() is non-blocking and deterministic — no sleeps, no timing assumptions.

Test stability rating: Stable.

Coverage gap (unchanged from last review): no dedicated new test asserts the opposite branch — that CHECKPOINT_COORDINATOR_RESET still leaves a live, schedulable executor. This is indirectly covered by pre-existing tests that call restoreCoordinator(true) twice in a row under assertDoesNotThrow (would fail with RejectedExecutionException if RESET stopped recreating), so this remains a Low-severity, non-blocking gap rather than a real hole.

Per the author's rebase comment, CheckpointCoordinatorTest: 16 run, 0 failures locally — consistent with what I'd expect given the logic is unchanged from what I already reviewed.

2.3 Documentation Updates

Not applicable — internal-only fix, no user-visible behavior or config change.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix. Minimal, correctly scoped to the one CheckpointCloseReason value that legitimately needs the old unconditional-recreate behavior. createScheduler() extraction is a clean side benefit removing duplicated thread-pool-construction code.

3.2 Maintainability

Improves maintainability — the "when do we need a live scheduler" decision is now one explicit condition instead of an implicit always-recreate pattern. Issue 1's comment would make it self-documenting.

3.3 Extensibility

If a future CheckpointCloseReason ever needs the scheduler kept alive too, the single if is the obvious extension point.

3.4 Historical-Version Compatibility

No impact — pure resource-lifecycle fix internal to a single JVM process; doesn't touch checkpoint/savepoint file formats, serialized job state, or any cross-version wire protocol. A job restored/upgraded from an older version behaves identically from the outside.

4. Issue Summary

Number Issue Location Severity
1 createScheduler() helper has no explanatory comment CheckpointCoordinator.java:275-286 Medium
2 Pre-lock scheduler.schedule(...) calls can surface RejectedExecutionException (now silently swallowed rather than logged) during concurrent terminal cleanup — three call sites: :760, :780, :985 CheckpointCoordinator.java:760,780,985 Low

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers — must be fixed
    • None. Both issues above are non-blocking nits, unchanged in substance from my last review.
  2. Recommended fixes — non-blocking
    • Issue 1: add a short comment to createScheduler().
    • Issue 2: optionally wrap the three pre-lock scheduler.schedule(...) call sites (:760, :780, :985) in a try/catch (RejectedExecutionException) with a DEBUG log, for cleaner behavior during concurrent cancellation. Does not affect correctness of the leak fix itself.
    • Optional: add an explicit assertion that CHECKPOINT_COORDINATOR_RESET leaves a live scheduler, so that half of the invariant is self-evidently tested rather than only incidentally covered by existing restoreCoordinator tests.

CI / upstream-sync diagnosis (live, as of this review): mergeable_state is blocked but mergeable: true (no merge conflict — dev is only 1 commit ahead since the rebase moments ago, trivially resyncable, not a real divergence concern). The current head (8fea514e) was just pushed (rebase) and its Build check is still queued/in_progress on both the apache-side pointer and the fork's own Actions run (CryoThrust/seatunnel run 34812493711) — no result yet, so I can't confirm green on this exact SHA yet. For context, the previous SHA's fork run (34036117776, pre-rebase) failed on unit-test (8, ubuntu-latest) (Maven Central network flake resolving connector-pulsar's netty-handler:4.1.73.Final), doris-connector-it (1/49 DorisIT failure), and rocketmq-connector-it (known container-timing flake) — none of which touch CheckpointCoordinator.java or seatunnel-engine-server, so those were environmental, not code-side. Please re-run/confirm once the current SHA's CI completes.

Overall assessment: This closes a real, unconditional, per-cancellation thread leak that the project's own e2e thread-leak check caught (#12147). I re-traced every CheckpointCloseReason and every direct and indirect (handleCoordinatorError fan-in) call site of cleanPendingCheckpoint against the current head and found the RESET-only condition exhaustively correct — nothing new or regressed since my last review, this is a straight rebase with the fix logic byte-for-byte unchanged. The two outstanding issues are the same minor, non-blocking ones from before (a documentation nit and a narrow, low-severity pre-existing race that this PR exposes as a silent no-op instead of a silent leak, rather than introduces). Good fix — safe to merge once CI is confirmed green on this SHA.

@CryoThrust

Copy link
Copy Markdown
Contributor Author

A note on the failing Build check, in case it shows up in review.

It is not this change. Every unit-test job passes; the failures are the connector-v2, transform-v2, rocketmq and engine-v2 integration suites, several of which touch no code this branch goes near (the branch changes only CheckpointCoordinator.java and its test). The same Build failure appears on my other open seatunnel PRs (#12149, #12101, #12051), which change different files, and on at least one unrelated contributor's PR (#12315) — while pushes to dev build green. That points at a fork-side/infrastructure problem rather than the diff.

Locally the affected area is green:

CheckpointCoordinatorTest  16 run, 0 failures

If the check stays red when it is reviewed, -DskipIT=true on the relevant suite would confirm the same result, but I did not want to push an empty commit purely to re-trigger CI without asking.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks for the heads-up, @CryoThrust — I checked this independently against the fork's actual run for 8fea514e (run 34812493711) rather than taking the summary at face value, and your diagnosis holds up. Breaking down what's actually failing:

  • engine-v2-it (both JDKs): the two real test errors are BackpressureSlowSinkIT.testCheckpointsKeepCompletingUnderSustainedBackpressure (ConditionTimeout) and SplitClusterFaultToleranceIT.testStreamJobCancelResolvesWhenWorkerCrashesBeforeCancelAck (ConditionTimeout). Both are known, independently-root-caused dev-level flakes unrelated to CheckpointCoordinator.java's scheduler-stop-after-cleanup change — BackpressureSlowSinkIT is a source checkpoint-lock starvation issue in the reader poll loop, and SplitClusterFaultToleranceIT's cancel test is a pre-existing ~70% flake around CancelTaskOperation acking before a worker-loss is detected. Neither touches checkpoint-scheduler shutdown/cleanup.
  • all-connectors-it-2: OpengaussCDCIT failing — this is a currently-tracked dev-level CDC schema-restore regression (unrelated to Zeta's checkpoint coordinator), already has a fix in flight upstream.
  • rocketmq-connector-it: RocketMqIT with 14 failures/29 errors — matches the same "known container-timing flake" signature I called out in my last review on this exact PR (the pre-rebase run also failed there for unrelated reasons).
  • all-connectors-it-7: S3FileConnectDryRunIT failing — this one's worth flagging specifically: the fix for it (MinIO Docker Hub image was pulled/replaced, breaking the dry-run test's container) merged into dev as 0d9f9e2303d at 2026-09-14T22:54:40Z — a few hours after your rebase (8fea514e was pushed at 06:07:08Z the same day). Your branch is now 9 commits behind dev (compare dev...8fea514e → behind_by: 9, status: diverged). Syncing to latest dev and rerunning CI should clear this specific lane.

So: three of the four failing lanes are pre-existing/tracked dev-side issues a sync won't change (they're flaky/regressed independent of what commit you're on), and the fourth (all-connectors-it-7/S3) has a real fix already on dev that a sync would pick up. Given mergeable: true (no actual conflicts, just a routine 9-commit drift), I'd suggest going ahead and syncing — it'll get you a cleaner signal on all-connectors-it-7 and won't hurt the others. No need for the empty-commit workaround.

To be clear, this doesn't change anything about the review itself: my "Ready to merge after fixes" conclusion from the last round stands (the two non-blocking items — the Javadoc nit and the pre-existing race note), and I already independently corroborated on the pre-rebase SHA that none of the environmental failures touch seatunnel-engine-server. Once the synced head's CI settles, ping me and I'll do a final pass on that SHA.

@CryoThrust
CryoThrust force-pushed the codex/seatunnel-12147 branch from 8fea514 to b70026e Compare September 16, 2026 07:41
@CryoThrust

Copy link
Copy Markdown
Contributor Author

@DanielLeens thanks for breaking those lanes down — that was more precise than my own summary, and it is what I acted on.

Synced as you suggested. b70026e63 is now rebased onto b37af3a9b (dev), a fast-forward with no conflicts (the diff is unchanged: CheckpointCoordinator.java + its test). The branch had drifted to 18 commits behind by the time I did it, so all-connectors-it-7/S3 should now pick up 0d9f9e2303d.

Rebuilt and ran the affected area on the synced head:

CheckpointCoordinatorTest  17 run, 0 failures

(17 rather than 16 because dev picked up an extra test in that class since my last run.)

The two non-blocking items from your earlier review are unchanged and still outstanding by design: the NOT_STARTED_STATUSES Javadoc nit is in, and the pre-existing check-then-act race is deliberately not folded in here — it is tracked as #12342 so it does not get lost. I'll ping you once the synced head's CI settles, per your last line.

Three items from review of the terminal-cleanup scheduler fix:

- document createScheduler(), including that only a CHECKPOINT_COORDINATOR_RESET
  cleanup may replace a shut-down scheduler
- guard the underlying scheduler.schedule in scheduleTriggerPendingCheckpoint
  against RejectedExecutionException: callers that run before taking the lock
  can race a concurrent terminal cleanup, which now leaves the scheduler shut
  down instead of silently replacing it, and the coordinator is ending anyway
- pin the RESET half of the invariant with an explicit assertion that a
  coordinator reset leaves a live scheduler, rather than relying on unrelated
  restoreCoordinator tests to trip over it
@CryoThrust

Copy link
Copy Markdown
Contributor Author

@DanielLeens correction to my previous comment first: I described the two non-blocking items as "the NOT_STARTED_STATUSES Javadoc nit and the pre-existing race" — that was #12156's list, not this PR's. Yours here were the createScheduler() comment (Issue 1) and the pre-lock RejectedExecutionException window (Issue 2). Both are now done in 6741ec1fe, along with the optional assertion.

Issue 1 — createScheduler() now carries a comment saying it builds a live 2-thread scheduler and that only a CHECKPOINT_COORDINATOR_RESET cleanup may replace a shut-down one, so the RESET-only invariant is visible to a reader who opens that method alone.

Issue 2 — option A. I guarded the underlying scheduler.schedule(...) in scheduleTriggerPendingCheckpoint rather than the individual call sites, so both the pre-lock and the in-lock callers are covered by one guard. On rejection it logs and skips the reschedule, with the reasoning in a comment: the only way to reach it is losing the race to a terminal cleanup, and the coordinator is ending anyway.

Optional assertion — testResetRecreatesLiveScheduler calls restoreCoordinator(true) and asserts the scheduler is not shut down, so the RESET half of the invariant is explicitly tested rather than incidentally covered by the existing double-restoreCoordinator tests.

Synced head is now 6741ec1fe on top of b37af3a9b:

CheckpointCoordinatorTest  18 run, 0 failures

Ping me if the synced CI still shows anything and I'll dig in.

@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 follow-up, @CryoThrust. I re-reviewed from scratch against the current head (6741ec1fe), which addresses the two non-blocking items from my last round plus a new commit. Full re-review below, not a diff-only pass.

What Problem Does This PR Solve?

CheckpointCoordinator.cleanPendingCheckpoint() used to call scheduler.shutdownNow() and then unconditionally spin up a brand-new, live 2-thread checkpoint-coordinator-<pipelineId>/<jobId> scheduler, even for genuinely terminal close reasons (job cancel/complete/error). Nothing ever shuts that replacement down for a terminal coordinator, so every job cancellation/completion permanently leaked 2 non-daemon threads on the master JVM — the leak the e2e thread-leak check in #12147 caught. The fix extracts a createScheduler() helper and only calls it again after shutdown when closedReason == CheckpointCloseReason.CHECKPOINT_COORDINATOR_RESET (the master-failover path via restoreCoordinator(), which explicitly un-shuts-down and keeps scheduling afterward). The new commit (6741ec1fe) is a targeted follow-up to my two prior review rounds: it documents createScheduler(), guards scheduleTriggerPendingCheckpoint's scheduler.schedule(...) against RejectedExecutionException, and adds an explicit test for the RESET-recreates-a-live-scheduler half of the invariant.

1. Code Change Review

1.1 Core Logic Analysis

Core fix, unchanged in logic since my first review (CheckpointCoordinator.java:1273-1280, inside the same pre-existing synchronized (lock) block that started at :1236):

scheduler.shutdownNow();
// A terminal coordinator must not create a replacement executor. Recreating it here
// leaves an idle checkpoint-coordinator thread alive after the job is cancelled or
// completed. A replacement is only needed when a master-failover reset restarts the
// coordinator.
if (closedReason == CheckpointCloseReason.CHECKPOINT_COORDINATOR_RESET) {
    scheduler = createScheduler();
}

I re-traced every CheckpointCloseReason and every direct/indirect (handleCoordinatorError fan-in) call site of cleanPendingCheckpoint again on this head; nothing has moved since my 2026-09-14 pass and the RESET-only condition is still exhaustively correct. Since the runtime path and root-cause analysis have not changed, I won't repeat the full trace a third time — see my prior two reviews for the line-by-line call-chain verification. scheduler.shutdownNow() and the conditional recreate stay atomic with respect to every other lock-holding accessor of the scheduler field, so there is no TOCTOU within cleanPendingCheckpoint itself: shutdown-and-decide-whether-to-recreate happens as one indivisible step under lock. ScheduledThreadPoolExecutor.shutdownNow() is idempotent (calling it twice is a safe no-op per the JDK contract), so a hypothetical double-cleanup is not a correctness concern either.

Issue 1 from my prior reviews is now resolved. createScheduler() (CheckpointCoordinator.java:289-308) now carries a doc comment:

/**
 * Builds a live 2-thread scheduler for this coordinator.
 *
 * <p>Only called from the constructor and from a {@code CHECKPOINT_COORDINATOR_RESET} cleanup:
 * a terminal coordinator must not get a replacement scheduler, or its threads outlive the job.
 */

This correctly states the invariant this PR introduces. Verified as a faithful extraction, byte-for-byte identical to the prior inline construction — no incidental behavior change.

Issue 2 from my prior reviews (the pre-lock/no-lock RejectedExecutionException race I traced to three call sites: old-head :760, :780, :985) is now only partially resolved — 2 of 3 sites are fixed, the third is not.

What the new commit did (CheckpointCoordinator.java:557-577):

protected void scheduleTriggerPendingCheckpoint(
        CheckpointType checkpointType, long delayMills) {
    try {
        scheduler.schedule(
                () -> tryTriggerPendingCheckpoint(checkpointType),
                delayMills,
                TimeUnit.MILLISECONDS);
    } catch (RejectedExecutionException e) {
        // A concurrent terminal cleanup shuts the scheduler down and, for a terminal close
        // reason, does not replace it. ...
        LOG.info(...);
    }
}

This is actually a smarter fix than a literal 3-site patch: by centralizing the guard inside scheduleTriggerPendingCheckpoint itself, it covers every caller of that method — not just the two I originally named (old :760/:780, now tryTriggerPendingCheckpoint's calls at :798/:818/:842/:852), but also the schema-change reschedule calls at :1595, :1610, :1633 that I hadn't individually enumerated. All of those are now safe against a concurrent terminal cleanup: worst case, a RejectedExecutionException is caught and logged at INFO instead of propagating or being silently dropped.

What it did not cover: the checkpoint-timeout watchdog scheduling in startTriggerPendingCheckpoint (CheckpointCoordinator.java:1051-1070, old-head :985) still calls scheduler.schedule(...) directly, with no try/catch:

pendingCheckpoint.setCheckpointTimeOutFuture(
        scheduler.schedule(
                () -> { ... handleCoordinatorError(CheckpointCloseReason.CHECKPOINT_EXPIRED, null); ... },
                checkpointTimeout,
                TimeUnit.MILLISECONDS));

This call structurally can't be covered by the scheduleTriggerPendingCheckpoint guard, because it isn't a "reschedule the next checkpoint" call — it arms a per-checkpoint timeout watchdog, a different scheduler.schedule(...) call site entirely. And the race window here is materially wider than the two now-fixed sites: this code runs inside startTriggerPendingCheckpoint's pendingCompletableFuture.thenAccept(...) continuation (:982), which is reached through createPendingCheckpoint() -> triggerPendingCheckpoint()'s idFuture.thenApplyAsync(..., executorService).thenApplyAsync(..., executorService) chain (:1107-1147) — i.e. it runs asynchronously on an executorService worker thread, not the thread that was holding lock when startTriggerPendingCheckpoint was originally invoked from inside tryTriggerPendingCheckpoint's synchronized (lock) block (:849) or startSavepoint's (:927). By the time this lambda runs, the coordinator may have already gone through an entire barrier-trigger-and-wait-for-ACK round trip (CompletableFuture.allOf(completableFutureArray).get(), :1028) — a job cancellation racing in anywhere during that window, followed by cleanPendingCheckpoint, leaves this call scheduling onto an already-shut-down, not-replaced scheduler. Unlike the two now-guarded sites, the resulting RejectedExecutionException here propagates out of a thenAccept(...) callback whose returned CompletableFuture is never assigned or joined (:982), so per CompletableFuture semantics it is captured as that discarded stage's exceptional completion and silently dropped — no log line at all, unlike the two now-guarded sites which at least log at INFO. Functionally this is still low-severity (the coordinator is terminating anyway, so a missed timeout-arm for a checkpoint nobody will wait on is harmless), matching the "Low" severity I already assigned this race in both prior reviews — but it means my own explicit prior recommendation ("wrap the three call sites: :760, :780, :985") was only two-thirds implemented, and the commit message for 6741ec1fe doesn't call out that the third site was deliberately left out, so it's worth a follow-up rather than assuming it's closed.

New, lower-priority observation (pre-existing, not touched by this diff, not blocking): the scheduler field (CheckpointCoordinator.java:164, private transient ScheduledExecutorService scheduler;) is not volatile, unlike e.g. latestCompletedCheckpoint a few lines above it. Every write to scheduler happens inside synchronized (lock), but several reads now happen from threads that never acquire lock (the pre-lock reads in tryTriggerPendingCheckpoint before scheduleTriggerPendingCheckpoint's lambda runs, and the async continuation at :1052 discussed above). In practice the RESET path's field reassignment to a fresh object is the only case where staleness would matter (a reader holding a stale reference to the pre-cleanup object still correctly observes that same object's own shutdown state, since ScheduledThreadPoolExecutor's internal state is itself thread-safe) — so this is a narrow, largely theoretical JMM-visibility gap rather than a practical bug, and it predates this PR. I'm flagging it only because this PR is the first change to make a shut-down-vs-live distinction load-bearing for this field; a follow-up making scheduler volatile would close the gap cheaply. Not required for this PR.

1.2 Compatibility Impact

Unchanged from my prior reviews: fully compatible. No config, public API, RPC/serialization format, or checkpoint/savepoint file format is touched. The only observable difference is that a terminated coordinator's thread pool now actually stays terminated.

1.3 Performance / Side-Effect Analysis

Unchanged from my prior reviews: this closes a genuine, unconditional, 2-non-daemon-thread-per-pipeline leak on every job cancellation/completion — exactly the class of slow monotonic leak that matters at sustained job-churn scale on the master node. The fix closes it completely for every terminal CheckpointCloseReason. The new try/catch in scheduleTriggerPendingCheckpoint adds negligible overhead (a try block around an existing call) and does not change steady-state behavior; it only changes what happens in the already-rare terminal-cleanup race window, from letting the exception propagate/leak to catching, logging, and moving on.

1.4 Error Handling and Logging

Issue 1: Checkpoint-timeout watchdog scheduling (startTriggerPendingCheckpoint) is still unguarded against the same RejectedExecutionException race this PR fixes for scheduleTriggerPendingCheckpoint

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/checkpoint/CheckpointCoordinator.java:1051-1070
  • Problem description: scheduler.schedule(...) here (arming the checkpoint-timeout watchdog) runs from an async thenAccept continuation with no lock held, exactly like the two call sites this PR just fixed — but this one is a separate, un-wrapped call. If a concurrent terminal cleanPendingCheckpoint shuts the scheduler down (and, for a terminal reason, does not replace it) before this line runs, scheduler.schedule(...) throws RejectedExecutionException. Because it's inside a thenAccept(...) whose returned future is discarded (:982), the exception is silently swallowed with no log line — worse for debuggability than the two now-guarded sites, which at least log at INFO.
  • Potential risk: Low. No data-correctness or availability impact — the coordinator is already terminating, so a dropped timeout-arm for a checkpoint nobody will wait on is harmless. This is the same underlying pre-existing race I flagged in both prior reviews (previously masked entirely by the old unconditional scheduler recreation); this PR narrows it from 3 exposed sites to 1, it doesn't introduce it.
  • Best improvement: Wrap this scheduler.schedule(...) call in the same try/catch (RejectedExecutionException) + log pattern just added to scheduleTriggerPendingCheckpoint, so all scheduler.schedule(...) call sites in this class behave consistently and the drop is at least visible in logs.
  • Severity: Low
  • Raised by another reviewer: No (carried forward and narrowed from my 2026-09-07 and 2026-09-14 reviews — same underlying race, now 2 of the original 3 call sites are fixed, this is the remaining one)

2. Code Quality Assessment

2.1 Coding Standards

Clean. The RejectedExecutionException import replaces the now-unused Executors import correctly. The centralized try/catch in scheduleTriggerPendingCheckpoint is a better-scoped fix than patching each caller individually — it covers more call sites than I originally enumerated, at the cost of missing the one call site (:1051) that doesn't go through that method.

2.2 Test Coverage and Test Stability

testCancelDoesNotRecreateScheduler (CheckpointCoordinatorTest.java:1027-1047) is unchanged in logic from my prior reviews: deterministic, no sleeps, asserts scheduler.isShutdown() after a PIPELINE_END-reason cancelCheckpoint().join().

New this round: testResetRecreatesLiveScheduler (CheckpointCoordinatorTest.java:1049-1075) directly asserts the other half of the invariant — restoreCoordinator(true) leaves scheduler.isShutdown() == false — closing the "Optional" coverage gap I noted in both prior reviews (previously only incidentally covered by pre-existing double-restoreCoordinator tests). Both new tests use the same buildMinimalCoordinator(executorService) helper as the rest of the class and follow its existing ReflectionUtils.getField pattern for inspecting the private scheduler field.

Test stability rating: Stable.

Remaining coverage gap (unchanged from my prior reviews, still non-blocking): neither test — nor any other test in this class — simulates a checkpoint trigger racing with terminal cleanup; both are strictly sequential (call one coordinator method, then assert). This means Issue 1 above (and the two now-fixed call sites) are verified by code inspection and the try/catch's presence, not by a test that actually drives the interleaving (e.g., blocking cleanPendingCheckpoint mid-flight while a concurrent thread is inside tryTriggerPendingCheckpoint's pre-lock window). Given the low severity and the fact this gap predates this PR (it's inherent to testing a genuine thread race deterministically), I'm keeping this as a non-blocking observation rather than a blocker, consistent with both my earlier reviews — but it's worth being explicit that "the guard exists" and "the race is tested" are different claims, and only the former is true here.

2.3 Documentation Updates

Not applicable — internal-only fix, no user-visible behavior or config change.

3. Architectural Soundness

3.1 Elegance of the Solution

Still a precise, minimally-scoped fix for the core leak. The follow-up commit's choice to centralize the RejectedExecutionException guard inside scheduleTriggerPendingCheckpoint rather than patching call sites individually is a good call — it's DRY and covers more callers than a literal per-site patch would have. It just isn't a full answer to "guard every scheduler.schedule(...) call," since one call site (:1051) is structurally outside that method.

3.2 Maintainability

Improved further this round: the RESET-only invariant is now documented at its single source (createScheduler()'s Javadoc), and the "why" behind catching RejectedExecutionException is explained in a comment at the catch site rather than left implicit.

3.3 Extensibility

Unchanged from my prior reviews — the single if (closedReason == CHECKPOINT_COORDINATOR_RESET) is the obvious extension point if a future close reason ever needs the scheduler kept alive too.

3.4 Historical-Version Compatibility

Unchanged from my prior reviews — no impact. Pure resource-lifecycle fix internal to a single JVM process; doesn't touch checkpoint/savepoint file formats, serialized job state, or any cross-version wire protocol.

4. Issue Summary

Number Issue Location Severity Status
- createScheduler() helper has no explanatory comment (my prior Issue 1) CheckpointCoordinator.java:289-308 Medium Resolved in 6741ec1fe
- Pre-lock scheduler.schedule(...) in scheduleTriggerPendingCheckpoint's callers can surface RejectedExecutionException on concurrent terminal cleanup (my prior Issue 2, 2 of 3 sites) CheckpointCoordinator.java:557-577 Low Resolved in 6741ec1fe
1 Checkpoint-timeout watchdog scheduler.schedule(...) in startTriggerPendingCheckpoint still unguarded against the same race (3rd of the original 3 sites) CheckpointCoordinator.java:1051-1070 Low Open (carried forward, non-blocking)

5. Merge Recommendation

Conclusion: Ready to merge, pending CI

  1. Blockers — must be fixed
    • None. The core fix is correct and complete; both my prior non-blocking items are resolved or improved, and the one remaining item (Issue 1 above) is a narrow, low-severity, pre-existing race that this PR shrinks from 3 exposed call sites to 1 rather than introduces.
  2. Recommended fixes — non-blocking
    • Issue 1: wrap the scheduler.schedule(...) call in startTriggerPendingCheckpoint (:1051-1070) in the same try/catch (RejectedExecutionException) pattern just added to scheduleTriggerPendingCheckpoint, for consistency and so the drop is at least logged.
    • Optional: a test that actually drives the trigger-vs-cleanup interleaving (rather than asserting the two sequential outcomes) would upgrade "the guard exists" to "the race is verified," but I don't consider this required given the severity.
    • Optional (out of scope for this PR): consider making the scheduler field volatile, since this PR is the first change to make its shut-down-vs-live state load-bearing across threads that don't hold lock.

CI diagnosis: As of this review, the Build check on 6741ec1fe (current head) is still queued/in_progress on both the apache-side pointer and the fork's own Actions run (CryoThrust/seatunnel run 35072891484) — no result yet on this exact SHA. mergeable is true / mergeStateStatus is BLOCKED (review-required, not a merge conflict). Please confirm green on this SHA before merge; I can't substitute the pre-rebase or pre-follow-up SHAs' results for it.

Overall assessment: This is the same real, previously-unconditional thread leak I verified in both prior rounds (#12147), and the core fix logic is unchanged and still correct on this head. The follow-up commit meaningfully improves the PR: it resolves the documentation nit in full, and resolves the RejectedExecutionException race for every call site that routes through scheduleTriggerPendingCheckpoint — which, on closer look this round, turned out to be more call sites than I'd originally enumerated. The one thing it doesn't close is the third site I named explicitly (the checkpoint-timeout watchdog scheduling), which remains open at Low severity as a non-blocking follow-up. Good fix, safe to merge once CI is confirmed green on this SHA.

@davidzollo

Copy link
Copy Markdown
Contributor

Updated this PR against current dev and completed the scheduler lifecycle follow-up in 0e6768c. Trigger scheduling keeps both terminal-shutdown rejection handling and dev's propagation of asynchronous trigger errors; the checkpoint-timeout watchdog now also records a late terminal-shutdown rejection. Both new lifecycle unit tests always cancel their coordinator during cleanup. The existing real master-failover IT still proves checkpoints progress after recovery and now checks the exact recovered coordinator's scheduler is shut down after cancellation, before server shutdown can hide it. Scoped Spotless and diff checks passed. Runtime validation remains pending on this final head; no merge or production approval is implied.

@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 thorough work on this, @CryoThrust, and thanks @davidzollo for carrying the follow-up. I went through the full diff and traced the coordinator lifecycle against the new head. Since my last review (6741ec1fe3) there are two new commits (4ddf6be50b, 0e6768c328) plus a merge of dev; I re-verified everything below at 0e6768c328. This review is by code reading only; nothing was executed locally.

What Problem Does This PR Solve?

  • User pain point: after a pipeline reaches a terminal state (cancel, complete, fail), CheckpointCoordinator.cleanPendingCheckpoint() shut down its scheduler and immediately created a replacement. The replacement was never used and never shut down, so every finished pipeline leaked an idle 2-thread checkpoint-coordinator-<pipeline>/<job> pool on the master.
  • Fix approach: create the replacement scheduler only for CHECKPOINT_COORDINATOR_RESET (master failover restore); make late scheduling attempts against a shut-down scheduler harmless.
  • One-sentence summary: stop leaking checkpoint scheduler threads after terminal cleanup without breaking failover restore.

1. Code Change Review

1.1 Core Logic Analysis

Before (dev): cleanPendingCheckpoint() always did scheduler.shutdownNow(); scheduler = Executors.newScheduledThreadPool(2, ...).
After (CheckpointCoordinator.java:1294-1301):

scheduler.shutdownNow();
if (closedReason == CheckpointCloseReason.CHECKPOINT_COORDINATOR_RESET) {
    scheduler = createScheduler();   // 2 threads, removeOnCancel, MDC tracing
}

Runtime path:

terminal: PIPELINE_END (1544) | COMPLETED (1468) | handleCoordinatorError (379) | cancelCheckpoint
  -> cleanPendingCheckpoint(reason) -> scheduler.shutdownNow(), no replacement
failover: CheckpointManager.restoreCoordinator (273) -> restoreCoordinator(alreadyStarted) (731)
  -> cleanPendingCheckpoint(RESET) -> new scheduler -> tryTriggerPendingCheckpoint(...)
late callers (guarded): scheduleTriggerPendingCheckpoint (561-584), checkpoint-timeout arm (1062-1090)

Findings, all verified in source at this head:

  • The only two scheduler.schedule(...) call sites in the class are both guarded by catch (RejectedExecutionException) now. This closes the third site I called out as open in my last round (the checkpoint-timeout watchdog), so that item is resolved.
  • A restart of a coordinator that previously went terminal (for example a pipeline failover after CHECKPOINT_INSIDE_ERROR) always goes through restoreCoordinator(), which calls cleanPendingCheckpoint(RESET) first, and shutdownNow() on an already-shut-down executor is a no-op, so a new live scheduler is created on that path. I found no path that reuses a coordinator after a terminal reason without going through restore.
  • The replacement scheduler is now built by createScheduler() and therefore also gets setRemoveOnCancelPolicy(true) and MDC tracing, which the old inline replacement did not have. This is a benign improvement, and it makes the constructor and the replacement consistent.
  • The scheduled trigger lambda keeps dev's catch (Throwable) -> handleCoordinatorError(CHECKPOINT_INSIDE_ERROR) propagation, so the guard does not swallow real trigger failures. Only the rejection of schedule() itself is downgraded to an INFO log.
  • Normal path vs edge path: the leak fix is hit on every normal job termination (main path). The rejection handling is hit only in the shutdown race window.

1.2 Compatibility Impact

Fully compatible. No config, protocol, serialization, checkpoint-storage or RPC change; scheduler is transient and private. Behavior difference visible to users: fewer idle threads after jobs end.

1.3 Performance / Side-Effect Analysis

Positive: removes one 2-thread pool per terminated pipeline (thread/memory growth on long-lived masters that run many jobs). No new locks. The RESET path creates the same pool as before.

1.4 Error Handling and Logging

  • Issue 1 (Low, new in this head, not raised by others): the Javadoc of cleanPendingCheckpoint still lists "Stopping and recreating the scheduler thread pool" and "the coordinator is ready for a clean restart if necessary" (CheckpointCoordinator.java:1242,1248). That is no longer accurate for terminal reasons. Fix: reword to "Stopping the scheduler thread pool (recreated only for CHECKPOINT_COORDINATOR_RESET)".
  • Issue 2 (Low, optional, raised by me in an earlier round, not by others): scheduler (CheckpointCoordinator.java:165) is a plain transient field that is reassigned under lock in cleanPendingCheckpoint but read without lock by scheduleTriggerPendingCheckpoint and the timeout arm. Previously a stale read would surface as a RejectedExecutionException; with this PR it is logged and the trigger or timeout arm is silently skipped. Making the field volatile would remove any chance of a post-reset caller seeing the old shut-down executor. I do not consider it blocking since the reset path re-triggers from the same thread that created the scheduler.

2. Code Quality Assessment

2.1 Coding Standards

Good: createScheduler() has a Javadoc that states the RESET-only invariant, and both swallow sites carry explanatory comments. Import cleanup is correct (Executors replaced by RejectedExecutionException).

2.2 Test Coverage and Test Stability

Rating: Stable on code reading (not executed).

  • CheckpointCoordinatorTest.testCancelDoesNotRecreateScheduler (:1027-1055) goes red if a replacement is created on terminal cleanup.
  • testResetRecreatesLiveScheduler (:1057-1090) goes red if the RESET branch is removed, which protects failover restore. Both always cancel the coordinator and shut down their executor in finally.
  • CheckpointCoordinatorFailoverIT.testStreamJobContinuesAfterMasterFailover now grabs the exact recovered coordinator on the new master (getCheckpointCoordinator(observedPipelineId)), cancels the job, and awaits scheduler.isShutdown() before server shutdown can mask a replacement. It uses Awaitility with a 10 s bound, not a fixed sleep. Reflection on a private field is already the convention in this IT (lock, pendingCounter).
  • Gap (informational): the new rejection-handling branches (scheduleTriggerPendingCheckpoint and the timeout arm) have no direct unit test that schedules against a shut-down coordinator. The leak itself is well covered; the swallow paths are covered only by reasoning.

2.3 Documentation Updates

Internal engine change, no user-visible docs needed.

3. Architectural Soundness

3.1 Elegance

Precise fix at the right layer (the cleanup that created the leak).

3.2 Maintainability

Good. One factory for the scheduler. The only maintainability nit is the stale Javadoc (Issue 1).

3.3 Extensibility

Fine. The "RESET is the only reason that revives the coordinator" invariant is now explicit.

3.4 Historical-Version Compatibility

No impact on checkpoint state, IMap contents or rolling-upgrade behavior.

4. Issue Summary

Number Issue Location Severity
1 cleanPendingCheckpoint Javadoc still says the scheduler is recreated CheckpointCoordinator.java:1242,1248 Low
2 scheduler not volatile while rejection is now swallowed (optional) CheckpointCoordinator.java:165 Low

5. Merge Recommendation

Conclusion: Ready to merge after fixes

Blockers (must fix): none on the code side.

Recommended fixes (non-blocking): Issue 1 (one-line Javadoc update) and optionally Issue 2.

CI on the current head (0e6768c328): CI has not executed on this head. The only workflow run attached to the head is PR signal, with conclusion action_required (it is waiting for a maintainer to approve workflow runs), and there are no check runs. The branch is 2 commits behind dev and has no merge conflict. Because this touches seatunnel-engine-server, I would like to see the engine unit tests and the engine-v2-it / CheckpointCoordinatorFailoverIT jobs green on this exact head before merge; the green or red state of earlier SHAs cannot be reused.

Overall assessment: the leak is real and the fix is minimal and correct. All items from my previous rounds are now addressed: the createScheduler() comment, the pre-lock rejection window, and the checkpoint-timeout watchdog site that I had left open as a follow-up. I do not see a better alternative location for the fix. No maintainer APPROVED/CHANGES_REQUESTED review exists on this PR yet, so it still needs a maintainer approval after CI is green.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for completing the scheduler lifecycle follow-up. I re-reviewed the full three-file diff at 0e6768c328d59c4b0e9bc9c214d9c6d746e971ce, including terminal cleanup, RESET, asynchronous barrier completion and the real failover assertion. The production direction is sound. Sorry for not asking for a deterministic late-scheduling regression in my previous round; the corresponding test-strength item below is a carryover, not a newly introduced source defect.

What Problem Does This PR Solve?

  • User pain point: checkpoint cleanup recreated an executor even when the coordinator had permanently ended, allowing late scheduling to keep checkpoint threads alive after cancellation/completion.
  • Fix approach: recreate only for coordinator RESET, preserve shutdown on terminal cleanup, and tolerate late schedule attempts rejected by that shutdown.
  • One-sentence summary: terminal coordinators stay stopped, while recovered coordinators retain a live checkpoint scheduler.

Example: cancel a recovered pipeline. Its scheduler must already be shut down before the member itself is stopped; otherwise member shutdown could hide the leak.

1. Code Change Review

1.1 Core Logic Analysis

Full +176/-60 diff: CheckpointCoordinator.java, existing CheckpointCoordinatorTest.java, existing CheckpointCoordinatorFailoverIT.java.

Before:

scheduler.shutdownNow();
scheduler = Executors.newScheduledThreadPool(2, threadFactory);

After (CheckpointCoordinator.java:1294-1301):

scheduler.shutdownNow();
if (closedReason == CheckpointCloseReason.CHECKPOINT_COORDINATOR_RESET) {
    scheduler = createScheduler();
}

createScheduler (:296-310) preserves two threads, naming, remove-on-cancel and MDC tracing for constructor and RESET. Trigger scheduling (:558-585) and timeout arming (:1060-1092) catch RejectedExecutionException from a pool that has shut down; actual asynchronous trigger errors still call handleCoordinatorError.

Key findings:

  • Terminal cancel, final completion and failure paths reach cleanup; this is not a per-row change.
  • RESET is a live restart: cleanup installs a new scheduler, restoreCoordinator clears shutdown and explicitly starts/restages checkpoint work. Old reset work is aborted; the new coordinator does not depend on a rejected old timer.
  • PendingCheckpoint.abortCheckpoint completes with null for RESET/PIPELINE_END, so those intentional aborts do not become new failure exceptions through the completion callback.
  • The factory keeps the existing executor policy on RESET; terminal late callbacks cannot allocate a replacement scheduler.

Complete lifecycle:

normal task readiness -> schedule trigger -> checkpoint ID/create pending state
 -> async barrier RPC -> arm timeout -> acknowledgements -> completion
 -> ordinary next trigger on same live scheduler

master recovery -> CheckpointManager.restoreCoordinator
 -> restoreCoordinator -> RESET cleanup under lock
 -> abort/clear old pending state -> old scheduler.shutdownNow -> factory creates new one
 -> shutdown=false -> restart checkpoint path / await task readiness

cancel / final completion / error -> terminal cleanup
 -> abort/clear pending work -> scheduler.shutdownNow -> no replacement
 -> complete coordinator/job future
late trigger / barrier completion -> scheduling rejected -> log lifecycle context

Cancel's cleanup occurs before its completion future is returned. The new IT obtains the exact coordinator that showed checkpoint progress after failover, cancels the job, waits for CANCELED, and checks scheduler shutdown before member teardown.

1.2 Compatibility Impact

Fully compatible for API/SPI, configs/defaults, serialization/checkpoints and job delivery semantics. RESET retains restart capability; only unwanted terminal resource lifetime changes. No user migration or incompatible-state entry is introduced.

1.3 Performance / Side-Effect Analysis

Removes terminal replacement executors; RESET still allocates the existing two-thread scheduler. No new row-path work, network request, shared queue or lock. Pending-work cleanup remains under the existing lock; shutdown is volatile. CPU/memory/GC and thread-lifetime improvement is structural, not a measured benchmark. Retry/idempotency and checkpoint storage semantics are unchanged.

1.4 Error Handling and Logging

Real scheduled-trigger exceptions still propagate into coordinator failure. Late terminal shutdown rejections are logged with job/pipeline/type or checkpoint ID and do not falsely report successful checkpointing. Standard ScheduledThreadPoolExecutor uses an unbounded delayed queue, so this rejection path concerns shutdown rather than an invented bounded-capacity drop policy.

Issue 1: Pin late scheduling rejection directly in the existing tests

  • Location: CheckpointCoordinatorTest.java:1028-1090; production CheckpointCoordinator.java:558-585,1060-1092.
  • Problem: the new tests assert terminal shutdown and a live RESET scheduler, but do not deterministically invoke a late trigger or complete a barrier callback after cleanup. The IT's scheduling race is incidental. Removing a rejection catch can therefore leave those invariant assertions green while the intended late-callback protection is gone.
  • Risk: weak regression protection for the new asynchronous shutdown boundary.
  • Best improvement: extend this test class with a canceled-coordinator late schedule call, asserting no thrown rejection and no replacement executor; use a controlled future/latch for timeout arming after cancel. Keep RESET and real failover assertions unchanged. No sleep is needed.
  • Severity: Medium, non-blocking test-strength recommendation; no failing production path is demonstrated in the current guarded code.
  • Raised by another reviewer: No.

Issue 2: Align cleanup Javadoc with the RESET-only rule

  • Location: CheckpointCoordinator.java:1242.
  • Problem: the cleanup summary still says stopping and recreating the scheduler without its new RESET condition, whereas the nearby implementation correctly distinguishes terminal cleanup.
  • Risk: misleading lifecycle guidance for later maintainers.
  • Best improvement: qualify that bullet with recreation only for CHECKPOINT_COORDINATOR_RESET.
  • Severity: Low, non-blocking.
  • Raised by another reviewer: No.

2. Code Quality Assessment

2.1 Coding Standards

Focused existing factory/cleanup/scheduling changes. createScheduler documents its ownership and lifecycle; tests extend the existing classes. No dependency, file, option or plugin change. Issue 2 is the remaining comment consistency item.

2.2 Test Coverage and Test Stability

Stability rating: Stable for the changed assertions (CheckpointCoordinatorTest.java:1028-1090, CheckpointCoordinatorFailoverIT.java:374-398). Unit operations use controlled minimal state, always cancel the coordinator and shut down the fixture executor in finally. The RESET case proves a live scheduler; the cancel case proves no replacement. The IT uses checkpoint-ID progress, CANCELED completion and an Awaitility shutdown condition; it does not use a fixed sleep or weaken existing data/progress checks. The captured coordinator is checked before member shutdown can mask the bug. Late-callback failure power remains Issue 1; this is not evidence of a flaky current assertion.

Local results: exact fetch/checkout seatunnel-review-12149; complete three-file diff read; numbered/rg tracing covered manager entry, readiness/trigger, pending abort, reset/cancel/final/error cleanup, asynchronous timeout and test helpers; git diff --check upstream/dev...HEAD passed. No local compilation, UT/IT/E2E or real job execution.

Current-head fork inventory contains no Build run. Apache PR signal is action_required; there is no executed failed test lane to attribute. A write-capable maintainer should approve/inspect that workflow and get exact-head Build results, including the changed server tests/failover IT. No empty source commit is needed just to approve a workflow, and no upstream test fix can be inferred from an absent run.

2.3 Documentation Updates

No new user setting/default, checkpoint format or upgrade step. EN/ZH user docs need no migration change for this resource-lifecycle correction; the internal lifecycle comment should be aligned as in Issue 2.

3. Architectural Soundness

3.1 Elegance

Precise fix at the coordinator that owns the scheduler. Smallest safe and best location coincide. Global executor or engine-shutdown changes would enlarge the lifecycle contract unnecessarily.

3.2 Maintainability

One factory preserves policy across construction/reset; terminal behavior is explicit. Deterministic late-callback tests would preserve that boundary more directly.

3.3 Extensibility

Additional close reasons must explicitly choose reset versus terminal semantics; no new cross-module abstraction is needed.

3.4 Historical-Version Compatibility

Stable state/config/protocol; recovered coordinators still schedule checkpoints. No migration required.

4. Issue Summary

Full diff, normal/reset/terminal paths, async completions, state/abort semantics, resources, tests/stability, docs, community discussion and current gates checked.

Number Issue Location Severity
1 Late scheduling catches lack direct deterministic regression CheckpointCoordinatorTest.java:1028-1090 Medium, non-blocking
2 Cleanup summary omits RESET-only recreation CheckpointCoordinator.java:1242 Low, non-blocking

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers (must resolve): workflow approval/activation and acceptable current-head CI, plus write-capable maintainer approval. No blocking source issue found.
  2. Recommended fixes (non-blocking): Issue 1's late-callback test and Issue 2's one-line comment correction.

Overall, the reset/terminal split is at the correct ownership layer and the existing failover IT now observes the actual resource invariant. There is no independent non-author review conclusion to duplicate. The author's reported local passes are not presented as my executions or this new head's CI. Compare is dev diverged, ahead 4 / behind 2, no conflict; drift is recorded only, without an unrelated failed check supporting a sync-first request. GitHub remains BLOCKED / REVIEW_REQUIRED. This COMMENT is not a runtime pass or effective approval.

@github-actions github-actions Bot added the e2e label Oct 26, 2026
@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks for the contribution. The CI fact cited in my previous conclusion has changed; this follow-up updates that gate on the unchanged reviewed head, without issuing another full source review.

Gate snapshot (2026-10-28T15:56:55+00:00), head 0e6768c328d59c4b0e9bc9c214d9c6d746e971ce: Build is ACTION_REQUIRED.

The exact blocking stage is Build workflow-run detection: the check says no fork Build was found for this SHA. This is not an executed test failure and does not by itself prove that fork Actions is disabled. Open the fork Actions tab, enable workflows if needed, then manually run the existing Build workflow for this PR branch. If a matching run already exists, link it for a maintainer to reconcile the aggregate. No empty commit or speculative dependency change is requested.

Upstream check: current dev retains the fork-run adoption workflow and its scheduled/manual status-refresh path. A base sync alone cannot enable fork Actions or supply a missing exact-head workflow run, so I am not prescribing sync as the fix for this activation gate.

My previous source conclusion remains clear for the reviewed scope. CI is not being passed by inference, and this follow-up is not an effective approval.

Comparison recorded in this scan: base dev, diverged, ahead 4 / behind 48, no merge conflict. Branch drift is metadata here and is not an additional sync request.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for retaining both upstream trigger-error propagation and this PR's terminal scheduler handling. I re-reviewed the full latest head, including the recovered coordinator check before member shutdown. No blocking source issue was found; the current Build detection gate still needs a real exact-head run.

What Problem Does This PR Solve?

User pain point: Terminal checkpoint cleanup used to replace its shutdown scheduler, allowing late callbacks to schedule work on a coordinator that had ended.

Fix approach: Centralize the two-thread scheduler setup, recreate only on CHECKPOINT_COORDINATOR_RESET and tolerate late terminal scheduling rejection.

One-sentence summary: Cancel a recovered job: its exact coordinator scheduler must remain shut down. A failover reset instead receives a new usable scheduler and continues checkpointing.

Review report time: 2026-10-29T11:26:50.689165-04:00. Current head 1846ff8c63f439483156cfd51be68b68ed7fe3cb; base dev at 07f5011b8506d0bfeca1a23df315a08f45cb3e33. Checks: Signal pull request update=SUCCESS; Build=ACTION_REQUIRED. Check references: Signal pull request update Build. Compare: diverged, ahead 5, behind 7; merge state blocked / BLOCKED.

1. Code Change Review

1.1 Core Logic Analysis

seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/checkpoint/CheckpointCoordinator.java:291-311 creates one MDC-wrapped scheduler with remove-on-cancel policy. cleanPendingCheckpoint (:1279-1336) aborts/tracks cleanup, shuts down the scheduler and recreates only for reset. scheduleTriggerPendingCheckpoint (:560-588) and async watchdog setup (:1082-1120) handle RejectedExecutionException; inner trigger errors still reach handleCoordinatorError. The two UTs and seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/CheckpointCoordinatorFailoverIT.java:383-408 observe terminal/reset behavior. All three changed files and manager/trigger/restore/error/cancel call chains were read.

Before:

scheduler.shutdownNow();
scheduler = Executors.newScheduledThreadPool(2, threadFactory);

After:

scheduler.shutdownNow();
if (closedReason == CHECKPOINT_COORDINATOR_RESET) { scheduler = createScheduler(); }

Key Findings

  • Normal terminal cancel/completion/error cleanup reaches the resource correction.
  • Recovery reset remains live and re-triggers through restoreCoordinator.
  • Late terminal scheduling rejection no longer creates replacement work; asynchronous trigger failures still propagate.
  • The IT checks the recovered scheduler before server shutdown can hide an incorrect live scheduler.

Complete runtime path

CheckpointManager creates coordinator -> constructor createScheduler
 -> task-ready callback -> tryTriggerPendingCheckpoint -> barrier RPC futures
 -> asynchronous completion arms timeout -> ack/completion or coordinator error
Terminal cancel/final/error -> cleanPendingCheckpoint -> abort pending -> clear tracking -> shutdownNow, no replacement
Master recovery -> restoreCoordinator (:725) -> RESET cleanup -> createScheduler -> shutdown=false
 -> restore idle/ready bookkeeping -> trigger current checkpoint -> continue periodic chain
Failover IT -> checkpoints progress on new master -> cancel job future -> assert recovered scheduler shut down before member cleanup

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

1.2 Compatibility Impact

Fully compatible. No configuration/default, public API/SPI, serialized checkpoint, persisted ready-to-close state or RPC shape changes. RESET still preserves persisted ready-to-close metadata and creates a live scheduler. Terminal behavior closes resources rather than changing data/state encoding. No migration is needed.

1.3 Performance / Side-Effect Analysis

A canceled/finished coordinator no longer owns replacement scheduling capacity. Scheduler thread count remains two for active/reset coordinators; canceled tasks retain remove-on-cancel and MDC wrapping on reset too. No new lock, retry, queue or network stage is added. Late rejection logs are lifecycle-bounded, not per row.

1.4 Error Handling and Logging

RejectedExecutionException is caught at scheduling boundaries; trigger-body Throwable still reaches handleCoordinatorError. Cleanup aborts pending checkpoints and resets counters before terminal completion. A focused reset/terminal rejection test would document that rejection is benign only for obsolete work; see Issue 1.

Issue 1: Add deterministic late-scheduling boundary regression coverage

  • Location: seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/checkpoint/CheckpointCoordinatorTest.java:1139-1203
  • Problem description: The new UTs prove scheduler replacement/shutdown, but do not directly drive either new rejection catch with a controlled in-flight callback. The existing failover IT observes the scheduler invariant, not the specific asynchronous rejection window.
  • Potential risk: A later change can remove or over-broaden the late-callback guard without these assertions detecting it. No current failing source path is established by that coverage gap alone.
  • Best improvement / root-cause and location assessment: Extend the existing coordinator test with latches/controlled futures: cancel while a barrier callback is held, release it and assert no scheduler resurrection or lost error propagation; retain a separate RESET case that resumes scheduling. This is a focused non-blocking follow-up at the scheduler owner, not a new engine abstraction.
  • Severity: Medium; non-blocking.
  • Raised by another reviewer: No.

Issue 2: Align the cleanup summary with RESET-only recreation

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/checkpoint/CheckpointCoordinator.java:1265
  • Problem description: The method-level cleanup summary still says stopping and recreating the scheduler pool without the RESET qualifier, although the new implementation intentionally keeps terminal schedulers shut down.
  • Potential risk: A future maintainer can infer the wrong lifecycle contract from the summary.
  • Best improvement / root-cause and location assessment: Qualify that bullet as recreation only for CHECKPOINT_COORDINATOR_RESET; retain the existing detailed inline explanation.
  • Severity: Low; non-blocking.
  • Raised by another reviewer: No.

2. Code Quality Assessment

2.1 Coding Standards

The complete changed-file set, imports and removed lines were inspected. No new option, protocol field, public API or connector registration is added. The important behavior and its limits are explained above; test-boundary documentation should explain the regression it protects.

2.2 Test Coverage and Test Stability

Stability rating: Stable. CheckpointCoordinatorTest.java:1139-1203 uses completion/finally cleanup and exact scheduler-state assertions; caller executors are shut down. seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/CheckpointCoordinatorFailoverIT.java:383-408 obtains the actual recovered coordinator, waits on job completion and uses bounded condition polling before server teardown. No new sleep, clock expectation, random data or host port is added. Reflection reads the lifecycle field; it does not invoke private production methods. The untested rejection window is the non-blocking coverage item above.

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

2.3 Documentation Updates

No user option/default or persistence contract changes; both language guides need no migration update. Correct the internal cleanup summary in Issue 2.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix.

3.2 Maintainability

Best change-location assessment: CheckpointCoordinator owns scheduler creation, reset and terminal cleanup, making it the best and smallest fix point. Changing a global executor or server shutdown would mask leaked coordinator lifecycle and broaden impact. The targeted deterministic callback tests are the best follow-up; no wider lifecycle refactor is required.

3.3 Extensibility

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

3.4 Historical-Version Compatibility

No configuration/default, public API/SPI, serialized checkpoint, persisted ready-to-close state or RPC shape changes. RESET still preserves persisted ready-to-close metadata and creates a live scheduler. Terminal behavior closes resources rather than changing data/state encoding. No migration is needed. This review does not claim an executed upgrade/recovery validation.

4. Issue Summary

Number Issue Location Severity
1 Add deterministic late-scheduling boundary regression coverage seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/checkpoint/CheckpointCoordinatorTest.java:1139-1203 Medium, non-blocking
2 Align the cleanup summary with RESET-only recreation seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/checkpoint/CheckpointCoordinator.java:1265 Low, non-blocking

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

Community review reconciliation: No independent non-author review or inline technical point exists in the collected history. The author's old suggestion to skip integration suites is not an acceptance path; keep required coverage. The follow-up by davidzollo is read as existing discussion, not attributed to this run.

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers — must be fixed: No code-side blocker found. Required current-head CI and effective maintainer review/merge gates must be satisfied.
  2. Recommended fixes — non-blocking: Issue 1: Add deterministic late-scheduling boundary regression coverage; Issue 2: Align the cleanup summary with RESET-only recreation

Overall assessment: CheckpointCoordinator owns scheduler creation, reset and terminal cleanup, making it the best and smallest fix point. Changing a global executor or server shutdown would mask leaked coordinator lifecycle and broaden impact. The targeted deterministic callback tests are the best follow-up; no wider lifecycle refactor is required. Current head 1846ff8c63f439483156cfd51be68b68ed7fe3cb; base dev at 07f5011b8506d0bfeca1a23df315a08f45cb3e33. Checks: Signal pull request update=SUCCESS; Build=ACTION_REQUIRED. Check references: Signal pull request update Build. Compare: diverged, ahead 5, behind 7; merge state blocked / BLOCKED. Behind/diverged status alone is synchronization metadata and does not justify a sync-and-rerun instruction. Daniel has READ permission: this COMMENT is a technical conclusion, not an effective APPROVED event or dismissal of historical requested changes. A write-capable maintainer owns final approval/dismissal where required. Exact blocking stage: Build workflow-run detection (ACTION_REQUIRED), https://github.com/apache/seatunnel/runs/123364072890 . No fork Build was found for the SHA; this is not an executed source-test failure. Open fork Actions, enable if disabled, then manually Run workflow -> Build on this branch; link an already-existing matching run instead of adding a trigger commit. Latest dev retains the scheduled/manual fork-run adoption mechanism; syncing alone cannot supply a missing fork run. Effective maintainer approval remains separate. Thanks again; happy to help with the focused next revision.

@CryoThrust

CryoThrust commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor Author

The old-head Build finished with five failed connector jobs. The four unit jobs and both engine-v2/resource-manager JDK lanes passed. The connector logs show:

  • SFTP / JDK 11 and 17: atmoz/sftp:alpine-3.7 returns 404 before the fixture starts.
  • Connector partition 5 / JDK 11: TiDBCDCIT.startUp fails while initializing the database with a communications-link error.
  • JDBC partition 7 / JDK 11 and 17: JdbcIrisIT times out in database startup; IRIS logs report startup errors and the JDBC connection is refused.

Synced current dev (37309e1a8) in 036319a35, including the existing SFTP #13203 and TiDB readiness #13269 fixes. This was a clean merge, with no manually resolved hunks in the checkpoint files; git show --remerge-diff 036319a35 is empty. The PR still changes exactly the three checkpoint production/unit/IT files. No IRIS workaround was added here, and its old startup failure's cause was not established.

On the new head, all 19 CheckpointCoordinatorTest cases pass locally. The streaming master-failover IT also passes without skips: two real in-process members, streaming recovery after master shutdown, then scheduler-shutdown verification after cancellation. Scoped Spotless, Checkstyle, packaging and dependency installation pass on JDK 11.

The new-head Build has now completed successfully on exact PR head 036319a35c5638ba788b09f7921e9e364e04bda5: 86 jobs succeeded, 11 were conditionally skipped, and none failed. This includes the previously failing connector lanes. This is the full workflow run in my fork, not a claim that the upstream PR check has been rerun or that every individual test ran without skips.

@SEZ9

SEZ9 commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

@CryoThrust thanks for the detailed breakdown of the old-head Build and for syncing dev (37309e1a8) in 036319a35.

From your log summary, the five failed connector jobs (the SFTP image 404 on JDK 11 and 17, the TiDBCDCIT.startUp communications-link error, and the JdbcIrisIT startup timeouts on JDK 11 and 17) are all fixture or database startup failures. The four unit jobs and both engine-v2/resource-manager JDK lanes passed. I agree with keeping connector workarounds out of this PR and holding the change to the three checkpoint files.

The earlier review found no blocking source issue on head 1846ff8c63f439483156cfd51be68b68ed7fe3cb, and the open gate was a real exact-head Build run. Since the head has moved with the sync, the remaining asks are:

  1. New-head Build: please post the final result of the new-head Build once it finishes, and confirm it ran against the current PR head.
  2. Sync commit: did 036319a35 need any conflict resolution in the three checkpoint files, or was it a clean merge? If anything was resolved by hand, please point out those hunks so they can be re-checked.
  3. SFTP and TiDB: if either still fails on the new head despite the fixes now pulled in from dev, please share the relevant log excerpt.
  4. IRIS: the startup cause is still not established. If JdbcIrisIT fails again, please paste the IRIS startup errors from the log so we can judge whether it is independent of this change.

Good to hear that all 19 CheckpointCoordinatorTest cases and the streaming master-failover IT pass locally on the new head. CI still needs the finished exact-head run and will not be passed by inference.

@SEZ9 SEZ9 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for working on this. I reviewed the latest head 036319a35c56.

What this PR fixes

  • User pain: After a streaming job is cancelled, finishes or fails, an idle checkpoint-coordinator-<pipelineId>/<jobId> pool stays alive (#12147). cleanPendingCheckpoint called scheduler.shutdownNow() and then unconditionally built a replacement pool for a coordinator that never runs again. That replacement also lacked the constructor's setRemoveOnCancelPolicy(true) and MDCTracer.tracing wrapping.
  • Fix approach: Pool construction moves into createScheduler() (CheckpointCoordinator.java:297). It is called from the constructor (:241) and from cleanPendingCheckpoint only when closedReason == CheckpointCloseReason.CHECKPOINT_COORDINATOR_RESET (:1322-1323), so every other close reason leaves the pool shut down. Both scheduler.schedule(...) call sites now catch RejectedExecutionException and log at INFO (:580, :1106). Two unit tests and an addition to the master-failover IT assert scheduler.isShutdown() after cancel and !isShutdown() after reset.
  • One-line summary: At head 036319a the leak fix holds. The terminal paths I traced (PIPELINE_END, CHECKPOINT_COORDINATOR_COMPLETED, error reasons) no longer recreate the pool, and both restore entry points (SubPlan.prepareRestorePipeline() and SubPlan.restorePipelineState()) still get a fully configured one through restoreCoordinator(). testResetRecreatesLiveScheduler does not race an asynchronous error path. One non-blocking observation outside the findings: scheduler (:167) is non-volatile and is read outside lock at :1085 and by some callers of :563, so a call that overlaps a RESET between shutdownNow() (:1317) and the reassignment (:1323) can hit the old pool and take the new INFO-level skip. The findings below are all LOW: comment and Javadoc accuracy, plus one stronger assertion for the IT.

Runtime chain I rechecked

Construction
  CheckpointCoordinator.<init> -> createScheduler()  CheckpointCoordinator.java:241
    createScheduler(): new ScheduledThreadPoolExecutor(2, named factory) + setRemoveOnCancelPolicy(true) + MDCTracer.tracing(executor)  CheckpointCoordinator.java:297-310
    field: private transient ScheduledExecutorService scheduler (not volatile)  CheckpointCoordinator.java:167

Terminal path: cancel (pool must stay shut down)
  SubPlan.cancelPipeline() -> cancelCheckpointCoordinator()  SubPlan.java:468-473, 485-488
  SubPlan.getPipelineEndState() (FAILED / CANCELED branches)  SubPlan.java:269, 272
    -> CheckpointManager.cancelCheckpoint(pipelineId)  CheckpointManager.java:458-459
      -> CheckpointCoordinator.cancelCheckpoint()  CheckpointCoordinator.java:1562
           early return, no cleanup, if checkpointCoordinatorFuture.isDone()  CheckpointCoordinator.java:1564
        -> cleanPendingCheckpoint(PIPELINE_END)  CheckpointCoordinator.java:1567 -> 1277
             shutdown = true  CheckpointCoordinator.java:1278
             synchronized (lock): abort and clear pendingCheckpoints  CheckpointCoordinator.java:1280-1303
             scheduler.shutdownNow()  CheckpointCoordinator.java:1317
             if (closedReason == CHECKPOINT_COORDINATOR_RESET) is false -> no createScheduler()  CheckpointCoordinator.java:1322

Other terminal paths through the same guard
  completePendingCheckpoint() -> cleanPendingCheckpoint(CHECKPOINT_COORDINATOR_COMPLETED)  CheckpointCoordinator.java:1491
  handleCoordinatorError(reason, e)  CheckpointCoordinator.java:366
    -> checkpointManager.handleCheckpointError(pipelineId, false)  CheckpointCoordinator.java:377
    -> cleanPendingCheckpoint(reason)  CheckpointCoordinator.java:381

Revival paths (the only places the pool comes back)
  Pipeline restore: SubPlan state process, FAILED / CANCELED -> checkNeedRestore(state) && prepareRestorePipeline()  SubPlan.java:826, 558
    -> CheckpointManager.reportedPipelineRunning(pipelineId, false)  SubPlan.java:568
  Master failover: SubPlan.restorePipelineState()  SubPlan.java:635
    -> CheckpointManager.reportedPipelineRunning(pipelineId, isCheckpointCoordinatorAlreadyStarted())  SubPlan.java:652-656
  Both: CheckpointManager.reportedPipelineRunning()  CheckpointManager.java:269
    -> CheckpointCoordinator.restoreCoordinator(alreadyStarted)  CheckpointManager.java:273 -> CheckpointCoordinator.java:725
      -> cleanPendingCheckpoint(CHECKPOINT_COORDINATOR_RESET)  CheckpointCoordinator.java:733
           scheduler.shutdownNow(); scheduler = createScheduler()  CheckpointCoordinator.java:1317, 1323
      -> shutdown = false  CheckpointCoordinator.java:734

Scheduling call sites that now tolerate a shut-down pool
  scheduleTriggerPendingCheckpoint(): scheduler.schedule(...)  CheckpointCoordinator.java:563
    catch (RejectedExecutionException) -> LOG.info, skip  CheckpointCoordinator.java:580
  startTriggerPendingCheckpoint(): timeout watchdog scheduler.schedule(...)  CheckpointCoordinator.java:1085
    catch (RejectedExecutionException) -> LOG.info, skip  CheckpointCoordinator.java:1106

Findings

Issue 1: The new comments say only a master-failover reset needs a replacement scheduler, but CHECKPOINT_COORDINATOR_RESET is also how an ordinary pipeline restore revives a coordinator whose scheduler was shut down by an earlier non-RESET cleanup.

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/checkpoint/CheckpointCoordinator.java:295
  • Why it matters: The createScheduler() Javadoc, the comment in cleanPendingCheckpoint and the new test Javadoc all describe the invariant too narrowly.
  • Root cause: restoreCoordinator() (CheckpointCoordinator.java:733) is the only caller that passes CHECKPOINT_COORDINATOR_RESET, and it is reached from two places through CheckpointManager.reportedPipelineRunning(). One is the master-failover restore in SubPlan.restorePipelineState() (reportedPipelineRunning(..., isCheckpointCoordinatorAlreadyStarted())). The other is SubPlan.prepareRestorePipeline(), which calls reportedPipelineRunning(pipelineId, false) whenever a FAILED or CANCELED pipeline is restored.
  • In that second path the same coordinator has already been through a non-RESET cleanup. That is either handleCoordinatorError(...) -> cleanPendingCheckpoint(<error reason>), or cancelCheckpoint() -> cleanPendingCheckpoint(PIPELINE_END) from SubPlan.getPipelineEndState(). With this PR the cleanup leaves the scheduler shut down, and the RESET then revives it. So "a terminal coordinator must not get a replacement scheduler" is not literally true for a coordinator that failed and is being restored.
  • Impact: the code is correct, because every revival goes through restoreCoordinator(). The comments hide the invariant that keeps checkpointing alive after a pipeline restart: restoreCoordinator() must run its RESET cleanup before anything is scheduled. A later change that trusts "master-failover only" and bypasses or narrows that RESET on the pipeline-restore path would leave a restarted streaming pipeline with a shut-down scheduler. Both schedule() sites would then skip at INFO level and checkpointing would stop without an error.
  • Fix: reword the comments to state the real contract. The scheduler stays down after any non-RESET cleanup, and restoreCoordinator() (pipeline restore or master failover) is the single place that brings it back.
  • Evidence: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/checkpoint/CheckpointCoordinator.java:1320 // completed. A replacement is only needed when a master-failover reset restarts the; seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/checkpoint/CheckpointCoordinatorTest.java:1169 * The other half of the same invariant: a master-failover reset does need the scheduler back,
  • Suggested fix: Small accuracy point on this Javadoc (and the matching comment in cleanPendingCheckpoint): CHECKPOINT_COORDINATOR_RESET is not only a master-failover event. SubPlan.prepareRestorePipeline() calls reportedPipelineRunning(pipelineId, false) -> restoreCoordinator(false) on every pipeline restore. By then this same coordinator has already been through a non-RESET cleanup (handleCoordinatorError or cancelCheckpoint), which now leaves the scheduler shut down. So a failed coordinator does get a replacement scheduler, via RESET. Could we reword to state the real invariant: the scheduler stays down after a non-RESET cleanup, and restoreCoordinator() (pipeline restore or master failover) is the single place that brings it back? That is the contract the next person touching this code needs to preserve.
  • Priority: P2 — optional
  • I traced this in the code.
  • When it happens: A streaming job with pipeline restore enabled fails a checkpoint, for example by timeout: handleCoordinatorError(CHECKPOINT_EXPIRED) -> line 381 -> line 1317 shuts the scheduler down with no recreation. The pipeline reaches an end state, and SubPlan.prepareRestorePipeline (SubPlan.java:568) -> restoreCoordinator(false) -> line 733 -> line 1323 gives the same coordinator a new scheduler. No master failover is involved, contrary to the comment.

Issue 2: The failover IT asserts only scheduler.isShutdown(), which shows no replacement pool was created but not that the checkpoint-coordinator-* threads from #12147 have exited.

  • Location: seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/CheckpointCoordinatorFailoverIT.java:405
  • Why it matters: Root cause: isShutdown() becomes true as soon as shutdownNow() returns inside cleanPendingCheckpoint, whether or not the pool's worker threads have terminated.
  • The assertion does discriminate the old behaviour. The pre-fix replacement pool would report false, so the test is a valid regression for the recreate.
  • It does not cover the symptom users reported: a thread that survives cancellation, for example a worker that ignores the interrupt.
  • A thread-name scan would be ambiguous here. Both members run in one JVM, and the first master's coordinator for the same pipeline uses the identical checkpoint-coordinator-<pipelineId>/<jobId> name.

Fix: inside the same Awaitility block, also assert scheduler.isTerminated(). It only becomes true once every worker of this coordinator's pool has exited. The MDC wrapper delegates isTerminated() to the underlying pool, as it does isShutdown().

Separately, testResetRecreatesLiveScheduler does not race an asynchronous error path. On the minimal coordinator the mocked sendOperationToMemberNode returns null, which triggerCheckpoint just collects into the array. CompletableFuture.allOf(completableFutureArray) waits only on the single outer future, so nothing reaches handleCoordinatorError and the reset scheduler is still live when the assertion runs.

  • Evidence: seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/CheckpointCoordinatorFailoverIT.java:406 "A canceled recovered pipeline must not recreate its scheduler");; seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/CheckpointCoordinatorFailoverIT.java:393 .atMost(10, TimeUnit.SECONDS); seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/CheckpointCoordinatorFailoverIT.java:405 scheduler.isShutdown(),
  • Suggested fix: isShutdown() proves no replacement pool was created, which is the right regression for the recreate. The symptom in #12147 is a surviving checkpoint-coordinator-* thread, though, and isShutdown() turns true as soon as shutdownNow() returns, even if a worker has not exited. Since this is already inside an Awaitility block, could we also assert scheduler.isTerminated() here? It only becomes true once all workers of this coordinator's pool are gone, and it avoids a thread-name scan that the first master's same-named threads could pollute.
  • Priority: P2 — optional
  • I traced this in the code.
  • When it happens: State: a coordinator whose scheduler had shutdownNow() called while a worker is still inside a task that does not respond to interrupt. Result: isShutdown() is true and isTerminated() is false, the checkpoint-coordinator-<pipeline>/<job> thread is still alive, and the assertion at line 405 passes.

Issue 3: The cleanPendingCheckpoint Javadoc still says the cleanup always stops and recreates the scheduler, which the new RESET-only guard contradicts.

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/checkpoint/CheckpointCoordinator.java:1322
  • Why it matters: The method Javadoc was not updated with the behaviour change.
  • Root cause: the PR makes recreation conditional on closedReason == CHECKPOINT_COORDINATOR_RESET. The Javadoc directly above (CheckpointCoordinator.java:1265) still lists "Stopping and recreating the scheduler thread pool" as an unconditional step. It still closes with "the coordinator is ready for a clean restart if necessary".
  • Impact: this is the lifecycle method the whole fix hinges on. After a PIPELINE_END, CHECKPOINT_COORDINATOR_COMPLETED or error cleanup the coordinator is deliberately not schedulable until restoreCoordinator() runs, which is the opposite of what the Javadoc says.
  • Fix: change the bullet to "Stopping the scheduler thread pool; a replacement is created only for CHECKPOINT_COORDINATOR_RESET", and qualify the "ready for a clean restart" sentence the same way.
  • Separately, not tied to a line: the PR title uses [Bug][Zeta]. The project commit convention defines only Feature/Fix/Improve/Docs/Test/Chore, so please retitle to [Fix][Zeta] Stop checkpoint scheduler after terminal cleanup so the squash commit follows it.
  • Evidence: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/checkpoint/CheckpointCoordinator.java:1323 scheduler = createScheduler();
  • Suggested fix: With this guard the method Javadoc above is out of date: it still lists "Stopping and recreating the scheduler thread pool" as an unconditional step and ends with "the coordinator is ready for a clean restart if necessary". Could you update the bullet to say the pool is always stopped and only recreated for CHECKPOINT_COORDINATOR_RESET, and qualify the last sentence accordingly? (Unrelated to this line: the title prefix should be [Fix][Zeta]; Bug is not one of the project's commit types.)
  • Priority: P2 — optional
  • I traced this in the code.
  • When it happens: Call cancelCheckpoint() on a coordinator: it runs cleanPendingCheckpoint(PIPELINE_END) at line 1567 and the scheduler stays shut down. testCancelDoesNotRecreateScheduler asserts exactly this and passes at this head. The Javadoc at line 1265 says the pool is recreated.

Issue 4: The cleanPendingCheckpoint Javadoc and the rewritten comment in the trigger lambda no longer describe what the code does.

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/checkpoint/CheckpointCoordinator.java:1318
  • Why it matters: Two comments are out of step with the new lifecycle.
  • The cleanPendingCheckpoint Javadoc still lists "Stopping and recreating the scheduler thread pool" and says the coordinator is "ready for a clean restart if necessary". After this PR that is true only for CHECKPOINT_COORDINATOR_RESET. Every other close reason leaves the scheduler shut down until restoreCoordinator() runs again.
  • The comment inside the trigger lambda was changed to "Preserve failure propagation from a scheduled trigger on shutdown races." That catch (Throwable e) handles every failure of tryTriggerPendingCheckpoint, not just shutdown races. The previous wording explained the real reason: a thrown trigger would silently drop the scheduled checkpoint chain.
  • Impact: this class is concurrency-sensitive. The next maintainer may rely on the Javadoc and assume a scheduler exists after a terminal close, or narrow the catch.
  • Fix: change the Javadoc bullet to say the scheduler is stopped and recreated only for a reset, and restore the original lambda comment.
  • Evidence: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/checkpoint/CheckpointCoordinator.java:568 // Preserve failure propagation from a scheduled trigger on shutdown
  • Suggested fix: The first sentence of this inline comment matches the new guard, but the method Javadoc above still lists "Stopping and recreating the scheduler thread pool" and says the coordinator is "ready for a clean restart if necessary", which now holds only for CHECKPOINT_COORDINATOR_RESET. Could you update that bullet to match? Also, the rewritten comment in the trigger lambda ("Preserve failure propagation from a scheduled trigger on shutdown races") undersells that catch (Throwable e), which handles every trigger failure; the previous wording was more accurate.
  • Priority: P2 — optional
  • I traced this in the code.
  • When it happens: Open CheckpointCoordinator.java at PR head. Follow cleanPendingCheckpoint(CheckpointCloseReason.PIPELINE_END) from :1567: :1317 shuts the scheduler down and :1322 skips createScheduler(), so no scheduler is recreated, while the Javadoc at :1265 says the method performs "Stopping and recreating the scheduler thread pool". Separately, any non-shutdown exception thrown by tryTriggerPendingCheckpoint (:566) lands in the catch whose comment at :568-569 mentions only "shutdown races".

Issue 5: The rewritten comment in the trigger lambda says the catch is about "shutdown races", but the catch handles every Throwable from tryTriggerPendingCheckpoint.

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/checkpoint/CheckpointCoordinator.java:568
  • Why it matters: The replacement comment is less accurate than the one it removed.
  • Root cause: the PR replaces the existing comment ("A thrown trigger would otherwise drop the scheduled checkpoint chain silently; fail the coordinator so the job can handle the error.") with "Preserve failure propagation from a scheduled trigger on shutdown races."
  • The catch (Throwable e) it annotates is not about shutdown. An exception thrown inside a scheduled task is captured in the returned future, which nobody inspects, so the checkpoint chain would stop silently. That is why any trigger failure must be routed to handleCoordinatorError(..., CHECKPOINT_INSIDE_ERROR).
  • Impact: shutdown races are handled by the new outer RejectedExecutionException catch. The inner comment now points readers at the wrong mechanism and loses the reason the catch-all must stay.
  • Fix: restore the original wording on the inner catch and keep the shutdown explanation only on the outer one.
  • Evidence: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/checkpoint/CheckpointCoordinator.java:569 // races.
  • Suggested fix: Nit: this inner catch (Throwable e) is not specific to shutdown races. It is there because an exception thrown inside a scheduled task never surfaces on its own, so any trigger failure has to fail the coordinator. The comment it replaced ("A thrown trigger would otherwise drop the scheduled checkpoint chain silently; fail the coordinator so the job can handle the error.") said that more precisely. Could we keep that wording here and leave the shutdown-race explanation on the outer RejectedExecutionException catch only?
  • Priority: P2 — optional
  • I traced this in the code.
  • When it happens: Read CheckpointCoordinator.java:562-588 at PR head. Any exception from tryTriggerPendingCheckpoint with the scheduler still live (not a shutdown race) is caught at :567 and escalated as CHECKPOINT_INSIDE_ERROR, yet the comment at :568-569 describes the catch only as handling "shutdown races". The actual shutdown-race handler is the outer catch at :580.

On points raised earlier in this thread

  • +1 — I checked this independently: The description of the change matches this head: the removed lines recreated the pool unconditionally after shutdownNow(), and the new code recreates it only for CHECKPOINT_COORDINATOR_RESET through a shared createScheduler(). Two details are imprecise. RESET is not only the master-failover path; SubPlan.prepareRestorePipeline (SubPlan.java:568) also sends it. And a fresh ScheduledThreadPoolExecutor starts worker threads lazily on the first schedule() call, so 'every cancellation adds two idle threads' holds only when something schedules on the replacement late; that was not measured here, and no merge-base run exists.
  • +1 — I checked this independently: The technical statement still holds at this head: terminal close reasons no longer get a replacement scheduler, and both new unit tests are present alongside testDuplicateSchemaChangeAfterCheckpointCompletionIsIgnored. The process statement, that head 8fea514 was a logic-identical rebase of the 2026-09-07 version, cannot be checked from this checkout, which only has head 036319a35c56. I neither confirm nor dispute that part.
  • This looks addressed at the current head: The two follow-up items this review describes are present at the current head: createScheduler() carries a Javadoc, and scheduleTriggerPendingCheckpoint wraps scheduler.schedule(...) in a RejectedExecutionException catch. The timeout-arming call site is guarded too. One imprecision remains: RESET is described as the master-failover path only, while SubPlan.prepareRestorePipeline (SubPlan.java:568) also triggers it.
  • +1 — I checked this independently: The fix summary is accurate at this head: the replacement is created only for RESET, and late scheduling against a shut-down pool is caught and logged. Two caveats. 'Master failover restore' is not the only RESET sender; an ordinary pipeline restore (SubPlan.java:568) reaches restoreCoordinator too. And 'the replacement was never used ... leaked an idle 2-thread pool' is internally inconsistent: a never-used ScheduledThreadPoolExecutor has no worker threads, so the leak requires a late schedule() on the replacement. That path is plausible but was not measured here.
  • +1 — I checked this independently: The carryover test-strength point still stands at this head: no test drives a schedule() call against an already shut-down scheduler, so both new RejectedExecutionException catch branches are unexercised. The production summary (terminal coordinators stay stopped, recovered ones keep a live scheduler) also matches the code and the passing tests.
  • +1 — I checked this independently: The technical summary holds at the current head 036319a35c56: scheduler setup is centralized, recreation is RESET-only, and late terminal scheduling rejection is tolerated. Local evidence is consistent with 'no blocking source issue': both modules build, and the targeted unit tests and failover IT pass. The status of the GitHub 'Build' check on the exact head is not in the supplied material, so that part is neither confirmed nor disputed. The review was written against the older head 1846ff8c.

Review conclusion

Conclusion: final approval remains pending on the previous comments

2. Remaining follow-ups

  • Issue 1: The new comments say only a master-failover reset needs a replacement scheduler, but CHECKPOINT_COORDINATOR_RESET is also how an ordinary pipeline restore revives a coordinator whose scheduler was shut down by an earlier non-RESET cleanup.
  • Issue 2: The failover IT asserts only scheduler.isShutdown(), which shows no replacement pool was created but not that the checkpoint-coordinator-* threads from #12147 have exited.
  • Issue 3: The cleanPendingCheckpoint Javadoc still says the cleanup always stops and recreates the scheduler, which the new RESET-only guard contradicts.
  • Issue 4: The cleanPendingCheckpoint Javadoc and the rewritten comment in the trigger lambda no longer describe what the code does.
  • Issue 5: The rewritten comment in the trigger lambda says the catch is about "shutdown races", but the catch handles every Throwable from tryTriggerPendingCheckpoint.

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

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for syncing the fixture fixes and posting the results. I verified that the fork Build completed successfully on this exact head. The previous connector-startup failures and the old workflow-detection message no longer describe the current head.

What problem does this PR solve?

User problem. Terminal checkpoint cleanup replaces the scheduler it just stopped, allowing a late callback to bring checkpoint threads back after job shutdown.

Change. Recreate the scheduler only during a recoverable coordinator RESET and tolerate a late submission to the stopped executor.

For example, a canceled streaming pipeline keeps its scheduler closed, while the same pipeline can continue taking checkpoints after a recoverable coordinator reset.

1. Code changes

1.1 Core logic

Before, CheckpointCoordinator.java unconditionally created a replacement after shutdownNow. After, CheckpointCoordinator.java:1317-1324 recreates it only for CHECKPOINT_COORDINATOR_RESET; both the delayed trigger and timeout-arm call sites catch rejection at lines 559-586 and 1083-1114.

Pipeline termination → CheckpointManager cancellation → cancelCheckpoint:1562-1572 → cleanPendingCheckpoint:1277 → clear pending state and shut down scheduler → complete CANCELED. Concurrent checkpoint completion/failure also reaches terminal cleanup. In reset, CheckpointManager.restoreCheckpointCoordinator → restoreCoordinator:725-770 → cleanPendingCheckpoint(RESET) → new scheduler → clear shutdown and resume. A late scheduling callback after terminal cleanup sees the closed executor; it cannot create an executor. Valid checkpoint and savepoint callers keep using an active schedule.

1.2 Compatibility

Fully compatible. Writer state, checkpoint format, config, defaults, API and RPC protocol stay the same. Terminal cleanup no longer accepts late scheduling work and RESET retains the existing restore state.

1.3 Performance and side effects

Terminal cleanup drops an unnecessary scheduler allocation and prevents future thread use in that coordinator. The active scheduler keeps the same two threads and removal policy. No new lock, network call or retry is introduced.

1.4 Errors, logging, and findings

The two late-submission catches keep terminal shutdown races from being reported as unexpected task failures. They include job/pipeline context and checkpoint identifier or type. No blocking source issue found.

Issue 1 (Medium, non-blocking). CheckpointCoordinatorTest.java:1139-1203 covers the scheduler lifecycle but does not force either late-submission catch. A controlled barrier callback or executor test double could exercise both with no timing guesses. This is the remaining test suggestion from my prior review.

Issue 2 (Low, non-blocking). CheckpointCoordinator.java:1265 still says cleanup recreates the pool. Specify that recreation belongs to RESET only.

2. Code quality

2.1 Conventions

The helper centralizes thread naming, MDC tracing and the remove-on-cancel policy. Terminal and resetting cases are explicit.

2.2 Test coverage and stability

Stability: Stable. The unit tests at CheckpointCoordinatorTest.java:1139-1203 assert scheduler state after cancel or reset and shut down their own executor in finally. The existing failover IT now polls on observable checkpoint progress and scheduler shutdown at CheckpointCoordinatorFailoverIT.java:383-407 and inspects shutdown before member teardown. Remaining blind spot is a late barrier callback, as in Issue 1.

2.3 Documentation

No user-visible setting or command changes. The English and Chinese guides can keep their existing recovery contract.

3. Architecture

3.1 Change location

A precise lifecycle fix at the component that owns the executor. Global shutdown would not establish the per-pipeline invariant.

3.2 Maintainability

Keep actor-specific cleanup and reset in one helper so the two modes cannot drift.

3.3 Extensibility

Additional lifecycle triggers can use the existing executor while the coordinator is active and respect the same closed boundary.

3.4 Upgrade impact

No state migration or rolling-upgrade instruction is required.

4. Findings summary

# Finding Location Severity
1 Exercise late scheduling during terminal cleanup CheckpointCoordinatorTest.java:1139 Medium
2 Describe RESET-only recreation in the cleanup summary CheckpointCoordinator.java:1265 Low

5. Merge recommendation

Can merge once required maintainer approval is recorded

Blocking items: No blocking source finding. The exact-head fork Build passed. Apache's rollup is empty and GitHub still requires review. A write-capable maintainer can verify the passing fork result and record the effective approval.

Non-blocking suggestions: Issues 1 and 2 can follow separately.

I agree with @SEZ9 that the older SFTP, TiDB and IRIS startup failures did not warrant connector changes in this checkpoint PR. The new head gives the relevant engine suites a completed result.

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

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

@CryoThrust CryoThrust changed the title [Bug][Zeta] Stop checkpoint scheduler after terminal cleanup [Fix][Zeta] Stop checkpoint scheduler after terminal cleanup Nov 18, 2026
@CryoThrust

Copy link
Copy Markdown
Contributor Author

Addressed the remaining points in the existing three checkpoint files:

  • The scheduler and cleanup Javadocs now describe RESET as the revival boundary for both pipeline restore and master failover. Non-reset cleanup leaves the pool stopped until restoreCoordinator() runs. The constructor description also makes lazy worker creation explicit.
  • Restored the explanation for the inner catch (Throwable): any failed scheduled trigger must fail the coordinator, otherwise the checkpoint chain could stop silently. The outer rejection handler remains specific to scheduling against a stopped pool.
  • The recovered streaming coordinator's cancellation check now awaits both isShutdown() and isTerminated() before either member is shut down. This checks that all workers of that specific scheduler have exited, without relying on ambiguous thread names.

On JDK 11, all 19 coordinator unit cases and the selected streaming master-failover IT pass without skips; scoped Spotless, Checkstyle and skip-tests packaging also pass. The title now uses [Fix][Zeta]. The earlier successful fork matrix applies to 036319a35; current-head CI is separate.

@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 clarifying the RESET lifecycle and for checking worker termination in the streaming failover fixture. I rechecked all three files on the new head.

What problem does this PR solve?

User problem. A canceled checkpoint coordinator replaced the scheduler it had just shut down, allowing late task submission to recreate worker threads.

Change. Leave the executor stopped on terminal cleanup and rebuild it during pipeline restore or master failover.

Canceling a recovered job now closes the scheduler and its actual worker threads before either cluster member is shut down.

1. Code changes

1.1 Core logic

Before, cleanPendingCheckpoint always replaced its stopped scheduler. After, CheckpointCoordinator.java:1319-1328 creates a replacement only during RESET, using the same tracing and remove-on-cancel behavior. The trigger callback and barrier timeout submission handle rejection at the stopped scheduler boundary.

CheckpointManager → terminal cancel/completion/failure → cleanPendingCheckpoint → stop scheduler → existing final status and future completion. On restore, CheckpointManager → restoreCoordinator → RESET cleanup → rebuild scheduler and resume pending state and normal triggers. Late callbacks against a stopped scheduler are ignored. A trigger that ran and threw still reaches the original coordinator error path.

1.2 Compatibility

Fully compatible. No persisted data, serialized checkpoint, public API, configuration or default changes.

1.3 Performance and side effects

Terminal cleanup avoids replacement executor allocations and late worker starts. Normal scheduling still uses two lazy workers. No additional network calls, retry or lock contention on the row path.

1.4 Errors, logging, and findings

No blocking source issue. Rejection logs retain job, pipeline and checkpoint type or ID, and the scheduled-task body still propagates real errors. The updated documentation correctly describes both restore paths.

2. Code quality

2.1 Conventions

The comment now explains RESET recreation and the distinction between enqueue failure and trigger failure.

2.2 Test coverage and stability

Stability: Stable. CheckpointCoordinatorTest.java:1139-1202 has deterministic scheduler-state checks after cancel/reset and closes its executor. The existing integration test at CheckpointCoordinatorFailoverIT.java:383-410 awaits both shutdown and termination for the recovered coordinator, before ending members. It polls actual worker lifecycle instead of thread names or a fixed sleep. A deterministic late barrier-submission case remains an optional extension.

2.3 Documentation

No end-user option or command changes. The English and Chinese guides retain their existing checkpoint behavior.

3. Architecture

3.1 Change location

A precise fix in the class that owns scheduling, terminal cleanup and release of pending checkpoint state.

3.2 Maintainability

The shared initializer preserves tracing and policy on reset. The scheduler lifecycle comments are now aligned with use.

3.3 Extensibility

New cleanup reasons can reuse the same lifecycle rule without affecting unrelated executors.

3.4 Upgrade impact

No migration or upgrade changes.

4. Findings summary

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

5. Merge recommendation

Can merge after current-head Build and maintainer approval

Blocking items: No blocking source finding. The green Build on 036319a is superseded by a new code head. The Build for 9df5b7f308 is queued, and Apache shows REVIEW_REQUIRED. Wait for the result for this SHA and write-capable approval.

Non-blocking suggestions: A focused executor or barrier callback regression for late rejection remains optional.

The updated test checks the specific scheduler that needs to terminate. The previous SFTP, TiDB and IRIS diagnosis is for older runs and no connector workaround is needed here.

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

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

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The only remaining technical gate in my previous review was CI. The Build for this unchanged head has now completed successfully; I checked the jobs and found no failed or cancelled jobs. The prior source review has no unresolved blocker, so I am changing my technical conclusion to approve. This updates my earlier queued/running CI statement. My repository permission is READ, so this review does not replace the effective approval or dismissal required from a maintainer with write access. GitHub still requires that maintainer step; branch drift is recorded separately and is not a source objection.

@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 the follow-up. I checked the latest changes at 9df5b7f30833 against my previous review comments.

The scope of this pass is limited to the findings from the previous review; it does not introduce a new set of review items.

Resolved previous findings

  • PR12149-F2 The new comments say only a master-failover reset needs a replacement scheduler, but CHECKPOINT_COORDINATOR_RESET is also how an ordinary pipeline restore revives a coordinator whose scheduler was shut down by an earlier non-RESET cleanup.
  • PR12149-F5 The failover IT asserts only scheduler.isShutdown(), which shows no replacement pool was created but not that the checkpoint-coordinator-* threads from #12147 have exited.
  • PR12149-F6 The cleanPendingCheckpoint Javadoc still says the cleanup always stops and recreates the scheduler, which the new RESET-only guard contradicts.
  • PR12149-F7 The cleanPendingCheckpoint Javadoc and the rewritten comment in the trigger lambda no longer describe what the code does.
  • PR12149-F8 The rewritten comment in the trigger lambda says the catch is about "shutdown races", but the catch handles every Throwable from tryTriggerPendingCheckpoint.

Review conclusion

Conclusion: LGTM, can merge

Nice work — the previous concerns are addressed. Thanks again for the contribution.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks @SEZ9 for confirming the prior findings are resolved. My technical approval already covers this unchanged head, and the exact-head Build remains successful. GitHub's remaining effective approval/merge gate needs a write-capable maintainer; Daniel's READ permission cannot dismiss historical requested changes. No further source change is requested here.

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

@davidzollo
davidzollo added this pull request to the merge queue Nov 24, 2026
Merged via the queue into apache:dev with commit 2847c8c Nov 24, 2026
2 checks passed
Vivek1106-04 added a commit to Vivek1106-04/seatunnel that referenced this pull request Nov 25, 2026
apache#12149 keeps a coordinator's scheduler shut down after non-reset cleanup so
late callbacks cannot arm timers for an ended pipeline. Carry that into the
lease model: terminal cleanup closes the lease and RESET takes a fresh one.
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] checkpoint-coordinator thread survives job cancellation (CANCELED job leaves its coordinator executor alive)

5 participants